MSVC compatibility fixes.
[wine/dcerpc.git] / loader / module.c
blob854802cb02f3f161dd35bd7a2dd6565c0de2094d
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 "heap.h"
36 #include "file.h"
37 #include "module.h"
38 #include "wine/debug.h"
39 #include "wine/server.h"
41 WINE_DEFAULT_DEBUG_CHANNEL(module);
42 WINE_DECLARE_DEBUG_CHANNEL(win32);
43 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
45 WINE_MODREF *MODULE_modref_list = NULL;
47 static WINE_MODREF *exe_modref;
48 static int free_lib_count; /* recursion depth of FreeLibrary calls */
49 static int process_detaching; /* set on process detach to avoid deadlocks with thread detach */
51 static CRITICAL_SECTION loader_section = CRITICAL_SECTION_INIT( "loader_section" );
53 /***********************************************************************
54 * wait_input_idle
56 * Wrapper to call WaitForInputIdle USER function
58 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
60 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
62 HMODULE mod = GetModuleHandleA( "user32.dll" );
63 if (mod)
65 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
66 if (ptr) return ptr( process, timeout );
68 return 0;
72 /*************************************************************************
73 * MODULE32_LookupHMODULE
74 * looks for the referenced HMODULE in the current process
75 * NOTE: Assumes that the process critical section is held!
77 static WINE_MODREF *MODULE32_LookupHMODULE( HMODULE hmod )
79 WINE_MODREF *wm;
81 if (!hmod)
82 return exe_modref;
84 if (!HIWORD(hmod)) {
85 ERR("tried to lookup 0x%04x in win32 module handler!\n",hmod);
86 SetLastError( ERROR_INVALID_HANDLE );
87 return NULL;
89 for ( wm = MODULE_modref_list; wm; wm=wm->next )
90 if (wm->module == hmod)
91 return wm;
92 SetLastError( ERROR_INVALID_HANDLE );
93 return NULL;
96 /*************************************************************************
97 * MODULE_AllocModRef
99 * Allocate a WINE_MODREF structure and add it to the process list
100 * NOTE: Assumes that the process critical section is held!
102 WINE_MODREF *MODULE_AllocModRef( HMODULE hModule, LPCSTR filename )
104 WINE_MODREF *wm;
106 DWORD long_len = strlen( filename );
107 DWORD short_len = GetShortPathNameA( filename, NULL, 0 );
109 if ((wm = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
110 sizeof(*wm) + long_len + short_len + 1 )))
112 wm->module = hModule;
113 wm->tlsindex = -1;
115 wm->filename = wm->data;
116 memcpy( wm->filename, filename, long_len + 1 );
117 if ((wm->modname = strrchr( wm->filename, '\\' ))) wm->modname++;
118 else wm->modname = wm->filename;
120 wm->short_filename = wm->filename + long_len + 1;
121 GetShortPathNameA( wm->filename, wm->short_filename, short_len + 1 );
122 if ((wm->short_modname = strrchr( wm->short_filename, '\\' ))) wm->short_modname++;
123 else wm->short_modname = wm->short_filename;
125 wm->next = MODULE_modref_list;
126 if (wm->next) wm->next->prev = wm;
127 MODULE_modref_list = wm;
129 if (!(RtlImageNtHeader(hModule)->FileHeader.Characteristics & IMAGE_FILE_DLL))
131 if (!exe_modref) exe_modref = wm;
132 else FIXME( "Trying to load second .EXE file: %s\n", filename );
135 return wm;
138 /*************************************************************************
139 * MODULE_InitDLL
141 static BOOL MODULE_InitDLL( WINE_MODREF *wm, DWORD type, LPVOID lpReserved )
143 BOOL retv = TRUE;
145 static LPCSTR typeName[] = { "PROCESS_DETACH", "PROCESS_ATTACH",
146 "THREAD_ATTACH", "THREAD_DETACH" };
147 assert( wm );
149 /* Skip calls for modules loaded with special load flags */
151 if (wm->flags & WINE_MODREF_DONT_RESOLVE_REFS) return TRUE;
153 TRACE("(%s,%s,%p) - CALL\n", wm->modname, typeName[type], lpReserved );
155 /* Call the initialization routine */
156 retv = PE_InitDLL( wm->module, type, lpReserved );
158 /* The state of the module list may have changed due to the call
159 to PE_InitDLL. We cannot assume that this module has not been
160 deleted. */
161 TRACE("(%p,%s,%p) - RETURN %d\n", wm, typeName[type], lpReserved, retv );
163 return retv;
166 /*************************************************************************
167 * MODULE_DllProcessAttach
169 * Send the process attach notification to all DLLs the given module
170 * depends on (recursively). This is somewhat complicated due to the fact that
172 * - we have to respect the module dependencies, i.e. modules implicitly
173 * referenced by another module have to be initialized before the module
174 * itself can be initialized
176 * - the initialization routine of a DLL can itself call LoadLibrary,
177 * thereby introducing a whole new set of dependencies (even involving
178 * the 'old' modules) at any time during the whole process
180 * (Note that this routine can be recursively entered not only directly
181 * from itself, but also via LoadLibrary from one of the called initialization
182 * routines.)
184 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
185 * the process *detach* notifications to be sent in the correct order.
186 * This must not only take into account module dependencies, but also
187 * 'hidden' dependencies created by modules calling LoadLibrary in their
188 * attach notification routine.
190 * The strategy is rather simple: we move a WINE_MODREF to the head of the
191 * list after the attach notification has returned. This implies that the
192 * detach notifications are called in the reverse of the sequence the attach
193 * notifications *returned*.
195 BOOL MODULE_DllProcessAttach( WINE_MODREF *wm, LPVOID lpReserved )
197 BOOL retv = TRUE;
198 int i;
200 RtlEnterCriticalSection( &loader_section );
202 if (!wm)
204 wm = exe_modref;
205 PE_InitTls();
207 assert( wm );
209 /* prevent infinite recursion in case of cyclical dependencies */
210 if ( ( wm->flags & WINE_MODREF_MARKER )
211 || ( wm->flags & WINE_MODREF_PROCESS_ATTACHED ) )
212 goto done;
214 TRACE("(%s,%p) - START\n", wm->modname, lpReserved );
216 /* Tag current MODREF to prevent recursive loop */
217 wm->flags |= WINE_MODREF_MARKER;
219 /* Recursively attach all DLLs this one depends on */
220 for ( i = 0; retv && i < wm->nDeps; i++ )
221 if ( wm->deps[i] )
222 retv = MODULE_DllProcessAttach( wm->deps[i], lpReserved );
224 /* Call DLL entry point */
225 if ( retv )
227 retv = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
228 if ( retv )
229 wm->flags |= WINE_MODREF_PROCESS_ATTACHED;
232 /* Re-insert MODREF at head of list */
233 if ( retv && wm->prev )
235 wm->prev->next = wm->next;
236 if ( wm->next ) wm->next->prev = wm->prev;
238 wm->prev = NULL;
239 wm->next = MODULE_modref_list;
240 MODULE_modref_list = wm->next->prev = wm;
243 /* Remove recursion flag */
244 wm->flags &= ~WINE_MODREF_MARKER;
246 TRACE("(%s,%p) - END\n", wm->modname, lpReserved );
248 done:
249 RtlLeaveCriticalSection( &loader_section );
250 return retv;
253 /*************************************************************************
254 * MODULE_DllProcessDetach
256 * Send DLL process detach notifications. See the comment about calling
257 * sequence at MODULE_DllProcessAttach. Unless the bForceDetach flag
258 * is set, only DLLs with zero refcount are notified.
260 void MODULE_DllProcessDetach( BOOL bForceDetach, LPVOID lpReserved )
262 WINE_MODREF *wm;
264 RtlEnterCriticalSection( &loader_section );
265 if (bForceDetach) process_detaching = 1;
268 for ( wm = MODULE_modref_list; wm; wm = wm->next )
270 /* Check whether to detach this DLL */
271 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
272 continue;
273 if ( wm->refCount > 0 && !bForceDetach )
274 continue;
276 /* Call detach notification */
277 wm->flags &= ~WINE_MODREF_PROCESS_ATTACHED;
278 MODULE_InitDLL( wm, DLL_PROCESS_DETACH, lpReserved );
280 /* Restart at head of WINE_MODREF list, as entries might have
281 been added and/or removed while performing the call ... */
282 break;
284 } while ( wm );
286 RtlLeaveCriticalSection( &loader_section );
289 /*************************************************************************
290 * MODULE_DllThreadAttach
292 * Send DLL thread attach notifications. These are sent in the
293 * reverse sequence of process detach notification.
296 void MODULE_DllThreadAttach( LPVOID lpReserved )
298 WINE_MODREF *wm;
300 /* don't do any attach calls if process is exiting */
301 if (process_detaching) return;
302 /* FIXME: there is still a race here */
304 RtlEnterCriticalSection( &loader_section );
306 PE_InitTls();
308 for ( wm = MODULE_modref_list; wm; wm = wm->next )
309 if ( !wm->next )
310 break;
312 for ( ; wm; wm = wm->prev )
314 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
315 continue;
316 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
317 continue;
319 MODULE_InitDLL( wm, DLL_THREAD_ATTACH, lpReserved );
322 RtlLeaveCriticalSection( &loader_section );
325 /*************************************************************************
326 * MODULE_DllThreadDetach
328 * Send DLL thread detach notifications. These are sent in the
329 * same sequence as process detach notification.
332 void MODULE_DllThreadDetach( LPVOID lpReserved )
334 WINE_MODREF *wm;
336 /* don't do any detach calls if process is exiting */
337 if (process_detaching) return;
338 /* FIXME: there is still a race here */
340 RtlEnterCriticalSection( &loader_section );
342 for ( wm = MODULE_modref_list; wm; wm = wm->next )
344 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
345 continue;
346 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
347 continue;
349 MODULE_InitDLL( wm, DLL_THREAD_DETACH, lpReserved );
352 RtlLeaveCriticalSection( &loader_section );
355 /****************************************************************************
356 * DisableThreadLibraryCalls (KERNEL32.@)
358 * Don't call DllEntryPoint for DLL_THREAD_{ATTACH,DETACH} if set.
360 BOOL WINAPI DisableThreadLibraryCalls( HMODULE hModule )
362 WINE_MODREF *wm;
363 BOOL retval = TRUE;
365 RtlEnterCriticalSection( &loader_section );
367 wm = MODULE32_LookupHMODULE( hModule );
368 if ( !wm )
369 retval = FALSE;
370 else
371 wm->flags |= WINE_MODREF_NO_DLL_CALLS;
373 RtlLeaveCriticalSection( &loader_section );
375 return retval;
379 /***********************************************************************
380 * MODULE_CreateDummyModule
382 * Create a dummy NE module for Win32 or Winelib.
384 HMODULE16 MODULE_CreateDummyModule( LPCSTR filename, HMODULE module32 )
386 HMODULE16 hModule;
387 NE_MODULE *pModule;
388 SEGTABLEENTRY *pSegment;
389 char *pStr,*s;
390 unsigned int len;
391 const char* basename;
392 OFSTRUCT *ofs;
393 int of_size, size;
395 /* Extract base filename */
396 basename = strrchr(filename, '\\');
397 if (!basename) basename = filename;
398 else basename++;
399 len = strlen(basename);
400 if ((s = strchr(basename, '.'))) len = s - basename;
402 /* Allocate module */
403 of_size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName)
404 + strlen(filename) + 1;
405 size = sizeof(NE_MODULE) +
406 /* loaded file info */
407 ((of_size + 3) & ~3) +
408 /* segment table: DS,CS */
409 2 * sizeof(SEGTABLEENTRY) +
410 /* name table */
411 len + 2 +
412 /* several empty tables */
415 hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
416 if (!hModule) return (HMODULE16)11; /* invalid exe */
418 FarSetOwner16( hModule, hModule );
419 pModule = (NE_MODULE *)GlobalLock16( hModule );
421 /* Set all used entries */
422 pModule->magic = IMAGE_OS2_SIGNATURE;
423 pModule->count = 1;
424 pModule->next = 0;
425 pModule->flags = 0;
426 pModule->dgroup = 0;
427 pModule->ss = 1;
428 pModule->cs = 2;
429 pModule->heap_size = 0;
430 pModule->stack_size = 0;
431 pModule->seg_count = 2;
432 pModule->modref_count = 0;
433 pModule->nrname_size = 0;
434 pModule->fileinfo = sizeof(NE_MODULE);
435 pModule->os_flags = NE_OSFLAGS_WINDOWS;
436 pModule->self = hModule;
437 pModule->module32 = module32;
439 /* Set version and flags */
440 if (module32)
442 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module32 );
443 pModule->expected_version = ((nt->OptionalHeader.MajorSubsystemVersion & 0xff) << 8 ) |
444 (nt->OptionalHeader.MinorSubsystemVersion & 0xff);
445 pModule->flags |= NE_FFLAGS_WIN32;
446 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
447 pModule->flags |= NE_FFLAGS_LIBMODULE | NE_FFLAGS_SINGLEDATA;
450 /* Set loaded file information */
451 ofs = (OFSTRUCT *)(pModule + 1);
452 memset( ofs, 0, of_size );
453 ofs->cBytes = of_size < 256 ? of_size : 255; /* FIXME */
454 strcpy( ofs->szPathName, filename );
456 pSegment = (SEGTABLEENTRY*)((char*)(pModule + 1) + ((of_size + 3) & ~3));
457 pModule->seg_table = (int)pSegment - (int)pModule;
458 /* Data segment */
459 pSegment->size = 0;
460 pSegment->flags = NE_SEGFLAGS_DATA;
461 pSegment->minsize = 0x1000;
462 pSegment++;
463 /* Code segment */
464 pSegment->flags = 0;
465 pSegment++;
467 /* Module name */
468 pStr = (char *)pSegment;
469 pModule->name_table = (int)pStr - (int)pModule;
470 assert(len<256);
471 *pStr = len;
472 lstrcpynA( pStr+1, basename, len+1 );
473 pStr += len+2;
475 /* All tables zero terminated */
476 pModule->res_table = pModule->import_table = pModule->entry_table =
477 (int)pStr - (int)pModule;
479 NE_RegisterModule( pModule );
480 return hModule;
484 /**********************************************************************
485 * MODULE_FindModule
487 * Find a (loaded) win32 module depending on path
489 * RETURNS
490 * the module handle if found
491 * 0 if not
493 WINE_MODREF *MODULE_FindModule(
494 LPCSTR path /* [in] pathname of module/library to be found */
496 WINE_MODREF *wm;
497 char dllname[260], *p;
499 /* Append .DLL to name if no extension present */
500 strcpy( dllname, path );
501 if (!(p = strrchr( dllname, '.')) || strchr( p, '/' ) || strchr( p, '\\'))
502 strcat( dllname, ".DLL" );
504 for ( wm = MODULE_modref_list; wm; wm = wm->next )
506 if ( !FILE_strcasecmp( dllname, wm->modname ) )
507 break;
508 if ( !FILE_strcasecmp( dllname, wm->filename ) )
509 break;
510 if ( !FILE_strcasecmp( dllname, wm->short_modname ) )
511 break;
512 if ( !FILE_strcasecmp( dllname, wm->short_filename ) )
513 break;
516 return wm;
520 /* Check whether a file is an OS/2 or a very old Windows executable
521 * by testing on import of KERNEL.
523 * FIXME: is reading the module imports the only way of discerning
524 * old Windows binaries from OS/2 ones ? At least it seems so...
526 static enum binary_type MODULE_Decide_OS2_OldWin(HANDLE hfile, const IMAGE_DOS_HEADER *mz,
527 const IMAGE_OS2_HEADER *ne)
529 DWORD currpos = SetFilePointer( hfile, 0, NULL, SEEK_CUR);
530 enum binary_type ret = BINARY_OS216;
531 LPWORD modtab = NULL;
532 LPSTR nametab = NULL;
533 DWORD len;
534 int i;
536 /* read modref table */
537 if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_modtab, NULL, SEEK_SET ) == -1)
538 || (!(modtab = HeapAlloc( GetProcessHeap(), 0, ne->ne_cmod*sizeof(WORD))))
539 || (!(ReadFile(hfile, modtab, ne->ne_cmod*sizeof(WORD), &len, NULL)))
540 || (len != ne->ne_cmod*sizeof(WORD)) )
541 goto broken;
543 /* read imported names table */
544 if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_imptab, NULL, SEEK_SET ) == -1)
545 || (!(nametab = HeapAlloc( GetProcessHeap(), 0, ne->ne_enttab - ne->ne_imptab)))
546 || (!(ReadFile(hfile, nametab, ne->ne_enttab - ne->ne_imptab, &len, NULL)))
547 || (len != ne->ne_enttab - ne->ne_imptab) )
548 goto broken;
550 for (i=0; i < ne->ne_cmod; i++)
552 LPSTR module = &nametab[modtab[i]];
553 TRACE("modref: %.*s\n", module[0], &module[1]);
554 if (!(strncmp(&module[1], "KERNEL", module[0])))
555 { /* very old Windows file */
556 MESSAGE("This seems to be a very old (pre-3.0) Windows executable. Expect crashes, especially if this is a real-mode binary !\n");
557 ret = BINARY_WIN16;
558 goto good;
562 broken:
563 ERR("Hmm, an error occurred. Is this binary file broken ?\n");
565 good:
566 HeapFree( GetProcessHeap(), 0, modtab);
567 HeapFree( GetProcessHeap(), 0, nametab);
568 SetFilePointer( hfile, currpos, NULL, SEEK_SET); /* restore filepos */
569 return ret;
572 /***********************************************************************
573 * MODULE_GetBinaryType
575 enum binary_type MODULE_GetBinaryType( HANDLE hfile )
577 union
579 struct
581 unsigned char magic[4];
582 unsigned char ignored[12];
583 unsigned short type;
584 } elf;
585 IMAGE_DOS_HEADER mz;
586 } header;
588 char magic[4];
589 DWORD len;
591 /* Seek to the start of the file and read the header information. */
592 if (SetFilePointer( hfile, 0, NULL, SEEK_SET ) == -1)
593 return BINARY_UNKNOWN;
594 if (!ReadFile( hfile, &header, sizeof(header), &len, NULL ) || len != sizeof(header))
595 return BINARY_UNKNOWN;
597 if (!memcmp( header.elf.magic, "\177ELF", 4 ))
599 /* FIXME: we don't bother to check byte order, architecture, etc. */
600 switch(header.elf.type)
602 case 2: return BINARY_UNIX_EXE;
603 case 3: return BINARY_UNIX_LIB;
605 return BINARY_UNKNOWN;
608 /* Not ELF, try DOS */
610 if (header.mz.e_magic == IMAGE_DOS_SIGNATURE)
612 /* We do have a DOS image so we will now try to seek into
613 * the file by the amount indicated by the field
614 * "Offset to extended header" and read in the
615 * "magic" field information at that location.
616 * This will tell us if there is more header information
617 * to read or not.
619 /* But before we do we will make sure that header
620 * structure encompasses the "Offset to extended header"
621 * field.
623 if ((header.mz.e_cparhdr << 4) < sizeof(IMAGE_DOS_HEADER))
624 return BINARY_DOS;
625 if (header.mz.e_crlc && (header.mz.e_lfarlc < sizeof(IMAGE_DOS_HEADER)))
626 return BINARY_DOS;
627 if (header.mz.e_lfanew < sizeof(IMAGE_DOS_HEADER))
628 return BINARY_DOS;
629 if (SetFilePointer( hfile, header.mz.e_lfanew, NULL, SEEK_SET ) == -1)
630 return BINARY_DOS;
631 if (!ReadFile( hfile, magic, sizeof(magic), &len, NULL ) || len != sizeof(magic))
632 return BINARY_DOS;
634 /* Reading the magic field succeeded so
635 * we will try to determine what type it is.
637 if (!memcmp( magic, "PE\0\0", 4 ))
639 IMAGE_FILE_HEADER FileHeader;
641 if (ReadFile( hfile, &FileHeader, sizeof(FileHeader), &len, NULL ) && len == sizeof(FileHeader))
643 if (FileHeader.Characteristics & IMAGE_FILE_DLL) return BINARY_PE_DLL;
644 return BINARY_PE_EXE;
646 return BINARY_DOS;
649 if (!memcmp( magic, "NE", 2 ))
651 /* This is a Windows executable (NE) header. This can
652 * mean either a 16-bit OS/2 or a 16-bit Windows or even a
653 * DOS program (running under a DOS extender). To decide
654 * which, we'll have to read the NE header.
656 IMAGE_OS2_HEADER ne;
657 if ( SetFilePointer( hfile, header.mz.e_lfanew, NULL, SEEK_SET ) != -1
658 && ReadFile( hfile, &ne, sizeof(ne), &len, NULL )
659 && len == sizeof(ne) )
661 switch ( ne.ne_exetyp )
663 case 2: return BINARY_WIN16;
664 case 5: return BINARY_DOS;
665 default: return MODULE_Decide_OS2_OldWin(hfile, &header.mz, &ne);
668 /* Couldn't read header, so abort. */
669 return BINARY_DOS;
672 /* Unknown extended header, but this file is nonetheless DOS-executable. */
673 return BINARY_DOS;
676 return BINARY_UNKNOWN;
679 /***********************************************************************
680 * GetBinaryTypeA [KERNEL32.@]
681 * GetBinaryType [KERNEL32.@]
683 * The GetBinaryType function determines whether a file is executable
684 * or not and if it is it returns what type of executable it is.
685 * The type of executable is a property that determines in which
686 * subsystem an executable file runs under.
688 * Binary types returned:
689 * SCS_32BIT_BINARY: A Win32 based application
690 * SCS_DOS_BINARY: An MS-Dos based application
691 * SCS_WOW_BINARY: A Win16 based application
692 * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
693 * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
694 * SCS_OS216_BINARY: A 16bit OS/2 based application
696 * Returns TRUE if the file is an executable in which case
697 * the value pointed by lpBinaryType is set.
698 * Returns FALSE if the file is not an executable or if the function fails.
700 * To do so it opens the file and reads in the header information
701 * if the extended header information is not present it will
702 * assume that the file is a DOS executable.
703 * If the extended header information is present it will
704 * determine if the file is a 16 or 32 bit Windows executable
705 * by check the flags in the header.
707 * Note that .COM and .PIF files are only recognized by their
708 * file name extension; but Windows does it the same way ...
710 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
712 BOOL ret = FALSE;
713 HANDLE hfile;
714 char *ptr;
716 TRACE_(win32)("%s\n", lpApplicationName );
718 /* Sanity check.
720 if ( lpApplicationName == NULL || lpBinaryType == NULL )
721 return FALSE;
723 /* Open the file indicated by lpApplicationName for reading.
725 hfile = CreateFileA( lpApplicationName, GENERIC_READ, FILE_SHARE_READ,
726 NULL, OPEN_EXISTING, 0, 0 );
727 if ( hfile == INVALID_HANDLE_VALUE )
728 return FALSE;
730 /* Check binary type
732 switch(MODULE_GetBinaryType( hfile ))
734 case BINARY_UNKNOWN:
735 /* try to determine from file name */
736 ptr = strrchr( lpApplicationName, '.' );
737 if (!ptr) break;
738 if (!FILE_strcasecmp( ptr, ".COM" ))
740 *lpBinaryType = SCS_DOS_BINARY;
741 ret = TRUE;
743 else if (!FILE_strcasecmp( ptr, ".PIF" ))
745 *lpBinaryType = SCS_PIF_BINARY;
746 ret = TRUE;
748 break;
749 case BINARY_PE_EXE:
750 case BINARY_PE_DLL:
751 *lpBinaryType = SCS_32BIT_BINARY;
752 ret = TRUE;
753 break;
754 case BINARY_WIN16:
755 *lpBinaryType = SCS_WOW_BINARY;
756 ret = TRUE;
757 break;
758 case BINARY_OS216:
759 *lpBinaryType = SCS_OS216_BINARY;
760 ret = TRUE;
761 break;
762 case BINARY_DOS:
763 *lpBinaryType = SCS_DOS_BINARY;
764 ret = TRUE;
765 break;
766 case BINARY_UNIX_EXE:
767 case BINARY_UNIX_LIB:
768 ret = FALSE;
769 break;
772 CloseHandle( hfile );
773 return ret;
776 /***********************************************************************
777 * GetBinaryTypeW [KERNEL32.@]
779 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
781 BOOL ret = FALSE;
782 LPSTR strNew = NULL;
784 TRACE_(win32)("%s\n", debugstr_w(lpApplicationName) );
786 /* Sanity check.
788 if ( lpApplicationName == NULL || lpBinaryType == NULL )
789 return FALSE;
791 /* Convert the wide string to a ascii string.
793 strNew = HEAP_strdupWtoA( GetProcessHeap(), 0, lpApplicationName );
795 if ( strNew != NULL )
797 ret = GetBinaryTypeA( strNew, lpBinaryType );
799 /* Free the allocated string.
801 HeapFree( GetProcessHeap(), 0, strNew );
804 return ret;
808 /***********************************************************************
809 * WinExec (KERNEL.166)
810 * WinExec16 (KERNEL32.@)
812 HINSTANCE16 WINAPI WinExec16( LPCSTR lpCmdLine, UINT16 nCmdShow )
814 LPCSTR p, args = NULL;
815 LPCSTR name_beg, name_end;
816 LPSTR name, cmdline;
817 int arglen;
818 HINSTANCE16 ret;
819 char buffer[MAX_PATH];
821 if (*lpCmdLine == '"') /* has to be only one and only at beginning ! */
823 name_beg = lpCmdLine+1;
824 p = strchr ( lpCmdLine+1, '"' );
825 if (p)
827 name_end = p;
828 args = strchr ( p, ' ' );
830 else /* yes, even valid with trailing '"' missing */
831 name_end = lpCmdLine+strlen(lpCmdLine);
833 else
835 name_beg = lpCmdLine;
836 args = strchr( lpCmdLine, ' ' );
837 name_end = args ? args : lpCmdLine+strlen(lpCmdLine);
840 if ((name_beg == lpCmdLine) && (!args))
841 { /* just use the original cmdline string as file name */
842 name = (LPSTR)lpCmdLine;
844 else
846 if (!(name = HeapAlloc( GetProcessHeap(), 0, name_end - name_beg + 1 )))
847 return ERROR_NOT_ENOUGH_MEMORY;
848 memcpy( name, name_beg, name_end - name_beg );
849 name[name_end - name_beg] = '\0';
852 if (args)
854 args++;
855 arglen = strlen(args);
856 cmdline = HeapAlloc( GetProcessHeap(), 0, 2 + arglen );
857 cmdline[0] = (BYTE)arglen;
858 strcpy( cmdline + 1, args );
860 else
862 cmdline = HeapAlloc( GetProcessHeap(), 0, 2 );
863 cmdline[0] = cmdline[1] = 0;
866 TRACE("name: '%s', cmdline: '%.*s'\n", name, cmdline[0], &cmdline[1]);
868 if (SearchPathA( NULL, name, ".exe", sizeof(buffer), buffer, NULL ))
870 LOADPARAMS16 params;
871 WORD showCmd[2];
872 showCmd[0] = 2;
873 showCmd[1] = nCmdShow;
875 params.hEnvironment = 0;
876 params.cmdLine = MapLS( cmdline );
877 params.showCmd = MapLS( showCmd );
878 params.reserved = 0;
880 ret = LoadModule16( buffer, &params );
881 UnMapLS( params.cmdLine );
882 UnMapLS( params.showCmd );
884 else ret = GetLastError();
886 HeapFree( GetProcessHeap(), 0, cmdline );
887 if (name != lpCmdLine) HeapFree( GetProcessHeap(), 0, name );
889 if (ret == 21) /* 32-bit module */
891 DWORD count;
892 ReleaseThunkLock( &count );
893 ret = LOWORD( WinExec( lpCmdLine, nCmdShow ) );
894 RestoreThunkLock( count );
896 return ret;
899 /***********************************************************************
900 * WinExec (KERNEL32.@)
902 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
904 PROCESS_INFORMATION info;
905 STARTUPINFOA startup;
906 char *cmdline;
907 UINT ret;
909 memset( &startup, 0, sizeof(startup) );
910 startup.cb = sizeof(startup);
911 startup.dwFlags = STARTF_USESHOWWINDOW;
912 startup.wShowWindow = nCmdShow;
914 /* cmdline needs to be writeable for CreateProcess */
915 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
916 strcpy( cmdline, lpCmdLine );
918 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
919 0, NULL, NULL, &startup, &info ))
921 /* Give 30 seconds to the app to come up */
922 if (wait_input_idle( info.hProcess, 30000 ) == 0xFFFFFFFF)
923 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
924 ret = 33;
925 /* Close off the handles */
926 CloseHandle( info.hThread );
927 CloseHandle( info.hProcess );
929 else if ((ret = GetLastError()) >= 32)
931 FIXME("Strange error set by CreateProcess: %d\n", ret );
932 ret = 11;
934 HeapFree( GetProcessHeap(), 0, cmdline );
935 return ret;
938 /**********************************************************************
939 * LoadModule (KERNEL32.@)
941 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
943 LOADPARAMS *params = (LOADPARAMS *)paramBlock;
944 PROCESS_INFORMATION info;
945 STARTUPINFOA startup;
946 HINSTANCE hInstance;
947 LPSTR cmdline, p;
948 char filename[MAX_PATH];
949 BYTE len;
951 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
953 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
954 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
955 return (HINSTANCE)GetLastError();
957 len = (BYTE)params->lpCmdLine[0];
958 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
959 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
961 strcpy( cmdline, filename );
962 p = cmdline + strlen(cmdline);
963 *p++ = ' ';
964 memcpy( p, params->lpCmdLine + 1, len );
965 p[len] = 0;
967 memset( &startup, 0, sizeof(startup) );
968 startup.cb = sizeof(startup);
969 if (params->lpCmdShow)
971 startup.dwFlags = STARTF_USESHOWWINDOW;
972 startup.wShowWindow = params->lpCmdShow[1];
975 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
976 params->lpEnvAddress, NULL, &startup, &info ))
978 /* Give 30 seconds to the app to come up */
979 if (wait_input_idle( info.hProcess, 30000 ) == 0xFFFFFFFF )
980 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
981 hInstance = (HINSTANCE)33;
982 /* Close off the handles */
983 CloseHandle( info.hThread );
984 CloseHandle( info.hProcess );
986 else if ((hInstance = (HINSTANCE)GetLastError()) >= (HINSTANCE)32)
988 FIXME("Strange error set by CreateProcess: %d\n", hInstance );
989 hInstance = (HINSTANCE)11;
992 HeapFree( GetProcessHeap(), 0, cmdline );
993 return hInstance;
997 /***********************************************************************
998 * GetModuleHandleA (KERNEL32.@)
999 * GetModuleHandle32 (KERNEL.488)
1001 HMODULE WINAPI GetModuleHandleA(LPCSTR module)
1003 WINE_MODREF *wm;
1005 if ( module == NULL )
1006 wm = exe_modref;
1007 else
1008 wm = MODULE_FindModule( module );
1010 return wm? wm->module : 0;
1013 /***********************************************************************
1014 * GetModuleHandleW (KERNEL32.@)
1016 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
1018 HMODULE hModule;
1019 LPSTR modulea = HEAP_strdupWtoA( GetProcessHeap(), 0, module );
1020 hModule = GetModuleHandleA( modulea );
1021 HeapFree( GetProcessHeap(), 0, modulea );
1022 return hModule;
1026 /***********************************************************************
1027 * GetModuleFileNameA (KERNEL32.@)
1028 * GetModuleFileName32 (KERNEL.487)
1030 * GetModuleFileNameA seems to *always* return the long path;
1031 * it's only GetModuleFileName16 that decides between short/long path
1032 * by checking if exe version >= 4.0.
1033 * (SDK docu doesn't mention this)
1035 DWORD WINAPI GetModuleFileNameA(
1036 HMODULE hModule, /* [in] module handle (32bit) */
1037 LPSTR lpFileName, /* [out] filenamebuffer */
1038 DWORD size ) /* [in] size of filenamebuffer */
1040 RtlEnterCriticalSection( &loader_section );
1042 lpFileName[0] = 0;
1043 if (!hModule && !(NtCurrentTeb()->tibflags & TEBF_WIN32))
1045 /* 16-bit task - get current NE module name */
1046 NE_MODULE *pModule = NE_GetPtr( GetCurrentTask() );
1047 if (pModule) GetLongPathNameA(NE_MODULE_NAME(pModule), lpFileName, size);
1049 else
1051 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1052 if (wm) lstrcpynA( lpFileName, wm->filename, size );
1055 RtlLeaveCriticalSection( &loader_section );
1056 TRACE("%s\n", lpFileName );
1057 return strlen(lpFileName);
1061 /***********************************************************************
1062 * GetModuleFileNameW (KERNEL32.@)
1064 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName, DWORD size )
1066 LPSTR fnA = HeapAlloc( GetProcessHeap(), 0, size * 2 );
1067 if (!fnA) return 0;
1068 GetModuleFileNameA( hModule, fnA, size * 2 );
1069 if (size > 0 && !MultiByteToWideChar( CP_ACP, 0, fnA, -1, lpFileName, size ))
1070 lpFileName[size-1] = 0;
1071 HeapFree( GetProcessHeap(), 0, fnA );
1072 return strlenW(lpFileName);
1076 /***********************************************************************
1077 * LoadLibraryExA (KERNEL32.@)
1079 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
1081 WINE_MODREF *wm;
1083 if(!libname)
1085 SetLastError(ERROR_INVALID_PARAMETER);
1086 return 0;
1089 if (flags & LOAD_LIBRARY_AS_DATAFILE)
1091 char filename[256];
1092 HMODULE hmod = 0;
1094 /* This method allows searching for the 'native' libraries only */
1095 if (SearchPathA( NULL, libname, ".dll", sizeof(filename), filename, NULL ))
1097 /* FIXME: maybe we should use the hfile parameter instead */
1098 HANDLE hFile = CreateFileA( filename, GENERIC_READ, FILE_SHARE_READ,
1099 NULL, OPEN_EXISTING, 0, 0 );
1100 if (hFile != INVALID_HANDLE_VALUE)
1102 HANDLE mapping;
1103 switch (MODULE_GetBinaryType( hFile ))
1105 case BINARY_PE_EXE:
1106 case BINARY_PE_DLL:
1107 mapping = CreateFileMappingA( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
1108 if (mapping)
1110 hmod = (HMODULE)MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
1111 CloseHandle( mapping );
1113 break;
1114 default:
1115 break;
1117 CloseHandle( hFile );
1119 if (hmod) return (HMODULE)((ULONG_PTR)hmod + 1);
1121 flags |= DONT_RESOLVE_DLL_REFERENCES; /* Just in case */
1122 /* Fallback to normal behaviour */
1125 RtlEnterCriticalSection( &loader_section );
1127 wm = MODULE_LoadLibraryExA( libname, hfile, flags );
1128 if ( wm )
1130 if ( !MODULE_DllProcessAttach( wm, NULL ) )
1132 WARN_(module)("Attach failed for module '%s'.\n", libname);
1133 MODULE_FreeLibrary(wm);
1134 SetLastError(ERROR_DLL_INIT_FAILED);
1135 wm = NULL;
1139 RtlLeaveCriticalSection( &loader_section );
1140 return wm ? wm->module : 0;
1143 /***********************************************************************
1144 * allocate_lib_dir
1146 * helper for MODULE_LoadLibraryExA. Allocate space to hold the directory
1147 * portion of the provided name and put the name in it.
1150 static LPCSTR allocate_lib_dir(LPCSTR libname)
1152 LPCSTR p, pmax;
1153 LPSTR result;
1154 int length;
1156 pmax = libname;
1157 if ((p = strrchr( pmax, '\\' ))) pmax = p + 1;
1158 if ((p = strrchr( pmax, '/' ))) pmax = p + 1; /* Naughty. MSDN says don't */
1159 if (pmax == libname && pmax[0] && pmax[1] == ':') pmax += 2;
1161 length = pmax - libname;
1163 result = HeapAlloc (GetProcessHeap(), 0, length+1);
1165 if (result)
1167 strncpy (result, libname, length);
1168 result [length] = '\0';
1171 return result;
1174 /***********************************************************************
1175 * MODULE_LoadLibraryExA (internal)
1177 * Load a PE style module according to the load order.
1179 * The HFILE parameter is not used and marked reserved in the SDK. I can
1180 * only guess that it should force a file to be mapped, but I rather
1181 * ignore the parameter because it would be extremely difficult to
1182 * integrate this with different types of module representations.
1184 * libdir is used to support LOAD_WITH_ALTERED_SEARCH_PATH during the recursion
1185 * on this function. When first called from LoadLibraryExA it will be
1186 * NULL but thereafter it may point to a buffer containing the path
1187 * portion of the library name. Note that the recursion all occurs
1188 * within a Critical section (see LoadLibraryExA) so the use of a
1189 * static is acceptable.
1190 * (We have to use a static variable at some point anyway, to pass the
1191 * information from BUILTIN32_dlopen through dlopen and the builtin's
1192 * init function into load_library).
1193 * allocated_libdir is TRUE in the stack frame that allocated libdir
1195 WINE_MODREF *MODULE_LoadLibraryExA( LPCSTR libname, HANDLE hfile, DWORD flags )
1197 DWORD err = GetLastError();
1198 WINE_MODREF *pwm;
1199 int i;
1200 enum loadorder_type loadorder[LOADORDER_NTYPES];
1201 LPSTR filename;
1202 const char *filetype = "";
1203 DWORD found;
1204 BOOL allocated_libdir = FALSE;
1205 static LPCSTR libdir = NULL; /* See above */
1207 if ( !libname ) return NULL;
1209 filename = HeapAlloc ( GetProcessHeap(), 0, MAX_PATH + 1 );
1210 if ( !filename ) return NULL;
1211 *filename = 0; /* Just in case we don't set it before goto error */
1213 RtlEnterCriticalSection( &loader_section );
1215 if ((flags & LOAD_WITH_ALTERED_SEARCH_PATH) && FILE_contains_path(libname))
1217 if (!(libdir = allocate_lib_dir(libname))) goto error;
1218 allocated_libdir = TRUE;
1221 if (!libdir || allocated_libdir)
1222 found = SearchPathA(NULL, libname, ".dll", MAX_PATH, filename, NULL);
1223 else
1224 found = DIR_SearchAlternatePath(libdir, libname, ".dll", MAX_PATH, filename, NULL);
1226 /* build the modules filename */
1227 if (!found)
1229 if (!MODULE_GetBuiltinPath( libname, ".dll", filename, MAX_PATH )) goto error;
1232 /* Check for already loaded module */
1233 if (!(pwm = MODULE_FindModule(filename)) && !FILE_contains_path(libname))
1235 LPSTR fn = HeapAlloc ( GetProcessHeap(), 0, MAX_PATH + 1 );
1236 if (fn)
1238 /* since the default loading mechanism uses a more detailed algorithm
1239 * than SearchPath (like using PATH, which can even be modified between
1240 * two attempts of loading the same DLL), the look-up above (with
1241 * SearchPath) can have put the file in system directory, whereas it
1242 * has already been loaded but with a different path. So do a specific
1243 * look-up with filename (without any path)
1245 strcpy ( fn, libname );
1246 /* if the filename doesn't have an extension append .DLL */
1247 if (!strrchr( fn, '.')) strcat( fn, ".dll" );
1248 if ((pwm = MODULE_FindModule( fn )) != NULL)
1249 strcpy( filename, fn );
1250 HeapFree( GetProcessHeap(), 0, fn );
1253 if (pwm)
1255 if(!(pwm->flags & WINE_MODREF_MARKER))
1256 pwm->refCount++;
1258 if ((pwm->flags & WINE_MODREF_DONT_RESOLVE_REFS) &&
1259 !(flags & DONT_RESOLVE_DLL_REFERENCES))
1261 pwm->flags &= ~WINE_MODREF_DONT_RESOLVE_REFS;
1262 PE_fixup_imports( pwm );
1264 TRACE("Already loaded module '%s' at 0x%08x, count=%d\n", filename, pwm->module, pwm->refCount);
1265 if (allocated_libdir)
1267 HeapFree ( GetProcessHeap(), 0, (LPSTR)libdir );
1268 libdir = NULL;
1270 RtlLeaveCriticalSection( &loader_section );
1271 HeapFree ( GetProcessHeap(), 0, filename );
1272 return pwm;
1275 MODULE_GetLoadOrder( loadorder, filename, TRUE);
1277 for(i = 0; i < LOADORDER_NTYPES; i++)
1279 if (loadorder[i] == LOADORDER_INVALID) break;
1280 SetLastError( ERROR_FILE_NOT_FOUND );
1282 switch(loadorder[i])
1284 case LOADORDER_DLL:
1285 TRACE("Trying native dll '%s'\n", filename);
1286 pwm = PE_LoadLibraryExA(filename, flags);
1287 filetype = "native";
1288 break;
1290 case LOADORDER_SO:
1291 TRACE("Trying so-library '%s'\n", filename);
1292 pwm = ELF_LoadLibraryExA(filename, flags);
1293 filetype = "so";
1294 break;
1296 case LOADORDER_BI:
1297 TRACE("Trying built-in '%s'\n", filename);
1298 pwm = BUILTIN32_LoadLibraryExA(filename, flags);
1299 filetype = "builtin";
1300 break;
1302 default:
1303 pwm = NULL;
1304 break;
1307 if(pwm)
1309 /* Initialize DLL just loaded */
1310 TRACE("Loaded module '%s' at 0x%08x\n", filename, pwm->module);
1311 if (!TRACE_ON(module))
1312 TRACE_(loaddll)("Loaded module '%s' : %s\n", filename, filetype);
1313 /* Set the refCount here so that an attach failure will */
1314 /* decrement the dependencies through the MODULE_FreeLibrary call. */
1315 pwm->refCount++;
1317 if (allocated_libdir)
1319 HeapFree ( GetProcessHeap(), 0, (LPSTR)libdir );
1320 libdir = NULL;
1322 RtlLeaveCriticalSection( &loader_section );
1323 SetLastError( err ); /* restore last error */
1324 HeapFree ( GetProcessHeap(), 0, filename );
1325 return pwm;
1328 if(GetLastError() != ERROR_FILE_NOT_FOUND)
1330 WARN("Loading of %s DLL %s failed (error %ld).\n",
1331 filetype, filename, GetLastError());
1332 break;
1336 error:
1337 if (allocated_libdir)
1339 HeapFree ( GetProcessHeap(), 0, (LPSTR)libdir );
1340 libdir = NULL;
1342 RtlLeaveCriticalSection( &loader_section );
1343 WARN("Failed to load module '%s'; error=%ld\n", filename, GetLastError());
1344 HeapFree ( GetProcessHeap(), 0, filename );
1345 return NULL;
1348 /***********************************************************************
1349 * LoadLibraryA (KERNEL32.@)
1351 HMODULE WINAPI LoadLibraryA(LPCSTR libname) {
1352 return LoadLibraryExA(libname,0,0);
1355 /***********************************************************************
1356 * LoadLibraryW (KERNEL32.@)
1358 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
1360 return LoadLibraryExW(libnameW,0,0);
1363 /***********************************************************************
1364 * LoadLibrary32 (KERNEL.452)
1365 * LoadSystemLibrary32 (KERNEL.482)
1367 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
1369 HMODULE hModule;
1370 DWORD count;
1372 ReleaseThunkLock( &count );
1373 hModule = LoadLibraryA( libname );
1374 RestoreThunkLock( count );
1375 return hModule;
1378 /***********************************************************************
1379 * LoadLibraryExW (KERNEL32.@)
1381 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW,HANDLE hfile,DWORD flags)
1383 LPSTR libnameA = HEAP_strdupWtoA( GetProcessHeap(), 0, libnameW );
1384 HMODULE ret = LoadLibraryExA( libnameA , hfile, flags );
1386 HeapFree( GetProcessHeap(), 0, libnameA );
1387 return ret;
1390 /***********************************************************************
1391 * MODULE_FlushModrefs
1393 * NOTE: Assumes that the process critical section is held!
1395 * Remove all unused modrefs and call the internal unloading routines
1396 * for the library type.
1398 static void MODULE_FlushModrefs(void)
1400 WINE_MODREF *wm, *next;
1402 for(wm = MODULE_modref_list; wm; wm = next)
1404 next = wm->next;
1406 if(wm->refCount)
1407 continue;
1409 /* Unlink this modref from the chain */
1410 if(wm->next)
1411 wm->next->prev = wm->prev;
1412 if(wm->prev)
1413 wm->prev->next = wm->next;
1414 if(wm == MODULE_modref_list)
1415 MODULE_modref_list = wm->next;
1417 TRACE(" unloading %s\n", wm->filename);
1418 if (!TRACE_ON(module))
1419 TRACE_(loaddll)("Unloaded module '%s' : %s\n", wm->filename,
1420 wm->dlhandle ? "builtin" : "native" );
1422 if (wm->dlhandle) wine_dll_unload( wm->dlhandle );
1423 else UnmapViewOfFile( (LPVOID)wm->module );
1424 FreeLibrary16(wm->hDummyMod);
1425 HeapFree( GetProcessHeap(), 0, wm->deps );
1426 HeapFree( GetProcessHeap(), 0, wm );
1430 /***********************************************************************
1431 * FreeLibrary (KERNEL32.@)
1432 * FreeLibrary32 (KERNEL.486)
1434 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
1436 BOOL retv = FALSE;
1437 WINE_MODREF *wm;
1439 if (!hLibModule)
1441 SetLastError( ERROR_INVALID_HANDLE );
1442 return FALSE;
1445 if ((ULONG_PTR)hLibModule & 1)
1447 /* this is a LOAD_LIBRARY_AS_DATAFILE module */
1448 char *ptr = (char *)hLibModule - 1;
1449 UnmapViewOfFile( ptr );
1450 return TRUE;
1453 RtlEnterCriticalSection( &loader_section );
1454 free_lib_count++;
1456 if ((wm = MODULE32_LookupHMODULE( hLibModule ))) retv = MODULE_FreeLibrary( wm );
1458 free_lib_count--;
1459 RtlLeaveCriticalSection( &loader_section );
1461 return retv;
1464 /***********************************************************************
1465 * MODULE_DecRefCount
1467 * NOTE: Assumes that the process critical section is held!
1469 static void MODULE_DecRefCount( WINE_MODREF *wm )
1471 int i;
1473 if ( wm->flags & WINE_MODREF_MARKER )
1474 return;
1476 if ( wm->refCount <= 0 )
1477 return;
1479 --wm->refCount;
1480 TRACE("(%s) refCount: %d\n", wm->modname, wm->refCount );
1482 if ( wm->refCount == 0 )
1484 wm->flags |= WINE_MODREF_MARKER;
1486 for ( i = 0; i < wm->nDeps; i++ )
1487 if ( wm->deps[i] )
1488 MODULE_DecRefCount( wm->deps[i] );
1490 wm->flags &= ~WINE_MODREF_MARKER;
1494 /***********************************************************************
1495 * MODULE_FreeLibrary
1497 * NOTE: Assumes that the process critical section is held!
1499 BOOL MODULE_FreeLibrary( WINE_MODREF *wm )
1501 TRACE("(%s) - START\n", wm->modname );
1503 /* Recursively decrement reference counts */
1504 MODULE_DecRefCount( wm );
1506 /* Call process detach notifications */
1507 if ( free_lib_count <= 1 )
1509 MODULE_DllProcessDetach( FALSE, NULL );
1510 SERVER_START_REQ( unload_dll )
1512 req->base = (void *)wm->module;
1513 wine_server_call( req );
1515 SERVER_END_REQ;
1516 MODULE_FlushModrefs();
1519 TRACE("END\n");
1521 return TRUE;
1525 /***********************************************************************
1526 * FreeLibraryAndExitThread (KERNEL32.@)
1528 VOID WINAPI FreeLibraryAndExitThread(HINSTANCE hLibModule, DWORD dwExitCode)
1530 FreeLibrary(hLibModule);
1531 ExitThread(dwExitCode);
1534 /***********************************************************************
1535 * PrivateLoadLibrary (KERNEL32.@)
1537 * FIXME: rough guesswork, don't know what "Private" means
1539 HINSTANCE16 WINAPI PrivateLoadLibrary(LPCSTR libname)
1541 return LoadLibrary16(libname);
1546 /***********************************************************************
1547 * PrivateFreeLibrary (KERNEL32.@)
1549 * FIXME: rough guesswork, don't know what "Private" means
1551 void WINAPI PrivateFreeLibrary(HINSTANCE16 handle)
1553 FreeLibrary16(handle);
1557 /***********************************************************************
1558 * GetProcAddress16 (KERNEL32.37)
1559 * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
1561 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
1563 if (!hModule) {
1564 WARN("hModule may not be 0!\n");
1565 return (FARPROC16)0;
1567 if (HIWORD(hModule))
1569 WARN("hModule is Win32 handle (%08x)\n", hModule );
1570 return (FARPROC16)0;
1572 return GetProcAddress16( LOWORD(hModule), name );
1575 /***********************************************************************
1576 * GetProcAddress (KERNEL.50)
1578 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, LPCSTR name )
1580 WORD ordinal;
1581 FARPROC16 ret;
1583 if (!hModule) hModule = GetCurrentTask();
1584 hModule = GetExePtr( hModule );
1586 if (HIWORD(name) != 0)
1588 ordinal = NE_GetOrdinal( hModule, name );
1589 TRACE("%04x '%s'\n", hModule, name );
1591 else
1593 ordinal = LOWORD(name);
1594 TRACE("%04x %04x\n", hModule, ordinal );
1596 if (!ordinal) return (FARPROC16)0;
1598 ret = NE_GetEntryPoint( hModule, ordinal );
1600 TRACE("returning %08x\n", (UINT)ret );
1601 return ret;
1605 /***********************************************************************
1606 * GetProcAddress (KERNEL32.@)
1608 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1610 return MODULE_GetProcAddress( hModule, function, -1, TRUE );
1613 /***********************************************************************
1614 * GetProcAddress32 (KERNEL.453)
1616 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
1618 return MODULE_GetProcAddress( hModule, function, -1, FALSE );
1621 /***********************************************************************
1622 * MODULE_GetProcAddress (internal)
1624 FARPROC MODULE_GetProcAddress(
1625 HMODULE hModule, /* [in] current module handle */
1626 LPCSTR function, /* [in] function to be looked up */
1627 int hint,
1628 BOOL snoop )
1630 WINE_MODREF *wm;
1631 FARPROC retproc = 0;
1633 if (HIWORD(function))
1634 TRACE_(win32)("(%08lx,%s (%d))\n",(DWORD)hModule,function,hint);
1635 else
1636 TRACE_(win32)("(%08lx,%p)\n",(DWORD)hModule,function);
1638 RtlEnterCriticalSection( &loader_section );
1639 if ((wm = MODULE32_LookupHMODULE( hModule )))
1641 retproc = wm->find_export( wm, function, hint, snoop );
1642 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1644 RtlLeaveCriticalSection( &loader_section );
1645 return retproc;
1649 /***************************************************************************
1650 * HasGPHandler (KERNEL.338)
1653 #include "pshpack1.h"
1654 typedef struct _GPHANDLERDEF
1656 WORD selector;
1657 WORD rangeStart;
1658 WORD rangeEnd;
1659 WORD handler;
1660 } GPHANDLERDEF;
1661 #include "poppack.h"
1663 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1665 HMODULE16 hModule;
1666 int gpOrdinal;
1667 SEGPTR gpPtr;
1668 GPHANDLERDEF *gpHandler;
1670 if ( (hModule = FarGetOwner16( SELECTOROF(address) )) != 0
1671 && (gpOrdinal = NE_GetOrdinal( hModule, "__GP" )) != 0
1672 && (gpPtr = (SEGPTR)NE_GetEntryPointEx( hModule, gpOrdinal, FALSE )) != 0
1673 && !IsBadReadPtr16( gpPtr, sizeof(GPHANDLERDEF) )
1674 && (gpHandler = MapSL( gpPtr )) != NULL )
1676 while (gpHandler->selector)
1678 if ( SELECTOROF(address) == gpHandler->selector
1679 && OFFSETOF(address) >= gpHandler->rangeStart
1680 && OFFSETOF(address) < gpHandler->rangeEnd )
1681 return MAKESEGPTR( gpHandler->selector, gpHandler->handler );
1682 gpHandler++;
1686 return 0;