- fixed another regression in sub-process creation (curses backend
[wine/gsoc_dplay.git] / loader / module.c
bloba27d5cc31f8453d0bd7bcd0b9af4d515da36f09a
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 WINE_MODREF *exe_modref;
51 static int free_lib_count; /* recursion depth of FreeLibrary calls */
52 int process_detaching = 0; /* set on process detach to avoid deadlocks with thread detach */
54 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 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 %p 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 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 * DisableThreadLibraryCalls (KERNEL32.@)
331 * Don't call DllEntryPoint for DLL_THREAD_{ATTACH,DETACH} if set.
333 BOOL WINAPI DisableThreadLibraryCalls( HMODULE hModule )
335 NTSTATUS nts = LdrDisableThreadCalloutsForDll( hModule );
336 if (nts == STATUS_SUCCESS) return TRUE;
338 SetLastError( RtlNtStatusToDosError( nts ) );
339 return FALSE;
343 /***********************************************************************
344 * MODULE_CreateDummyModule
346 * Create a dummy NE module for Win32 or Winelib.
348 HMODULE16 MODULE_CreateDummyModule( LPCSTR filename, HMODULE module32 )
350 HMODULE16 hModule;
351 NE_MODULE *pModule;
352 SEGTABLEENTRY *pSegment;
353 char *pStr,*s;
354 unsigned int len;
355 const char* basename;
356 OFSTRUCT *ofs;
357 int of_size, size;
359 /* Extract base filename */
360 basename = strrchr(filename, '\\');
361 if (!basename) basename = filename;
362 else basename++;
363 len = strlen(basename);
364 if ((s = strchr(basename, '.'))) len = s - basename;
366 /* Allocate module */
367 of_size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName)
368 + strlen(filename) + 1;
369 size = sizeof(NE_MODULE) +
370 /* loaded file info */
371 ((of_size + 3) & ~3) +
372 /* segment table: DS,CS */
373 2 * sizeof(SEGTABLEENTRY) +
374 /* name table */
375 len + 2 +
376 /* several empty tables */
379 hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
380 if (!hModule) return (HMODULE16)11; /* invalid exe */
382 FarSetOwner16( hModule, hModule );
383 pModule = (NE_MODULE *)GlobalLock16( hModule );
385 /* Set all used entries */
386 pModule->magic = IMAGE_OS2_SIGNATURE;
387 pModule->count = 1;
388 pModule->next = 0;
389 pModule->flags = 0;
390 pModule->dgroup = 0;
391 pModule->ss = 1;
392 pModule->cs = 2;
393 pModule->heap_size = 0;
394 pModule->stack_size = 0;
395 pModule->seg_count = 2;
396 pModule->modref_count = 0;
397 pModule->nrname_size = 0;
398 pModule->fileinfo = sizeof(NE_MODULE);
399 pModule->os_flags = NE_OSFLAGS_WINDOWS;
400 pModule->self = hModule;
401 pModule->module32 = module32;
403 /* Set version and flags */
404 if (module32)
406 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( module32 );
407 pModule->expected_version = ((nt->OptionalHeader.MajorSubsystemVersion & 0xff) << 8 ) |
408 (nt->OptionalHeader.MinorSubsystemVersion & 0xff);
409 pModule->flags |= NE_FFLAGS_WIN32;
410 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
411 pModule->flags |= NE_FFLAGS_LIBMODULE | NE_FFLAGS_SINGLEDATA;
414 /* Set loaded file information */
415 ofs = (OFSTRUCT *)(pModule + 1);
416 memset( ofs, 0, of_size );
417 ofs->cBytes = of_size < 256 ? of_size : 255; /* FIXME */
418 strcpy( ofs->szPathName, filename );
420 pSegment = (SEGTABLEENTRY*)((char*)(pModule + 1) + ((of_size + 3) & ~3));
421 pModule->seg_table = (int)pSegment - (int)pModule;
422 /* Data segment */
423 pSegment->size = 0;
424 pSegment->flags = NE_SEGFLAGS_DATA;
425 pSegment->minsize = 0x1000;
426 pSegment++;
427 /* Code segment */
428 pSegment->flags = 0;
429 pSegment++;
431 /* Module name */
432 pStr = (char *)pSegment;
433 pModule->name_table = (int)pStr - (int)pModule;
434 assert(len<256);
435 *pStr = len;
436 lstrcpynA( pStr+1, basename, len+1 );
437 pStr += len+2;
439 /* All tables zero terminated */
440 pModule->res_table = pModule->import_table = pModule->entry_table =
441 (int)pStr - (int)pModule;
443 NE_RegisterModule( pModule );
444 return hModule;
448 /* Check whether a file is an OS/2 or a very old Windows executable
449 * by testing on import of KERNEL.
451 * FIXME: is reading the module imports the only way of discerning
452 * old Windows binaries from OS/2 ones ? At least it seems so...
454 static enum binary_type MODULE_Decide_OS2_OldWin(HANDLE hfile, const IMAGE_DOS_HEADER *mz,
455 const IMAGE_OS2_HEADER *ne)
457 DWORD currpos = SetFilePointer( hfile, 0, NULL, SEEK_CUR);
458 enum binary_type ret = BINARY_OS216;
459 LPWORD modtab = NULL;
460 LPSTR nametab = NULL;
461 DWORD len;
462 int i;
464 /* read modref table */
465 if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_modtab, NULL, SEEK_SET ) == -1)
466 || (!(modtab = HeapAlloc( GetProcessHeap(), 0, ne->ne_cmod*sizeof(WORD))))
467 || (!(ReadFile(hfile, modtab, ne->ne_cmod*sizeof(WORD), &len, NULL)))
468 || (len != ne->ne_cmod*sizeof(WORD)) )
469 goto broken;
471 /* read imported names table */
472 if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_imptab, NULL, SEEK_SET ) == -1)
473 || (!(nametab = HeapAlloc( GetProcessHeap(), 0, ne->ne_enttab - ne->ne_imptab)))
474 || (!(ReadFile(hfile, nametab, ne->ne_enttab - ne->ne_imptab, &len, NULL)))
475 || (len != ne->ne_enttab - ne->ne_imptab) )
476 goto broken;
478 for (i=0; i < ne->ne_cmod; i++)
480 LPSTR module = &nametab[modtab[i]];
481 TRACE("modref: %.*s\n", module[0], &module[1]);
482 if (!(strncmp(&module[1], "KERNEL", module[0])))
483 { /* very old Windows file */
484 MESSAGE("This seems to be a very old (pre-3.0) Windows executable. Expect crashes, especially if this is a real-mode binary !\n");
485 ret = BINARY_WIN16;
486 goto good;
490 broken:
491 ERR("Hmm, an error occurred. Is this binary file broken ?\n");
493 good:
494 HeapFree( GetProcessHeap(), 0, modtab);
495 HeapFree( GetProcessHeap(), 0, nametab);
496 SetFilePointer( hfile, currpos, NULL, SEEK_SET); /* restore filepos */
497 return ret;
500 /***********************************************************************
501 * MODULE_GetBinaryType
503 enum binary_type MODULE_GetBinaryType( HANDLE hfile )
505 union
507 struct
509 unsigned char magic[4];
510 unsigned char ignored[12];
511 unsigned short type;
512 } elf;
513 IMAGE_DOS_HEADER mz;
514 } header;
516 char magic[4];
517 DWORD len;
519 /* Seek to the start of the file and read the header information. */
520 if (SetFilePointer( hfile, 0, NULL, SEEK_SET ) == -1)
521 return BINARY_UNKNOWN;
522 if (!ReadFile( hfile, &header, sizeof(header), &len, NULL ) || len != sizeof(header))
523 return BINARY_UNKNOWN;
525 if (!memcmp( header.elf.magic, "\177ELF", 4 ))
527 /* FIXME: we don't bother to check byte order, architecture, etc. */
528 switch(header.elf.type)
530 case 2: return BINARY_UNIX_EXE;
531 case 3: return BINARY_UNIX_LIB;
533 return BINARY_UNKNOWN;
536 /* Not ELF, try DOS */
538 if (header.mz.e_magic == IMAGE_DOS_SIGNATURE)
540 /* We do have a DOS image so we will now try to seek into
541 * the file by the amount indicated by the field
542 * "Offset to extended header" and read in the
543 * "magic" field information at that location.
544 * This will tell us if there is more header information
545 * to read or not.
547 /* But before we do we will make sure that header
548 * structure encompasses the "Offset to extended header"
549 * field.
551 if ((header.mz.e_cparhdr << 4) < sizeof(IMAGE_DOS_HEADER))
552 return BINARY_DOS;
553 if (header.mz.e_crlc && (header.mz.e_lfarlc < sizeof(IMAGE_DOS_HEADER)))
554 return BINARY_DOS;
555 if (header.mz.e_lfanew < sizeof(IMAGE_DOS_HEADER))
556 return BINARY_DOS;
557 if (SetFilePointer( hfile, header.mz.e_lfanew, NULL, SEEK_SET ) == -1)
558 return BINARY_DOS;
559 if (!ReadFile( hfile, magic, sizeof(magic), &len, NULL ) || len != sizeof(magic))
560 return BINARY_DOS;
562 /* Reading the magic field succeeded so
563 * we will try to determine what type it is.
565 if (!memcmp( magic, "PE\0\0", 4 ))
567 IMAGE_FILE_HEADER FileHeader;
569 if (ReadFile( hfile, &FileHeader, sizeof(FileHeader), &len, NULL ) && len == sizeof(FileHeader))
571 if (FileHeader.Characteristics & IMAGE_FILE_DLL) return BINARY_PE_DLL;
572 return BINARY_PE_EXE;
574 return BINARY_DOS;
577 if (!memcmp( magic, "NE", 2 ))
579 /* This is a Windows executable (NE) header. This can
580 * mean either a 16-bit OS/2 or a 16-bit Windows or even a
581 * DOS program (running under a DOS extender). To decide
582 * which, we'll have to read the NE header.
584 IMAGE_OS2_HEADER ne;
585 if ( SetFilePointer( hfile, header.mz.e_lfanew, NULL, SEEK_SET ) != -1
586 && ReadFile( hfile, &ne, sizeof(ne), &len, NULL )
587 && len == sizeof(ne) )
589 switch ( ne.ne_exetyp )
591 case 2: return BINARY_WIN16;
592 case 5: return BINARY_DOS;
593 default: return MODULE_Decide_OS2_OldWin(hfile, &header.mz, &ne);
596 /* Couldn't read header, so abort. */
597 return BINARY_DOS;
600 /* Unknown extended header, but this file is nonetheless DOS-executable. */
601 return BINARY_DOS;
604 return BINARY_UNKNOWN;
607 /***********************************************************************
608 * GetBinaryTypeA [KERNEL32.@]
609 * GetBinaryType [KERNEL32.@]
611 * The GetBinaryType function determines whether a file is executable
612 * or not and if it is it returns what type of executable it is.
613 * The type of executable is a property that determines in which
614 * subsystem an executable file runs under.
616 * Binary types returned:
617 * SCS_32BIT_BINARY: A Win32 based application
618 * SCS_DOS_BINARY: An MS-Dos based application
619 * SCS_WOW_BINARY: A Win16 based application
620 * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
621 * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
622 * SCS_OS216_BINARY: A 16bit OS/2 based application
624 * Returns TRUE if the file is an executable in which case
625 * the value pointed by lpBinaryType is set.
626 * Returns FALSE if the file is not an executable or if the function fails.
628 * To do so it opens the file and reads in the header information
629 * if the extended header information is not present it will
630 * assume that the file is a DOS executable.
631 * If the extended header information is present it will
632 * determine if the file is a 16 or 32 bit Windows executable
633 * by check the flags in the header.
635 * Note that .COM and .PIF files are only recognized by their
636 * file name extension; but Windows does it the same way ...
638 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
640 BOOL ret = FALSE;
641 HANDLE hfile;
642 char *ptr;
644 TRACE_(win32)("%s\n", lpApplicationName );
646 /* Sanity check.
648 if ( lpApplicationName == NULL || lpBinaryType == NULL )
649 return FALSE;
651 /* Open the file indicated by lpApplicationName for reading.
653 hfile = CreateFileA( lpApplicationName, GENERIC_READ, FILE_SHARE_READ,
654 NULL, OPEN_EXISTING, 0, 0 );
655 if ( hfile == INVALID_HANDLE_VALUE )
656 return FALSE;
658 /* Check binary type
660 switch(MODULE_GetBinaryType( hfile ))
662 case BINARY_UNKNOWN:
663 /* try to determine from file name */
664 ptr = strrchr( lpApplicationName, '.' );
665 if (!ptr) break;
666 if (!FILE_strcasecmp( ptr, ".COM" ))
668 *lpBinaryType = SCS_DOS_BINARY;
669 ret = TRUE;
671 else if (!FILE_strcasecmp( ptr, ".PIF" ))
673 *lpBinaryType = SCS_PIF_BINARY;
674 ret = TRUE;
676 break;
677 case BINARY_PE_EXE:
678 case BINARY_PE_DLL:
679 *lpBinaryType = SCS_32BIT_BINARY;
680 ret = TRUE;
681 break;
682 case BINARY_WIN16:
683 *lpBinaryType = SCS_WOW_BINARY;
684 ret = TRUE;
685 break;
686 case BINARY_OS216:
687 *lpBinaryType = SCS_OS216_BINARY;
688 ret = TRUE;
689 break;
690 case BINARY_DOS:
691 *lpBinaryType = SCS_DOS_BINARY;
692 ret = TRUE;
693 break;
694 case BINARY_UNIX_EXE:
695 case BINARY_UNIX_LIB:
696 ret = FALSE;
697 break;
700 CloseHandle( hfile );
701 return ret;
704 /***********************************************************************
705 * GetBinaryTypeW [KERNEL32.@]
707 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
709 BOOL ret = FALSE;
710 LPSTR strNew = NULL;
712 TRACE_(win32)("%s\n", debugstr_w(lpApplicationName) );
714 /* Sanity check.
716 if ( lpApplicationName == NULL || lpBinaryType == NULL )
717 return FALSE;
719 /* Convert the wide string to a ascii string.
721 strNew = HEAP_strdupWtoA( GetProcessHeap(), 0, lpApplicationName );
723 if ( strNew != NULL )
725 ret = GetBinaryTypeA( strNew, lpBinaryType );
727 /* Free the allocated string.
729 HeapFree( GetProcessHeap(), 0, strNew );
732 return ret;
736 /***********************************************************************
737 * WinExec (KERNEL.166)
739 HINSTANCE16 WINAPI WinExec16( LPCSTR lpCmdLine, UINT16 nCmdShow )
741 LPCSTR p, args = NULL;
742 LPCSTR name_beg, name_end;
743 LPSTR name, cmdline;
744 int arglen;
745 HINSTANCE16 ret;
746 char buffer[MAX_PATH];
748 if (*lpCmdLine == '"') /* has to be only one and only at beginning ! */
750 name_beg = lpCmdLine+1;
751 p = strchr ( lpCmdLine+1, '"' );
752 if (p)
754 name_end = p;
755 args = strchr ( p, ' ' );
757 else /* yes, even valid with trailing '"' missing */
758 name_end = lpCmdLine+strlen(lpCmdLine);
760 else
762 name_beg = lpCmdLine;
763 args = strchr( lpCmdLine, ' ' );
764 name_end = args ? args : lpCmdLine+strlen(lpCmdLine);
767 if ((name_beg == lpCmdLine) && (!args))
768 { /* just use the original cmdline string as file name */
769 name = (LPSTR)lpCmdLine;
771 else
773 if (!(name = HeapAlloc( GetProcessHeap(), 0, name_end - name_beg + 1 )))
774 return ERROR_NOT_ENOUGH_MEMORY;
775 memcpy( name, name_beg, name_end - name_beg );
776 name[name_end - name_beg] = '\0';
779 if (args)
781 args++;
782 arglen = strlen(args);
783 cmdline = HeapAlloc( GetProcessHeap(), 0, 2 + arglen );
784 cmdline[0] = (BYTE)arglen;
785 strcpy( cmdline + 1, args );
787 else
789 cmdline = HeapAlloc( GetProcessHeap(), 0, 2 );
790 cmdline[0] = cmdline[1] = 0;
793 TRACE("name: '%s', cmdline: '%.*s'\n", name, cmdline[0], &cmdline[1]);
795 if (SearchPathA( NULL, name, ".exe", sizeof(buffer), buffer, NULL ))
797 LOADPARAMS16 params;
798 WORD showCmd[2];
799 showCmd[0] = 2;
800 showCmd[1] = nCmdShow;
802 params.hEnvironment = 0;
803 params.cmdLine = MapLS( cmdline );
804 params.showCmd = MapLS( showCmd );
805 params.reserved = 0;
807 ret = LoadModule16( buffer, &params );
808 UnMapLS( params.cmdLine );
809 UnMapLS( params.showCmd );
811 else ret = GetLastError();
813 HeapFree( GetProcessHeap(), 0, cmdline );
814 if (name != lpCmdLine) HeapFree( GetProcessHeap(), 0, name );
816 if (ret == 21) /* 32-bit module */
818 DWORD count;
819 ReleaseThunkLock( &count );
820 ret = LOWORD( WinExec( lpCmdLine, nCmdShow ) );
821 RestoreThunkLock( count );
823 return ret;
826 /***********************************************************************
827 * WinExec (KERNEL32.@)
829 UINT WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
831 PROCESS_INFORMATION info;
832 STARTUPINFOA startup;
833 char *cmdline;
834 UINT ret;
836 memset( &startup, 0, sizeof(startup) );
837 startup.cb = sizeof(startup);
838 startup.dwFlags = STARTF_USESHOWWINDOW;
839 startup.wShowWindow = nCmdShow;
841 /* cmdline needs to be writeable for CreateProcess */
842 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
843 strcpy( cmdline, lpCmdLine );
845 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
846 0, NULL, NULL, &startup, &info ))
848 /* Give 30 seconds to the app to come up */
849 if (wait_input_idle( info.hProcess, 30000 ) == 0xFFFFFFFF)
850 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
851 ret = 33;
852 /* Close off the handles */
853 CloseHandle( info.hThread );
854 CloseHandle( info.hProcess );
856 else if ((ret = GetLastError()) >= 32)
858 FIXME("Strange error set by CreateProcess: %d\n", ret );
859 ret = 11;
861 HeapFree( GetProcessHeap(), 0, cmdline );
862 return ret;
865 /**********************************************************************
866 * LoadModule (KERNEL32.@)
868 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
870 LOADPARAMS *params = (LOADPARAMS *)paramBlock;
871 PROCESS_INFORMATION info;
872 STARTUPINFOA startup;
873 HINSTANCE hInstance;
874 LPSTR cmdline, p;
875 char filename[MAX_PATH];
876 BYTE len;
878 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
880 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
881 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
882 return (HINSTANCE)GetLastError();
884 len = (BYTE)params->lpCmdLine[0];
885 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
886 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
888 strcpy( cmdline, filename );
889 p = cmdline + strlen(cmdline);
890 *p++ = ' ';
891 memcpy( p, params->lpCmdLine + 1, len );
892 p[len] = 0;
894 memset( &startup, 0, sizeof(startup) );
895 startup.cb = sizeof(startup);
896 if (params->lpCmdShow)
898 startup.dwFlags = STARTF_USESHOWWINDOW;
899 startup.wShowWindow = params->lpCmdShow[1];
902 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
903 params->lpEnvAddress, NULL, &startup, &info ))
905 /* Give 30 seconds to the app to come up */
906 if (wait_input_idle( info.hProcess, 30000 ) == 0xFFFFFFFF )
907 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
908 hInstance = (HINSTANCE)33;
909 /* Close off the handles */
910 CloseHandle( info.hThread );
911 CloseHandle( info.hProcess );
913 else if ((hInstance = (HINSTANCE)GetLastError()) >= (HINSTANCE)32)
915 FIXME("Strange error set by CreateProcess: %p\n", hInstance );
916 hInstance = (HINSTANCE)11;
919 HeapFree( GetProcessHeap(), 0, cmdline );
920 return hInstance;
924 /***********************************************************************
925 * GetModuleHandleA (KERNEL32.@)
926 * GetModuleHandle32 (KERNEL.488)
928 HMODULE WINAPI GetModuleHandleA(LPCSTR module)
930 NTSTATUS nts;
931 HMODULE ret;
933 if (module)
935 UNICODE_STRING wstr;
937 RtlCreateUnicodeStringFromAsciiz(&wstr, module);
938 nts = LdrGetDllHandle(0, 0, &wstr, &ret);
939 RtlFreeUnicodeString( &wstr );
941 else
942 nts = LdrGetDllHandle(0, 0, NULL, &ret);
943 if (nts != STATUS_SUCCESS)
945 ret = 0;
946 SetLastError( RtlNtStatusToDosError( nts ) );
949 return ret;
952 /***********************************************************************
953 * GetModuleHandleW (KERNEL32.@)
955 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
957 NTSTATUS nts;
958 HMODULE ret;
960 if (module)
962 UNICODE_STRING wstr;
964 RtlInitUnicodeString( &wstr, module );
965 nts = LdrGetDllHandle( 0, 0, &wstr, &ret);
967 else
968 nts = LdrGetDllHandle( 0, 0, NULL, &ret);
970 if (nts != STATUS_SUCCESS)
972 SetLastError( RtlNtStatusToDosError( nts ) );
973 ret = 0;
975 return ret;
979 /***********************************************************************
980 * GetModuleFileNameA (KERNEL32.@)
981 * GetModuleFileName32 (KERNEL.487)
983 * GetModuleFileNameA seems to *always* return the long path;
984 * it's only GetModuleFileName16 that decides between short/long path
985 * by checking if exe version >= 4.0.
986 * (SDK docu doesn't mention this)
988 DWORD WINAPI GetModuleFileNameA(
989 HMODULE hModule, /* [in] module handle (32bit) */
990 LPSTR lpFileName, /* [out] filenamebuffer */
991 DWORD size ) /* [in] size of filenamebuffer */
993 RtlEnterCriticalSection( &loader_section );
995 lpFileName[0] = 0;
996 if (!hModule && !(NtCurrentTeb()->tibflags & TEBF_WIN32))
998 /* 16-bit task - get current NE module name */
999 NE_MODULE *pModule = NE_GetPtr( GetCurrentTask() );
1000 if (pModule) GetLongPathNameA(NE_MODULE_NAME(pModule), lpFileName, size);
1002 else
1004 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1005 if (wm) lstrcpynA( lpFileName, wm->filename, size );
1008 RtlLeaveCriticalSection( &loader_section );
1009 TRACE("%s\n", lpFileName );
1010 return strlen(lpFileName);
1014 /***********************************************************************
1015 * GetModuleFileNameW (KERNEL32.@)
1017 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName, DWORD size )
1019 LPSTR fnA = HeapAlloc( GetProcessHeap(), 0, size * 2 );
1020 if (!fnA) return 0;
1021 GetModuleFileNameA( hModule, fnA, size * 2 );
1022 if (size > 0 && !MultiByteToWideChar( CP_ACP, 0, fnA, -1, lpFileName, size ))
1023 lpFileName[size-1] = 0;
1024 HeapFree( GetProcessHeap(), 0, fnA );
1025 return strlenW(lpFileName);
1029 /***********************************************************************
1030 * LoadLibraryExA (KERNEL32.@)
1032 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
1034 WINE_MODREF *wm;
1036 if(!libname)
1038 SetLastError(ERROR_INVALID_PARAMETER);
1039 return 0;
1042 if (flags & LOAD_LIBRARY_AS_DATAFILE)
1044 char filename[256];
1045 HMODULE hmod = 0;
1047 /* This method allows searching for the 'native' libraries only */
1048 if (SearchPathA( NULL, libname, ".dll", sizeof(filename), filename, NULL ))
1050 /* FIXME: maybe we should use the hfile parameter instead */
1051 HANDLE hFile = CreateFileA( filename, GENERIC_READ, FILE_SHARE_READ,
1052 NULL, OPEN_EXISTING, 0, 0 );
1053 if (hFile != INVALID_HANDLE_VALUE)
1055 HANDLE mapping;
1056 switch (MODULE_GetBinaryType( hFile ))
1058 case BINARY_PE_EXE:
1059 case BINARY_PE_DLL:
1060 mapping = CreateFileMappingA( hFile, NULL, PAGE_READONLY, 0, 0, NULL );
1061 if (mapping)
1063 hmod = (HMODULE)MapViewOfFile( mapping, FILE_MAP_READ, 0, 0, 0 );
1064 CloseHandle( mapping );
1066 break;
1067 default:
1068 break;
1070 CloseHandle( hFile );
1072 if (hmod) return (HMODULE)((ULONG_PTR)hmod + 1);
1074 flags |= DONT_RESOLVE_DLL_REFERENCES; /* Just in case */
1075 /* Fallback to normal behaviour */
1078 RtlEnterCriticalSection( &loader_section );
1080 wm = MODULE_LoadLibraryExA( libname, hfile, flags );
1081 if ( wm )
1083 if ( !MODULE_DllProcessAttach( wm, NULL ) )
1085 WARN_(module)("Attach failed for module '%s'.\n", libname);
1086 MODULE_FreeLibrary(wm);
1087 SetLastError(ERROR_DLL_INIT_FAILED);
1088 wm = NULL;
1092 RtlLeaveCriticalSection( &loader_section );
1093 return wm ? wm->module : 0;
1096 /***********************************************************************
1097 * allocate_lib_dir
1099 * helper for MODULE_LoadLibraryExA. Allocate space to hold the directory
1100 * portion of the provided name and put the name in it.
1103 static LPCSTR allocate_lib_dir(LPCSTR libname)
1105 LPCSTR p, pmax;
1106 LPSTR result;
1107 int length;
1109 pmax = libname;
1110 if ((p = strrchr( pmax, '\\' ))) pmax = p + 1;
1111 if ((p = strrchr( pmax, '/' ))) pmax = p + 1; /* Naughty. MSDN says don't */
1112 if (pmax == libname && pmax[0] && pmax[1] == ':') pmax += 2;
1114 length = pmax - libname;
1116 result = HeapAlloc (GetProcessHeap(), 0, length+1);
1118 if (result)
1120 strncpy (result, libname, length);
1121 result [length] = '\0';
1124 return result;
1127 /***********************************************************************
1128 * MODULE_LoadLibraryExA (internal)
1130 * Load a PE style module according to the load order.
1132 * The HFILE parameter is not used and marked reserved in the SDK. I can
1133 * only guess that it should force a file to be mapped, but I rather
1134 * ignore the parameter because it would be extremely difficult to
1135 * integrate this with different types of module representations.
1137 * libdir is used to support LOAD_WITH_ALTERED_SEARCH_PATH during the recursion
1138 * on this function. When first called from LoadLibraryExA it will be
1139 * NULL but thereafter it may point to a buffer containing the path
1140 * portion of the library name. Note that the recursion all occurs
1141 * within a Critical section (see LoadLibraryExA) so the use of a
1142 * static is acceptable.
1143 * (We have to use a static variable at some point anyway, to pass the
1144 * information from BUILTIN32_dlopen through dlopen and the builtin's
1145 * init function into load_library).
1146 * allocated_libdir is TRUE in the stack frame that allocated libdir
1148 WINE_MODREF *MODULE_LoadLibraryExA( LPCSTR libname, HANDLE hfile, DWORD flags )
1150 DWORD err = GetLastError();
1151 WINE_MODREF *pwm;
1152 int i;
1153 enum loadorder_type loadorder[LOADORDER_NTYPES];
1154 LPSTR filename;
1155 const char *filetype = "";
1156 DWORD found;
1157 BOOL allocated_libdir = FALSE;
1158 static LPCSTR libdir = NULL; /* See above */
1160 if ( !libname ) return NULL;
1162 filename = HeapAlloc ( GetProcessHeap(), 0, MAX_PATH + 1 );
1163 if ( !filename ) return NULL;
1164 *filename = 0; /* Just in case we don't set it before goto error */
1166 RtlEnterCriticalSection( &loader_section );
1168 if ((flags & LOAD_WITH_ALTERED_SEARCH_PATH) && FILE_contains_path(libname))
1170 if (!(libdir = allocate_lib_dir(libname))) goto error;
1171 allocated_libdir = TRUE;
1174 if (!libdir || allocated_libdir)
1175 found = SearchPathA(NULL, libname, ".dll", MAX_PATH, filename, NULL);
1176 else
1177 found = DIR_SearchAlternatePath(libdir, libname, ".dll", MAX_PATH, filename, NULL);
1179 /* build the modules filename */
1180 if (!found)
1182 if (!MODULE_GetBuiltinPath( libname, ".dll", filename, MAX_PATH )) goto error;
1185 /* Check for already loaded module */
1186 if (!(pwm = MODULE_FindModule(filename)) && !FILE_contains_path(libname))
1188 LPSTR fn = HeapAlloc ( GetProcessHeap(), 0, MAX_PATH + 1 );
1189 if (fn)
1191 /* since the default loading mechanism uses a more detailed algorithm
1192 * than SearchPath (like using PATH, which can even be modified between
1193 * two attempts of loading the same DLL), the look-up above (with
1194 * SearchPath) can have put the file in system directory, whereas it
1195 * has already been loaded but with a different path. So do a specific
1196 * look-up with filename (without any path)
1198 strcpy ( fn, libname );
1199 /* if the filename doesn't have an extension append .DLL */
1200 if (!strrchr( fn, '.')) strcat( fn, ".dll" );
1201 if ((pwm = MODULE_FindModule( fn )) != NULL)
1202 strcpy( filename, fn );
1203 HeapFree( GetProcessHeap(), 0, fn );
1206 if (pwm)
1208 pwm->refCount++;
1210 if ((pwm->flags & WINE_MODREF_DONT_RESOLVE_REFS) &&
1211 !(flags & DONT_RESOLVE_DLL_REFERENCES))
1213 pwm->flags &= ~WINE_MODREF_DONT_RESOLVE_REFS;
1214 PE_fixup_imports( pwm );
1216 TRACE("Already loaded module '%s' at %p, count=%d\n", filename, pwm->module, pwm->refCount);
1217 if (allocated_libdir)
1219 HeapFree ( GetProcessHeap(), 0, (LPSTR)libdir );
1220 libdir = NULL;
1222 RtlLeaveCriticalSection( &loader_section );
1223 HeapFree ( GetProcessHeap(), 0, filename );
1224 return pwm;
1227 MODULE_GetLoadOrder( loadorder, filename, TRUE);
1229 for(i = 0; i < LOADORDER_NTYPES; i++)
1231 if (loadorder[i] == LOADORDER_INVALID) break;
1232 SetLastError( ERROR_FILE_NOT_FOUND );
1234 switch(loadorder[i])
1236 case LOADORDER_DLL:
1237 TRACE("Trying native dll '%s'\n", filename);
1238 pwm = PE_LoadLibraryExA(filename, flags);
1239 filetype = "native";
1240 break;
1242 case LOADORDER_BI:
1243 TRACE("Trying built-in '%s'\n", filename);
1244 pwm = BUILTIN32_LoadLibraryExA(filename, flags);
1245 filetype = "builtin";
1246 break;
1248 default:
1249 pwm = NULL;
1250 break;
1253 if(pwm)
1255 /* Initialize DLL just loaded */
1256 TRACE("Loaded module '%s' at %p\n", filename, pwm->module);
1257 if (!TRACE_ON(module))
1258 TRACE_(loaddll)("Loaded module '%s' : %s\n", filename, filetype);
1259 /* Set the refCount here so that an attach failure will */
1260 /* decrement the dependencies through the MODULE_FreeLibrary call. */
1261 pwm->refCount = 1;
1263 if (allocated_libdir)
1265 HeapFree ( GetProcessHeap(), 0, (LPSTR)libdir );
1266 libdir = NULL;
1268 RtlLeaveCriticalSection( &loader_section );
1269 SetLastError( err ); /* restore last error */
1270 HeapFree ( GetProcessHeap(), 0, filename );
1271 return pwm;
1274 if(GetLastError() != ERROR_FILE_NOT_FOUND)
1276 WARN("Loading of %s DLL %s failed (error %ld).\n",
1277 filetype, filename, GetLastError());
1278 break;
1282 error:
1283 if (allocated_libdir)
1285 HeapFree ( GetProcessHeap(), 0, (LPSTR)libdir );
1286 libdir = NULL;
1288 RtlLeaveCriticalSection( &loader_section );
1289 WARN("Failed to load module '%s'; error=%ld\n", filename, GetLastError());
1290 HeapFree ( GetProcessHeap(), 0, filename );
1291 return NULL;
1294 /***********************************************************************
1295 * LoadLibraryA (KERNEL32.@)
1297 HMODULE WINAPI LoadLibraryA(LPCSTR libname) {
1298 return LoadLibraryExA(libname,0,0);
1301 /***********************************************************************
1302 * LoadLibraryW (KERNEL32.@)
1304 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
1306 return LoadLibraryExW(libnameW,0,0);
1309 /***********************************************************************
1310 * LoadLibrary32 (KERNEL.452)
1311 * LoadSystemLibrary32 (KERNEL.482)
1313 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
1315 HMODULE hModule;
1316 DWORD count;
1318 ReleaseThunkLock( &count );
1319 hModule = LoadLibraryA( libname );
1320 RestoreThunkLock( count );
1321 return hModule;
1324 /***********************************************************************
1325 * LoadLibraryExW (KERNEL32.@)
1327 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW,HANDLE hfile,DWORD flags)
1329 LPSTR libnameA = HEAP_strdupWtoA( GetProcessHeap(), 0, libnameW );
1330 HMODULE ret = LoadLibraryExA( libnameA , hfile, flags );
1332 HeapFree( GetProcessHeap(), 0, libnameA );
1333 return ret;
1336 /***********************************************************************
1337 * MODULE_FlushModrefs
1339 * NOTE: Assumes that the process critical section is held!
1341 * Remove all unused modrefs and call the internal unloading routines
1342 * for the library type.
1344 static void MODULE_FlushModrefs(void)
1346 WINE_MODREF *wm, *next;
1348 for(wm = MODULE_modref_list; wm; wm = next)
1350 next = wm->next;
1352 if(wm->refCount)
1353 continue;
1355 /* Unlink this modref from the chain */
1356 if(wm->next)
1357 wm->next->prev = wm->prev;
1358 if(wm->prev)
1359 wm->prev->next = wm->next;
1360 if(wm == MODULE_modref_list)
1361 MODULE_modref_list = wm->next;
1363 TRACE(" unloading %s\n", wm->filename);
1364 if (!TRACE_ON(module))
1365 TRACE_(loaddll)("Unloaded module '%s' : %s\n", wm->filename,
1366 wm->dlhandle ? "builtin" : "native" );
1368 SERVER_START_REQ( unload_dll )
1370 req->base = (void *)wm->module;
1371 wine_server_call( req );
1373 SERVER_END_REQ;
1375 if (wm->dlhandle) wine_dll_unload( wm->dlhandle );
1376 else UnmapViewOfFile( (LPVOID)wm->module );
1377 FreeLibrary16(wm->hDummyMod);
1378 HeapFree( GetProcessHeap(), 0, wm->deps );
1379 HeapFree( GetProcessHeap(), 0, wm );
1383 /***********************************************************************
1384 * FreeLibrary (KERNEL32.@)
1385 * FreeLibrary32 (KERNEL.486)
1387 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
1389 BOOL retv = FALSE;
1390 WINE_MODREF *wm;
1392 if (!hLibModule)
1394 SetLastError( ERROR_INVALID_HANDLE );
1395 return FALSE;
1398 if ((ULONG_PTR)hLibModule & 1)
1400 /* this is a LOAD_LIBRARY_AS_DATAFILE module */
1401 char *ptr = (char *)hLibModule - 1;
1402 UnmapViewOfFile( ptr );
1403 return TRUE;
1406 RtlEnterCriticalSection( &loader_section );
1408 /* if we're stopping the whole process (and forcing the removal of all
1409 * DLLs) the library will be freed anyway
1411 if (process_detaching) retv = TRUE;
1412 else
1414 free_lib_count++;
1415 if ((wm = MODULE32_LookupHMODULE( hLibModule ))) retv = MODULE_FreeLibrary( wm );
1416 free_lib_count--;
1419 RtlLeaveCriticalSection( &loader_section );
1421 return retv;
1424 /***********************************************************************
1425 * MODULE_DecRefCount
1427 * NOTE: Assumes that the process critical section is held!
1429 static void MODULE_DecRefCount( WINE_MODREF *wm )
1431 int i;
1433 if ( wm->flags & WINE_MODREF_MARKER )
1434 return;
1436 if ( wm->refCount <= 0 )
1437 return;
1439 --wm->refCount;
1440 TRACE("(%s) refCount: %d\n", wm->modname, wm->refCount );
1442 if ( wm->refCount == 0 )
1444 wm->flags |= WINE_MODREF_MARKER;
1446 for ( i = 0; i < wm->nDeps; i++ )
1447 if ( wm->deps[i] )
1448 MODULE_DecRefCount( wm->deps[i] );
1450 wm->flags &= ~WINE_MODREF_MARKER;
1454 /***********************************************************************
1455 * MODULE_FreeLibrary
1457 * NOTE: Assumes that the process critical section is held!
1459 BOOL MODULE_FreeLibrary( WINE_MODREF *wm )
1461 TRACE("(%s) - START\n", wm->modname );
1463 /* Recursively decrement reference counts */
1464 MODULE_DecRefCount( wm );
1466 /* Call process detach notifications */
1467 if ( free_lib_count <= 1 )
1469 MODULE_DllProcessDetach( FALSE, NULL );
1470 MODULE_FlushModrefs();
1473 TRACE("END\n");
1475 return TRUE;
1479 /***********************************************************************
1480 * FreeLibraryAndExitThread (KERNEL32.@)
1482 VOID WINAPI FreeLibraryAndExitThread(HINSTANCE hLibModule, DWORD dwExitCode)
1484 FreeLibrary(hLibModule);
1485 ExitThread(dwExitCode);
1488 /***********************************************************************
1489 * PrivateLoadLibrary (KERNEL32.@)
1491 * FIXME: rough guesswork, don't know what "Private" means
1493 HINSTANCE16 WINAPI PrivateLoadLibrary(LPCSTR libname)
1495 return LoadLibrary16(libname);
1500 /***********************************************************************
1501 * PrivateFreeLibrary (KERNEL32.@)
1503 * FIXME: rough guesswork, don't know what "Private" means
1505 void WINAPI PrivateFreeLibrary(HINSTANCE16 handle)
1507 FreeLibrary16(handle);
1511 /***********************************************************************
1512 * GetProcAddress16 (KERNEL32.37)
1513 * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
1515 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
1517 if (!hModule) {
1518 WARN("hModule may not be 0!\n");
1519 return (FARPROC16)0;
1521 if (HIWORD(hModule))
1523 WARN("hModule is Win32 handle (%p)\n", hModule );
1524 return (FARPROC16)0;
1526 return GetProcAddress16( LOWORD(hModule), name );
1529 /***********************************************************************
1530 * GetProcAddress (KERNEL.50)
1532 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, LPCSTR name )
1534 WORD ordinal;
1535 FARPROC16 ret;
1537 if (!hModule) hModule = GetCurrentTask();
1538 hModule = GetExePtr( hModule );
1540 if (HIWORD(name) != 0)
1542 ordinal = NE_GetOrdinal( hModule, name );
1543 TRACE("%04x '%s'\n", hModule, name );
1545 else
1547 ordinal = LOWORD(name);
1548 TRACE("%04x %04x\n", hModule, ordinal );
1550 if (!ordinal) return (FARPROC16)0;
1552 ret = NE_GetEntryPoint( hModule, ordinal );
1554 TRACE("returning %08x\n", (UINT)ret );
1555 return ret;
1559 /***********************************************************************
1560 * GetProcAddress (KERNEL32.@)
1562 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1564 NTSTATUS nts;
1565 FARPROC fp;
1567 if (HIWORD(function))
1569 ANSI_STRING str;
1571 RtlInitAnsiString( &str, function );
1572 nts = LdrGetProcedureAddress( hModule, &str, 0, (void**)&fp );
1574 else
1575 nts = LdrGetProcedureAddress( hModule, NULL, (DWORD)function, (void**)&fp );
1576 if (nts != STATUS_SUCCESS)
1578 SetLastError( RtlNtStatusToDosError( nts ) );
1579 fp = NULL;
1581 return fp;
1584 /***********************************************************************
1585 * GetProcAddress32 (KERNEL.453)
1587 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
1589 /* FIXME: we used to disable snoop when returning proc for Win16 subsystem */
1590 return GetProcAddress( hModule, function );
1593 /***************************************************************************
1594 * HasGPHandler (KERNEL.338)
1597 #include "pshpack1.h"
1598 typedef struct _GPHANDLERDEF
1600 WORD selector;
1601 WORD rangeStart;
1602 WORD rangeEnd;
1603 WORD handler;
1604 } GPHANDLERDEF;
1605 #include "poppack.h"
1607 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1609 HMODULE16 hModule;
1610 int gpOrdinal;
1611 SEGPTR gpPtr;
1612 GPHANDLERDEF *gpHandler;
1614 if ( (hModule = FarGetOwner16( SELECTOROF(address) )) != 0
1615 && (gpOrdinal = NE_GetOrdinal( hModule, "__GP" )) != 0
1616 && (gpPtr = (SEGPTR)NE_GetEntryPointEx( hModule, gpOrdinal, FALSE )) != 0
1617 && !IsBadReadPtr16( gpPtr, sizeof(GPHANDLERDEF) )
1618 && (gpHandler = MapSL( gpPtr )) != NULL )
1620 while (gpHandler->selector)
1622 if ( SELECTOROF(address) == gpHandler->selector
1623 && OFFSETOF(address) >= gpHandler->rangeStart
1624 && OFFSETOF(address) < gpHandler->rangeEnd )
1625 return MAKESEGPTR( gpHandler->selector, gpHandler->handler );
1626 gpHandler++;
1630 return 0;