4 * Copyright 1995 Alexandre Julliard
11 #include <sys/types.h>
13 #include "wine/winuser16.h"
14 #include "wine/winbase16.h"
26 #include "selectors.h"
27 #include "stackframe.h"
29 #include "debugtools.h"
31 #include "loadorder.h"
34 DECLARE_DEBUG_CHANNEL(module)
35 DECLARE_DEBUG_CHANNEL(win32)
37 /*************************************************************************
39 * Walk MODREFs for input process ID
41 void MODULE_WalkModref( DWORD id )
44 WINE_MODREF *zwm, *prev = NULL;
45 PDB *pdb = PROCESS_IdToPDB( id );
48 MESSAGE("Invalid process id (pid)\n");
52 MESSAGE("Modref list for process pdb=%p\n", pdb);
53 MESSAGE("Modref next prev handle deps flags name\n");
54 for ( zwm = pdb->modref_list; zwm; zwm = zwm->next) {
55 MESSAGE("%p %p %p %04x %5d %04x %s\n", zwm, zwm->next, zwm->prev,
56 zwm->module, zwm->nDeps, zwm->flags, zwm->modname);
57 for ( i = 0; i < zwm->nDeps; i++ ) {
59 MESSAGE(" %d %p %s\n", i, zwm->deps[i], zwm->deps[i]->modname);
61 if (prev != zwm->prev)
62 MESSAGE(" --> modref corrupt, previous pointer wrong!!\n");
67 /*************************************************************************
68 * MODULE32_LookupHMODULE
69 * looks for the referenced HMODULE in the current process
71 WINE_MODREF *MODULE32_LookupHMODULE( HMODULE hmod )
76 return PROCESS_Current()->exe_modref;
79 ERR_(module)("tried to lookup 0x%04x in win32 module handler!\n",hmod);
82 for ( wm = PROCESS_Current()->modref_list; wm; wm=wm->next )
83 if (wm->module == hmod)
88 /*************************************************************************
91 static BOOL MODULE_InitDll( WINE_MODREF *wm, DWORD type, LPVOID lpReserved )
95 static LPCSTR typeName[] = { "PROCESS_DETACH", "PROCESS_ATTACH",
96 "THREAD_ATTACH", "THREAD_DETACH" };
100 /* Skip calls for modules loaded with special load flags */
102 if ( ( wm->flags & WINE_MODREF_DONT_RESOLVE_REFS )
103 || ( wm->flags & WINE_MODREF_LOAD_AS_DATAFILE ) )
107 TRACE_(module)("(%s,%s,%p) - CALL\n",
108 wm->modname, typeName[type], lpReserved );
110 /* Call the initialization routine */
114 retv = PE_InitDLL( wm, type, lpReserved );
118 /* no need to do that, dlopen() already does */
122 ERR_(module)("wine_modref type %d not handled.\n", wm->type );
127 TRACE_(module)("(%s,%s,%p) - RETURN %d\n",
128 wm->modname, typeName[type], lpReserved, retv );
133 /*************************************************************************
134 * MODULE_DllProcessAttach
136 * Send the process attach notification to all DLLs the given module
137 * depends on (recursively). This is somewhat complicated due to the fact that
139 * - we have to respect the module dependencies, i.e. modules implicitly
140 * referenced by another module have to be initialized before the module
141 * itself can be initialized
143 * - the initialization routine of a DLL can itself call LoadLibrary,
144 * thereby introducing a whole new set of dependencies (even involving
145 * the 'old' modules) at any time during the whole process
147 * (Note that this routine can be recursively entered not only directly
148 * from itself, but also via LoadLibrary from one of the called initialization
151 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
152 * the process *detach* notifications to be sent in the correct order.
153 * This must not only take into account module dependencies, but also
154 * 'hidden' dependencies created by modules calling LoadLibrary in their
155 * attach notification routine.
157 * The strategy is rather simple: we move a WINE_MODREF to the head of the
158 * list after the attach notification has returned. This implies that the
159 * detach notifications are called in the reverse of the sequence the attach
160 * notifications *returned*.
162 * NOTE: Assumes that the process critical section is held!
165 BOOL MODULE_DllProcessAttach( WINE_MODREF *wm, LPVOID lpReserved )
171 /* prevent infinite recursion in case of cyclical dependencies */
172 if ( ( wm->flags & WINE_MODREF_MARKER )
173 || ( wm->flags & WINE_MODREF_PROCESS_ATTACHED ) )
176 TRACE_(module)("(%s,%p) - START\n",
177 wm->modname, lpReserved );
179 /* Tag current MODREF to prevent recursive loop */
180 wm->flags |= WINE_MODREF_MARKER;
182 /* Recursively attach all DLLs this one depends on */
183 for ( i = 0; retv && i < wm->nDeps; i++ )
185 retv = MODULE_DllProcessAttach( wm->deps[i], lpReserved );
187 /* Call DLL entry point */
190 retv = MODULE_InitDll( wm, DLL_PROCESS_ATTACH, lpReserved );
192 wm->flags |= WINE_MODREF_PROCESS_ATTACHED;
195 /* Re-insert MODREF at head of list */
196 if ( retv && wm->prev )
198 wm->prev->next = wm->next;
199 if ( wm->next ) wm->next->prev = wm->prev;
202 wm->next = PROCESS_Current()->modref_list;
203 PROCESS_Current()->modref_list = wm->next->prev = wm;
206 /* Remove recursion flag */
207 wm->flags &= ~WINE_MODREF_MARKER;
209 TRACE_(module)("(%s,%p) - END\n",
210 wm->modname, lpReserved );
215 /*************************************************************************
216 * MODULE_DllProcessDetach
218 * Send DLL process detach notifications. See the comment about calling
219 * sequence at MODULE_DllProcessAttach. Unless the bForceDetach flag
220 * is set, only DLLs with zero refcount are notified.
222 * NOTE: Assumes that the process critical section is held!
225 void MODULE_DllProcessDetach( BOOL bForceDetach, LPVOID lpReserved )
231 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
233 /* Check whether to detach this DLL */
234 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
236 if ( wm->refCount > 0 && !bForceDetach )
239 /* Call detach notification */
240 wm->flags &= ~WINE_MODREF_PROCESS_ATTACHED;
241 MODULE_InitDll( wm, DLL_PROCESS_DETACH, lpReserved );
243 /* Restart at head of WINE_MODREF list, as entries might have
244 been added and/or removed while performing the call ... */
250 /*************************************************************************
251 * MODULE_DllThreadAttach
253 * Send DLL thread attach notifications. These are sent in the
254 * reverse sequence of process detach notification.
257 void MODULE_DllThreadAttach( LPVOID lpReserved )
261 EnterCriticalSection( &PROCESS_Current()->crit_section );
263 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
267 for ( ; wm; wm = wm->prev )
269 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
271 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
274 MODULE_InitDll( wm, DLL_THREAD_ATTACH, lpReserved );
277 LeaveCriticalSection( &PROCESS_Current()->crit_section );
280 /*************************************************************************
281 * MODULE_DllThreadDetach
283 * Send DLL thread detach notifications. These are sent in the
284 * same sequence as process detach notification.
287 void MODULE_DllThreadDetach( LPVOID lpReserved )
291 EnterCriticalSection( &PROCESS_Current()->crit_section );
293 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
295 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
297 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
300 MODULE_InitDll( wm, DLL_THREAD_DETACH, lpReserved );
303 LeaveCriticalSection( &PROCESS_Current()->crit_section );
306 /****************************************************************************
307 * DisableThreadLibraryCalls (KERNEL32.74)
309 * Don't call DllEntryPoint for DLL_THREAD_{ATTACH,DETACH} if set.
311 BOOL WINAPI DisableThreadLibraryCalls( HMODULE hModule )
316 EnterCriticalSection( &PROCESS_Current()->crit_section );
318 wm = MODULE32_LookupHMODULE( hModule );
322 wm->flags |= WINE_MODREF_NO_DLL_CALLS;
324 LeaveCriticalSection( &PROCESS_Current()->crit_section );
330 /***********************************************************************
331 * MODULE_CreateDummyModule
333 * Create a dummy NE module for Win32 or Winelib.
335 HMODULE MODULE_CreateDummyModule( const OFSTRUCT *ofs, LPCSTR modName )
339 SEGTABLEENTRY *pSegment;
342 const char* basename;
344 INT of_size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName)
345 + strlen(ofs->szPathName) + 1;
346 INT size = sizeof(NE_MODULE) +
347 /* loaded file info */
349 /* segment table: DS,CS */
350 2 * sizeof(SEGTABLEENTRY) +
353 /* several empty tables */
356 hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
357 if (!hModule) return (HMODULE)11; /* invalid exe */
359 FarSetOwner16( hModule, hModule );
360 pModule = (NE_MODULE *)GlobalLock16( hModule );
362 /* Set all used entries */
363 pModule->magic = IMAGE_OS2_SIGNATURE;
370 pModule->heap_size = 0;
371 pModule->stack_size = 0;
372 pModule->seg_count = 2;
373 pModule->modref_count = 0;
374 pModule->nrname_size = 0;
375 pModule->fileinfo = sizeof(NE_MODULE);
376 pModule->os_flags = NE_OSFLAGS_WINDOWS;
377 pModule->expected_version = 0x030a;
378 pModule->self = hModule;
380 /* Set loaded file information */
381 memcpy( pModule + 1, ofs, of_size );
382 ((OFSTRUCT *)(pModule+1))->cBytes = of_size - 1;
384 pSegment = (SEGTABLEENTRY*)((char*)(pModule + 1) + of_size);
385 pModule->seg_table = (int)pSegment - (int)pModule;
388 pSegment->flags = NE_SEGFLAGS_DATA;
389 pSegment->minsize = 0x1000;
396 pStr = (char *)pSegment;
397 pModule->name_table = (int)pStr - (int)pModule;
402 basename = strrchr(ofs->szPathName,'\\');
403 if (!basename) basename = ofs->szPathName;
406 len = strlen(basename);
407 if ((s = strchr(basename,'.'))) len = s - basename;
408 if (len > 8) len = 8;
410 strncpy( pStr+1, basename, len );
411 if (len < 8) pStr[len+1] = 0;
414 /* All tables zero terminated */
415 pModule->res_table = pModule->import_table = pModule->entry_table =
416 (int)pStr - (int)pModule;
418 NE_RegisterModule( pModule );
423 /***********************************************************************
424 * MODULE_GetWndProcEntry16 (not a Windows API function)
426 * Return an entry point from the WPROCS dll.
428 FARPROC16 MODULE_GetWndProcEntry16( LPCSTR name )
430 FARPROC16 ret = NULL;
434 /* FIXME: hack for Winelib */
435 extern LRESULT ColorDlgProc16(HWND16,UINT16,WPARAM16,LPARAM);
436 extern LRESULT FileOpenDlgProc16(HWND16,UINT16,WPARAM16,LPARAM);
437 extern LRESULT FileSaveDlgProc16(HWND16,UINT16,WPARAM16,LPARAM);
438 extern LRESULT FindTextDlgProc16(HWND16,UINT16,WPARAM16,LPARAM);
439 extern LRESULT PrintDlgProc16(HWND16,UINT16,WPARAM16,LPARAM);
440 extern LRESULT PrintSetupDlgProc16(HWND16,UINT16,WPARAM16,LPARAM);
441 extern LRESULT ReplaceTextDlgProc16(HWND16,UINT16,WPARAM16,LPARAM);
443 if (!strcmp(name,"ColorDlgProc"))
444 return (FARPROC16)ColorDlgProc16;
445 if (!strcmp(name,"FileOpenDlgProc"))
446 return (FARPROC16)FileOpenDlgProc16;
447 if (!strcmp(name,"FileSaveDlgProc"))
448 return (FARPROC16)FileSaveDlgProc16;
449 if (!strcmp(name,"FindTextDlgProc"))
450 return (FARPROC16)FindTextDlgProc16;
451 if (!strcmp(name,"PrintDlgProc"))
452 return (FARPROC16)PrintDlgProc16;
453 if (!strcmp(name,"PrintSetupDlgProc"))
454 return (FARPROC16)PrintSetupDlgProc16;
455 if (!strcmp(name,"ReplaceTextDlgProc"))
456 return (FARPROC16)ReplaceTextDlgProc16;
457 FIXME_(module)("No mapping for %s(), add one in library/miscstubs.c\n",name);
464 static HMODULE hModule = 0;
466 if (!hModule) hModule = GetModuleHandle16( "WPROCS" );
467 ordinal = NE_GetOrdinal( hModule, name );
468 if (!(ret = NE_GetEntryPoint( hModule, ordinal )))
470 WARN_(module)("%s not found\n", name );
478 /**********************************************************************
479 * MODULE_FindModule32
481 * Find a (loaded) win32 module depending on path
482 * The handling of '.' is a bit weird, but we need it that way,
483 * for sometimes the programs use '<name>.exe' and '<name>.dll' and
484 * this is the only way to differentiate. (mainly hypertrm.exe)
487 * the module handle if found
490 WINE_MODREF *MODULE_FindModule(
491 LPCSTR path /* [in] pathname of module/library to be found */
497 if (!(filename = strrchr( path, '\\' )))
498 filename = HEAP_strdupA( GetProcessHeap(), 0, path );
500 filename = HEAP_strdupA( GetProcessHeap(), 0, filename+1 );
501 dotptr=strrchr(filename,'.');
503 for ( wm = PROCESS_Current()->modref_list; wm; wm=wm->next ) {
504 LPSTR xmodname,xdotptr;
506 assert (wm->modname);
507 xmodname = HEAP_strdupA( GetProcessHeap(), 0, wm->modname );
508 xdotptr=strrchr(xmodname,'.');
509 if ( (xdotptr && !dotptr) ||
512 if (dotptr) *dotptr = '\0';
513 if (xdotptr) *xdotptr = '\0';
515 if (!strcasecmp( filename, xmodname)) {
516 HeapFree( GetProcessHeap(), 0, filename );
517 HeapFree( GetProcessHeap(), 0, xmodname );
520 if (dotptr) *dotptr='.';
521 /* FIXME: add paths, shortname */
522 HeapFree( GetProcessHeap(), 0, xmodname );
524 /* if that fails, try looking for the filename... */
525 for ( wm = PROCESS_Current()->modref_list; wm; wm=wm->next ) {
526 LPSTR xlname,xdotptr;
528 assert (wm->longname);
529 xlname = strrchr(wm->longname,'\\');
531 xlname = wm->longname;
534 xlname = HEAP_strdupA( GetProcessHeap(), 0, xlname );
535 xdotptr=strrchr(xlname,'.');
536 if ( (xdotptr && !dotptr) ||
539 if (dotptr) *dotptr = '\0';
540 if (xdotptr) *xdotptr = '\0';
542 if (!strcasecmp( filename, xlname)) {
543 HeapFree( GetProcessHeap(), 0, filename );
544 HeapFree( GetProcessHeap(), 0, xlname );
547 if (dotptr) *dotptr='.';
548 /* FIXME: add paths, shortname */
549 HeapFree( GetProcessHeap(), 0, xlname );
551 HeapFree( GetProcessHeap(), 0, filename );
555 /***********************************************************************
556 * MODULE_GetBinaryType
558 * The GetBinaryType function determines whether a file is executable
559 * or not and if it is it returns what type of executable it is.
560 * The type of executable is a property that determines in which
561 * subsystem an executable file runs under.
563 * Binary types returned:
564 * SCS_32BIT_BINARY: A Win32 based application
565 * SCS_DOS_BINARY: An MS-Dos based application
566 * SCS_WOW_BINARY: A Win16 based application
567 * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
568 * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
569 * SCS_OS216_BINARY: A 16bit OS/2 based application
571 * Returns TRUE if the file is an executable in which case
572 * the value pointed by lpBinaryType is set.
573 * Returns FALSE if the file is not an executable or if the function fails.
575 * To do so it opens the file and reads in the header information
576 * if the extended header information is not presend it will
577 * assume that that the file is a DOS executable.
578 * If the extended header information is present it will
579 * determine if the file is an 16 or 32 bit Windows executable
580 * by check the flags in the header.
582 * Note that .COM and .PIF files are only recognized by their
583 * file name extension; but Windows does it the same way ...
585 static BOOL MODULE_GetBinaryType( HFILE hfile, OFSTRUCT *ofs,
586 LPDWORD lpBinaryType )
588 IMAGE_DOS_HEADER mz_header;
591 /* Seek to the start of the file and read the DOS header information.
593 if ( _llseek( hfile, 0, SEEK_SET ) >= 0 &&
594 _lread( hfile, &mz_header, sizeof(mz_header) ) == sizeof(mz_header) )
596 /* Now that we have the header check the e_magic field
597 * to see if this is a dos image.
599 if ( mz_header.e_magic == IMAGE_DOS_SIGNATURE )
601 BOOL lfanewValid = FALSE;
602 /* We do have a DOS image so we will now try to seek into
603 * the file by the amount indicated by the field
604 * "Offset to extended header" and read in the
605 * "magic" field information at that location.
606 * This will tell us if there is more header information
609 /* But before we do we will make sure that header
610 * structure encompasses the "Offset to extended header"
613 if ( (mz_header.e_cparhdr<<4) >= sizeof(IMAGE_DOS_HEADER) )
614 if ( ( mz_header.e_crlc == 0 && mz_header.e_lfarlc == 0 ) ||
615 ( mz_header.e_lfarlc >= sizeof(IMAGE_DOS_HEADER) ) )
616 if ( mz_header.e_lfanew >= sizeof(IMAGE_DOS_HEADER) &&
617 _llseek( hfile, mz_header.e_lfanew, SEEK_SET ) >= 0 &&
618 _lread( hfile, magic, sizeof(magic) ) == sizeof(magic) )
623 /* If we cannot read this "extended header" we will
624 * assume that we have a simple DOS executable.
626 *lpBinaryType = SCS_DOS_BINARY;
631 /* Reading the magic field succeeded so
632 * we will try to determine what type it is.
634 if ( *(DWORD*)magic == IMAGE_NT_SIGNATURE )
636 /* This is an NT signature.
638 *lpBinaryType = SCS_32BIT_BINARY;
641 else if ( *(WORD*)magic == IMAGE_OS2_SIGNATURE )
643 /* The IMAGE_OS2_SIGNATURE indicates that the
644 * "extended header is a Windows executable (NE)
645 * header." This can mean either a 16-bit OS/2
646 * or a 16-bit Windows or even a DOS program
647 * (running under a DOS extender). To decide
648 * which, we'll have to read the NE header.
652 if ( _llseek( hfile, mz_header.e_lfanew, SEEK_SET ) >= 0 &&
653 _lread( hfile, &ne, sizeof(ne) ) == sizeof(ne) )
655 switch ( ne.operating_system )
657 case 2: *lpBinaryType = SCS_WOW_BINARY; return TRUE;
658 case 5: *lpBinaryType = SCS_DOS_BINARY; return TRUE;
659 default: *lpBinaryType = SCS_OS216_BINARY; return TRUE;
662 /* Couldn't read header, so abort. */
667 /* Unknown extended header, so abort.
675 /* If we get here, we don't even have a correct MZ header.
676 * Try to check the file extension for known types ...
678 ptr = strrchr( ofs->szPathName, '.' );
679 if ( ptr && !strchr( ptr, '\\' ) && !strchr( ptr, '/' ) )
681 if ( !lstrcmpiA( ptr, ".COM" ) )
683 *lpBinaryType = SCS_DOS_BINARY;
687 if ( !lstrcmpiA( ptr, ".PIF" ) )
689 *lpBinaryType = SCS_PIF_BINARY;
697 /***********************************************************************
698 * GetBinaryTypeA [KERNEL32.280]
700 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
706 TRACE_(win32)("%s\n", lpApplicationName );
710 if ( lpApplicationName == NULL || lpBinaryType == NULL )
713 /* Open the file indicated by lpApplicationName for reading.
715 if ( (hfile = OpenFile( lpApplicationName, &ofs, OF_READ )) == HFILE_ERROR )
720 ret = MODULE_GetBinaryType( hfile, &ofs, lpBinaryType );
724 CloseHandle( hfile );
729 /***********************************************************************
730 * GetBinaryTypeW [KERNEL32.281]
732 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
737 TRACE_(win32)("%s\n", debugstr_w(lpApplicationName) );
741 if ( lpApplicationName == NULL || lpBinaryType == NULL )
744 /* Convert the wide string to a ascii string.
746 strNew = HEAP_strdupWtoA( GetProcessHeap(), 0, lpApplicationName );
748 if ( strNew != NULL )
750 ret = GetBinaryTypeA( strNew, lpBinaryType );
752 /* Free the allocated string.
754 HeapFree( GetProcessHeap(), 0, strNew );
760 /**********************************************************************
761 * MODULE_CreateUnixProcess
763 static BOOL MODULE_CreateUnixProcess( LPCSTR filename, LPCSTR lpCmdLine,
764 LPSTARTUPINFOA lpStartupInfo,
765 LPPROCESS_INFORMATION lpProcessInfo,
768 DOS_FULL_NAME full_name;
769 const char *unixfilename = filename;
770 const char *argv[256], **argptr;
773 /* Get Unix file name and iconic flag */
775 if ( lpStartupInfo->dwFlags & STARTF_USESHOWWINDOW )
776 if ( lpStartupInfo->wShowWindow == SW_SHOWMINIMIZED
777 || lpStartupInfo->wShowWindow == SW_SHOWMINNOACTIVE )
780 if ( strchr(filename, '/')
781 || strchr(filename, ':')
782 || strchr(filename, '\\') )
784 if ( DOSFS_GetFullName( filename, TRUE, &full_name ) )
785 unixfilename = full_name.long_name;
790 SetLastError( ERROR_FILE_NOT_FOUND );
794 /* Build argument list */
799 char *p = strdup(lpCmdLine);
800 *argptr++ = unixfilename;
801 if (iconic) *argptr++ = "-iconic";
804 while (*p && (*p == ' ' || *p == '\t')) *p++ = '\0';
807 while (*p && *p != ' ' && *p != '\t') p++;
813 if (iconic) *argptr++ = "-iconic";
814 *argptr++ = lpCmdLine;
818 /* Fork and execute */
822 /* Note: don't use Wine routines here, as this process
823 has not been correctly initialized! */
825 execvp( argv[0], (char**)argv );
829 fprintf( stderr, "CreateProcess: can't exec 'wine %s'\n",
834 /* Fake success return value */
836 memset( lpProcessInfo, '\0', sizeof( *lpProcessInfo ) );
837 lpProcessInfo->hProcess = INVALID_HANDLE_VALUE;
838 lpProcessInfo->hThread = INVALID_HANDLE_VALUE;
840 SetLastError( ERROR_SUCCESS );
844 /***********************************************************************
845 * WinExec16 (KERNEL.166)
847 HINSTANCE16 WINAPI WinExec16( LPCSTR lpCmdLine, UINT16 nCmdShow )
851 SYSLEVEL_ReleaseWin16Lock();
852 hInst = WinExec( lpCmdLine, nCmdShow );
853 SYSLEVEL_RestoreWin16Lock();
858 /***********************************************************************
859 * WinExec (KERNEL32.566)
861 HINSTANCE WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
864 UINT16 paramCmdShow[2];
867 return 2; /* File not found */
869 /* Set up LOADPARAMS buffer for LoadModule */
871 memset( ¶ms, '\0', sizeof(params) );
872 params.lpCmdLine = (LPSTR)lpCmdLine;
873 params.lpCmdShow = paramCmdShow;
874 params.lpCmdShow[0] = 2;
875 params.lpCmdShow[1] = nCmdShow;
877 /* Now load the executable file */
879 return LoadModule( NULL, ¶ms );
882 /**********************************************************************
883 * LoadModule (KERNEL32.499)
885 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
887 LOADPARAMS *params = (LOADPARAMS *)paramBlock;
888 PROCESS_INFORMATION info;
889 STARTUPINFOA startup;
894 memset( &startup, '\0', sizeof(startup) );
895 startup.cb = sizeof(startup);
896 startup.dwFlags = STARTF_USESHOWWINDOW;
897 startup.wShowWindow = params->lpCmdShow? params->lpCmdShow[1] : 0;
899 if ( !CreateProcessA( name, params->lpCmdLine,
900 NULL, NULL, FALSE, 0, params->lpEnvAddress,
901 NULL, &startup, &info ) )
903 hInstance = GetLastError();
904 if ( hInstance < 32 ) return hInstance;
906 FIXME_(module)("Strange error set by CreateProcess: %d\n", hInstance );
910 /* Get 16-bit hInstance/hTask from process */
911 pdb = PROCESS_IdToPDB( info.dwProcessId );
912 tdb = pdb? (TDB *)GlobalLock16( pdb->task ) : NULL;
913 hInstance = tdb && tdb->hInstance? tdb->hInstance : pdb? pdb->task : 0;
914 /* If there is no hInstance (32-bit process) return a dummy value
916 * FIXME: should do this in all cases and fix Win16 callers */
917 if (!hInstance) hInstance = 33;
919 /* Close off the handles */
920 CloseHandle( info.hThread );
921 CloseHandle( info.hProcess );
926 /*************************************************************************
929 * Get next blank delimited token from input string. If quoted then
930 * process till matching quote and then till blank.
932 * Returns number of characters in token (not including \0). On
933 * end of string (EOS), returns a 0.
935 * from (IO) address of start of input string to scan, updated to
936 * next non-processed character.
937 * to (IO) address of start of output string (previous token \0
938 * char), updated to end of new output string (the \0
941 static int get_makename_token(LPCSTR *from, LPSTR *to )
944 LPCSTR to_old = *to; /* only used for tracing */
946 while ( **from == ' ') {
947 /* Copy leading blanks (separators between previous */
948 /* token and this token). */
955 while ( (**from != 0) && (**from != ' ') && (**from != '"') ) {
956 **to = **from; (*from)++; (*to)++; len++;
958 if ( **from == '"' ) {
959 /* Handle quoted string. */
961 if ( !strchr(*from, '"') ) {
962 /* fail - no closing quote. Return entire string */
963 while ( **from != 0 ) {
964 **to = **from; (*from)++; (*to)++; len++;
968 while( **from != '"') {
978 /* either EOS or ' ' */
983 **to = 0; /* terminate output string */
985 TRACE_(module)("returning token len=%d, string=%s\n",
991 /*************************************************************************
992 * make_lpCommandLine_name
994 * Try longer and longer strings from "line" to find an existing
995 * file name. Each attempt is delimited by a blank outside of quotes.
996 * Also will attempt to append ".exe" if requested and not already
997 * present. Returns the address of the remaining portion of the
1002 static BOOL make_lpCommandLine_name( LPCSTR line, LPSTR name, int namelen,
1014 /* scan over initial blanks if any */
1015 while ( *from == ' ') from++;
1017 /* get a token and append to previous data the check for existance */
1019 if ( !get_makename_token( &from, &to ) ) {
1020 /* EOS has occured and not found - exit */
1025 TRACE_(module)("checking if file exists '%s'\n", name);
1026 retlen = SearchPathA( NULL, name, ".exe", sizeof(buffer), buffer, &lastpart);
1027 if ( retlen && (retlen < sizeof(buffer)) ) break;
1030 /* if we have a non-null full path name in buffer then move to output */
1032 if ( strlen(buffer) <= namelen ) {
1033 strcpy( name, buffer );
1035 /* not enough space to return full path string */
1036 FIXME_(module)("internal string not long enough, need %d\n",
1041 /* all done, indicate end of module name and then trace and exit */
1042 if (after) *after = from;
1043 TRACE_(module)("%i, selected file name '%s'\n and cmdline as %s\n",
1044 found, name, debugstr_a(from));
1048 /*************************************************************************
1049 * make_lpApplicationName_name
1051 * Scan input string (the lpApplicationName) and remove any quotes
1052 * if they are balanced.
1056 static BOOL make_lpApplicationName_name( LPCSTR line, LPSTR name, int namelen)
1059 LPSTR to, to_end, to_old;
1060 DOS_FULL_NAME full_name;
1063 to_end = to + namelen - 1;
1066 while ( *line == ' ' ) line++; /* point to beginning of string */
1069 /* Copy all input till end, or quote */
1070 while((*from != 0) && (*from != '"') && (to < to_end))
1072 if (to >= to_end) { *to = 0; break; }
1076 /* Handle quoted string. If there is a closing quote, copy all */
1077 /* that is inside. */
1079 if (!strchr(from, '"'))
1081 /* fail - no closing quote */
1082 to = to_old; /* restore to previous attempt */
1083 *to = 0; /* end string */
1084 break; /* exit with previous attempt */
1086 while((*from != '"') && (to < to_end)) *to++ = *from++;
1087 if (to >= to_end) { *to = 0; break; }
1089 continue; /* past quoted string, so restart from top */
1092 *to = 0; /* terminate output string */
1093 to_old = to; /* save for possible use in unmatched quote case */
1095 /* loop around keeping the blank as part of file name */
1097 break; /* exit if out of input string */
1100 if (!DOSFS_GetFullName(name, TRUE, &full_name)) {
1101 TRACE_(module)("file not found '%s'\n", name );
1105 if (strlen(full_name.long_name) >= namelen ) {
1106 FIXME_(module)("name longer than buffer (len=%d), file=%s\n",
1107 namelen, full_name.long_name);
1110 strcpy(name, full_name.long_name);
1112 TRACE_(module)("selected as file name '%s'\n", name );
1116 /**********************************************************************
1117 * CreateProcessA (KERNEL32.171)
1119 BOOL WINAPI CreateProcessA( LPCSTR lpApplicationName, LPSTR lpCommandLine,
1120 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1121 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1122 BOOL bInheritHandles, DWORD dwCreationFlags,
1123 LPVOID lpEnvironment, LPCSTR lpCurrentDirectory,
1124 LPSTARTUPINFOA lpStartupInfo,
1125 LPPROCESS_INFORMATION lpProcessInfo )
1128 BOOL found_file = FALSE;
1133 LPCSTR cmdline = NULL;
1135 /* Get name and command line */
1137 if (!lpApplicationName && !lpCommandLine)
1139 SetLastError( ERROR_FILE_NOT_FOUND );
1143 /* Process the AppName or CmdLine to get module name and path */
1147 if (lpApplicationName) {
1148 found_file = make_lpApplicationName_name( lpApplicationName, name, sizeof(name) );
1149 cmdline = (lpCommandLine) ? lpCommandLine : lpApplicationName ;
1152 found_file = make_lpCommandLine_name( lpCommandLine, name, sizeof ( name ), &cmdline );
1154 if ( !found_file ) {
1155 /* make an early exit if file not found - save second pass */
1156 SetLastError( ERROR_FILE_NOT_FOUND );
1160 /* Warn if unsupported features are used */
1162 if (dwCreationFlags & CREATE_SUSPENDED)
1163 FIXME_(module)("(%s,...): CREATE_SUSPENDED ignored\n", name);
1164 if (dwCreationFlags & DETACHED_PROCESS)
1165 FIXME_(module)("(%s,...): DETACHED_PROCESS ignored\n", name);
1166 if (dwCreationFlags & CREATE_NEW_CONSOLE)
1167 FIXME_(module)("(%s,...): CREATE_NEW_CONSOLE ignored\n", name);
1168 if (dwCreationFlags & NORMAL_PRIORITY_CLASS)
1169 FIXME_(module)("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
1170 if (dwCreationFlags & IDLE_PRIORITY_CLASS)
1171 FIXME_(module)("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
1172 if (dwCreationFlags & HIGH_PRIORITY_CLASS)
1173 FIXME_(module)("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
1174 if (dwCreationFlags & REALTIME_PRIORITY_CLASS)
1175 FIXME_(module)("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
1176 if (dwCreationFlags & CREATE_NEW_PROCESS_GROUP)
1177 FIXME_(module)("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
1178 if (dwCreationFlags & CREATE_UNICODE_ENVIRONMENT)
1179 FIXME_(module)("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
1180 if (dwCreationFlags & CREATE_SEPARATE_WOW_VDM)
1181 FIXME_(module)("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
1182 if (dwCreationFlags & CREATE_SHARED_WOW_VDM)
1183 FIXME_(module)("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
1184 if (dwCreationFlags & CREATE_DEFAULT_ERROR_MODE)
1185 FIXME_(module)("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
1186 if (dwCreationFlags & CREATE_NO_WINDOW)
1187 FIXME_(module)("(%s,...): CREATE_NO_WINDOW ignored\n", name);
1188 if (dwCreationFlags & PROFILE_USER)
1189 FIXME_(module)("(%s,...): PROFILE_USER ignored\n", name);
1190 if (dwCreationFlags & PROFILE_KERNEL)
1191 FIXME_(module)("(%s,...): PROFILE_KERNEL ignored\n", name);
1192 if (dwCreationFlags & PROFILE_SERVER)
1193 FIXME_(module)("(%s,...): PROFILE_SERVER ignored\n", name);
1194 if (lpCurrentDirectory)
1195 FIXME_(module)("(%s,...): lpCurrentDirectory %s ignored\n",
1196 name, lpCurrentDirectory);
1197 if (lpStartupInfo->lpDesktop)
1198 FIXME_(module)("(%s,...): lpStartupInfo->lpDesktop %s ignored\n",
1199 name, lpStartupInfo->lpDesktop);
1200 if (lpStartupInfo->lpTitle)
1201 FIXME_(module)("(%s,...): lpStartupInfo->lpTitle %s ignored\n",
1202 name, lpStartupInfo->lpTitle);
1203 if (lpStartupInfo->dwFlags & STARTF_USECOUNTCHARS)
1204 FIXME_(module)("(%s,...): STARTF_USECOUNTCHARS (%ld,%ld) ignored\n",
1205 name, lpStartupInfo->dwXCountChars, lpStartupInfo->dwYCountChars);
1206 if (lpStartupInfo->dwFlags & STARTF_USEFILLATTRIBUTE)
1207 FIXME_(module)("(%s,...): STARTF_USEFILLATTRIBUTE %lx ignored\n",
1208 name, lpStartupInfo->dwFillAttribute);
1209 if (lpStartupInfo->dwFlags & STARTF_RUNFULLSCREEN)
1210 FIXME_(module)("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
1211 if (lpStartupInfo->dwFlags & STARTF_FORCEONFEEDBACK)
1212 FIXME_(module)("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
1213 if (lpStartupInfo->dwFlags & STARTF_FORCEOFFFEEDBACK)
1214 FIXME_(module)("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
1215 if (lpStartupInfo->dwFlags & STARTF_USEHOTKEY)
1216 FIXME_(module)("(%s,...): STARTF_USEHOTKEY ignored\n", name);
1218 /* When in WineLib, always fork new Unix process */
1221 return MODULE_CreateUnixProcess( name, cmdline,
1222 lpStartupInfo, lpProcessInfo, TRUE );
1224 /* Check for special case: second instance of NE module */
1226 lstrcpynA( ofs.szPathName, name, sizeof( ofs.szPathName ) );
1227 retv = NE_CreateProcess( HFILE_ERROR, &ofs, cmdline, lpEnvironment,
1228 lpProcessAttributes, lpThreadAttributes,
1229 bInheritHandles, dwCreationFlags,
1230 lpStartupInfo, lpProcessInfo );
1232 /* Load file and create process */
1236 /* Open file and determine executable type */
1238 if ( (hFile = OpenFile( name, &ofs, OF_READ )) == HFILE_ERROR )
1240 SetLastError( ERROR_FILE_NOT_FOUND );
1244 if ( !MODULE_GetBinaryType( hFile, &ofs, &type ) )
1246 CloseHandle( hFile );
1248 /* FIXME: Try Unix executable only when appropriate! */
1249 if ( MODULE_CreateUnixProcess( name, cmdline,
1250 lpStartupInfo, lpProcessInfo, FALSE ) )
1253 SetLastError( ERROR_BAD_FORMAT );
1258 /* Create process */
1262 case SCS_32BIT_BINARY:
1263 retv = PE_CreateProcess( hFile, &ofs, cmdline, lpEnvironment,
1264 lpProcessAttributes, lpThreadAttributes,
1265 bInheritHandles, dwCreationFlags,
1266 lpStartupInfo, lpProcessInfo );
1269 case SCS_DOS_BINARY:
1270 retv = MZ_CreateProcess( hFile, &ofs, cmdline, lpEnvironment,
1271 lpProcessAttributes, lpThreadAttributes,
1272 bInheritHandles, dwCreationFlags,
1273 lpStartupInfo, lpProcessInfo );
1276 case SCS_WOW_BINARY:
1277 retv = NE_CreateProcess( hFile, &ofs, cmdline, lpEnvironment,
1278 lpProcessAttributes, lpThreadAttributes,
1279 bInheritHandles, dwCreationFlags,
1280 lpStartupInfo, lpProcessInfo );
1283 case SCS_PIF_BINARY:
1284 case SCS_POSIX_BINARY:
1285 case SCS_OS216_BINARY:
1286 FIXME_(module)("Unsupported executable type: %ld\n", type );
1290 SetLastError( ERROR_BAD_FORMAT );
1295 CloseHandle( hFile );
1300 /**********************************************************************
1301 * CreateProcessW (KERNEL32.172)
1303 * lpReserved is not converted
1305 BOOL WINAPI CreateProcessW( LPCWSTR lpApplicationName, LPWSTR lpCommandLine,
1306 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1307 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1308 BOOL bInheritHandles, DWORD dwCreationFlags,
1309 LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory,
1310 LPSTARTUPINFOW lpStartupInfo,
1311 LPPROCESS_INFORMATION lpProcessInfo )
1313 STARTUPINFOA StartupInfoA;
1315 LPSTR lpApplicationNameA = HEAP_strdupWtoA (GetProcessHeap(),0,lpApplicationName);
1316 LPSTR lpCommandLineA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCommandLine);
1317 LPSTR lpCurrentDirectoryA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCurrentDirectory);
1319 memcpy (&StartupInfoA, lpStartupInfo, sizeof(STARTUPINFOA));
1320 StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpDesktop);
1321 StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpTitle);
1323 TRACE_(win32)("(%s,%s,...)\n", debugstr_w(lpApplicationName), debugstr_w(lpCommandLine));
1325 if (lpStartupInfo->lpReserved)
1326 FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n", debugstr_w(lpStartupInfo->lpReserved));
1328 ret = CreateProcessA( lpApplicationNameA, lpCommandLineA,
1329 lpProcessAttributes, lpThreadAttributes,
1330 bInheritHandles, dwCreationFlags,
1331 lpEnvironment, lpCurrentDirectoryA,
1332 &StartupInfoA, lpProcessInfo );
1334 HeapFree( GetProcessHeap(), 0, lpCurrentDirectoryA );
1335 HeapFree( GetProcessHeap(), 0, lpCommandLineA );
1336 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1337 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1342 /***********************************************************************
1343 * GetModuleHandle (KERNEL32.237)
1345 HMODULE WINAPI GetModuleHandleA(LPCSTR module)
1349 if ( module == NULL )
1350 wm = PROCESS_Current()->exe_modref;
1352 wm = MODULE_FindModule( module );
1354 return wm? wm->module : 0;
1357 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
1360 LPSTR modulea = HEAP_strdupWtoA( GetProcessHeap(), 0, module );
1361 hModule = GetModuleHandleA( modulea );
1362 HeapFree( GetProcessHeap(), 0, modulea );
1367 /***********************************************************************
1368 * GetModuleFileName32A (KERNEL32.235)
1370 DWORD WINAPI GetModuleFileNameA(
1371 HMODULE hModule, /* [in] module handle (32bit) */
1372 LPSTR lpFileName, /* [out] filenamebuffer */
1373 DWORD size /* [in] size of filenamebuffer */
1375 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1377 if (!wm) /* can happen on start up or the like */
1380 if (PE_HEADER(wm->module)->OptionalHeader.MajorOperatingSystemVersion >= 4.0)
1381 lstrcpynA( lpFileName, wm->longname, size );
1383 lstrcpynA( lpFileName, wm->shortname, size );
1385 TRACE_(module)("%s\n", lpFileName );
1386 return strlen(lpFileName);
1390 /***********************************************************************
1391 * GetModuleFileName32W (KERNEL32.236)
1393 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName,
1396 LPSTR fnA = (char*)HeapAlloc( GetProcessHeap(), 0, size );
1397 DWORD res = GetModuleFileNameA( hModule, fnA, size );
1398 lstrcpynAtoW( lpFileName, fnA, size );
1399 HeapFree( GetProcessHeap(), 0, fnA );
1404 /***********************************************************************
1405 * LoadLibraryEx32W (KERNEL.513)
1407 HMODULE WINAPI LoadLibraryEx32W16( LPCSTR libname, HANDLE16 hf,
1412 SYSLEVEL_ReleaseWin16Lock();
1413 hModule = LoadLibraryExA( libname, hf, flags );
1414 SYSLEVEL_RestoreWin16Lock();
1419 /***********************************************************************
1420 * LoadLibrary32_16 (KERNEL.452)
1422 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
1424 return LoadLibraryEx32W16( libname, 0, 0 );
1427 /***********************************************************************
1428 * LoadLibraryExA (KERNEL32)
1430 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HFILE hfile, DWORD flags)
1436 SetLastError(ERROR_INVALID_PARAMETER);
1440 EnterCriticalSection(&PROCESS_Current()->crit_section);
1442 wm = MODULE_LoadLibraryExA( libname, hfile, flags );
1444 if(wm && !MODULE_DllProcessAttach(wm, NULL))
1446 WARN_(module)("Attach failed for module '%s', \n", libname);
1447 MODULE_FreeLibrary(wm);
1448 SetLastError(ERROR_DLL_INIT_FAILED);
1452 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1454 return wm ? wm->module : 0;
1457 /***********************************************************************
1458 * MODULE_LoadLibraryExA (internal)
1460 * Load a PE style module according to the load order.
1462 * The HFILE parameter is not used and marked reserved in the SDK. I can
1463 * only guess that it should force a file to be mapped, but I rather
1464 * ignore the parameter because it would be extremely difficult to
1465 * integrate this with different types of module represenations.
1468 WINE_MODREF *MODULE_LoadLibraryExA( LPCSTR libname, HFILE hfile, DWORD flags )
1473 module_loadorder_t *plo;
1475 EnterCriticalSection(&PROCESS_Current()->crit_section);
1477 /* Check for already loaded module */
1478 if((pwm = MODULE_FindModule(libname)))
1480 if(!(pwm->flags & WINE_MODREF_MARKER))
1482 TRACE_(module)("Already loaded module '%s' at 0x%08x, count=%d, \n", libname, pwm->module, pwm->refCount);
1483 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1487 plo = MODULE_GetLoadOrder(libname);
1489 for(i = 0; i < MODULE_LOADORDER_NTYPES; i++)
1491 switch(plo->loadorder[i])
1493 case MODULE_LOADORDER_DLL:
1494 TRACE_(module)("Trying native dll '%s'\n", libname);
1495 pwm = PE_LoadLibraryExA(libname, flags, &err);
1498 case MODULE_LOADORDER_ELFDLL:
1499 TRACE_(module)("Trying elfdll '%s'\n", libname);
1500 pwm = ELFDLL_LoadLibraryExA(libname, flags, &err);
1503 case MODULE_LOADORDER_SO:
1504 TRACE_(module)("Trying so-library '%s'\n", libname);
1505 pwm = ELF_LoadLibraryExA(libname, flags, &err);
1508 case MODULE_LOADORDER_BI:
1509 TRACE_(module)("Trying built-in '%s'\n", libname);
1510 pwm = BUILTIN32_LoadLibraryExA(libname, flags, &err);
1514 ERR_(module)("Got invalid loadorder type %d (%s index %d)\n", plo->loadorder[i], plo->modulename, i);
1517 case MODULE_LOADORDER_INVALID: /* We ignore this as it is an empty entry */
1524 /* Initialize DLL just loaded */
1525 TRACE_(module)("Loaded module '%s' at 0x%08x, \n", libname, pwm->module);
1527 /* Set the refCount here so that an attach failure will */
1528 /* decrement the dependencies through the MODULE_FreeLibrary call. */
1531 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1533 if (PROCESS_Current()->flags & PDB32_DEBUGGED)
1534 DEBUG_SendLoadDLLEvent( -1 /*FIXME*/, pwm->module, pwm->modname );
1539 if(err != ERROR_FILE_NOT_FOUND)
1543 ERR_(module)("Failed to load module '%s'; error=0x%08lx, \n", libname, err);
1545 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1549 /***********************************************************************
1550 * LoadLibraryA (KERNEL32)
1552 HMODULE WINAPI LoadLibraryA(LPCSTR libname) {
1553 return LoadLibraryExA(libname,0,0);
1556 /***********************************************************************
1557 * LoadLibraryW (KERNEL32)
1559 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
1561 return LoadLibraryExW(libnameW,0,0);
1564 /***********************************************************************
1565 * LoadLibraryExW (KERNEL32)
1567 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW,HFILE hfile,DWORD flags)
1569 LPSTR libnameA = HEAP_strdupWtoA( GetProcessHeap(), 0, libnameW );
1570 HMODULE ret = LoadLibraryExA( libnameA , hfile, flags );
1572 HeapFree( GetProcessHeap(), 0, libnameA );
1576 /***********************************************************************
1577 * MODULE_FlushModrefs
1579 * NOTE: Assumes that the process critical section is held!
1581 * Remove all unused modrefs and call the internal unloading routines
1582 * for the library type.
1584 static void MODULE_FlushModrefs(void)
1586 WINE_MODREF *wm, *next;
1588 for(wm = PROCESS_Current()->modref_list; wm; wm = next)
1595 /* Unlink this modref from the chain */
1597 wm->next->prev = wm->prev;
1599 wm->prev->next = wm->next;
1600 if(wm == PROCESS_Current()->modref_list)
1601 PROCESS_Current()->modref_list = wm->next;
1604 * The unloaders are also responsible for freeing the modref itself
1605 * because the loaders were responsible for allocating it.
1609 case MODULE32_PE: PE_UnloadLibrary(wm); break;
1610 case MODULE32_ELF: ELF_UnloadLibrary(wm); break;
1611 case MODULE32_ELFDLL: ELFDLL_UnloadLibrary(wm); break;
1612 case MODULE32_BI: BUILTIN32_UnloadLibrary(wm); break;
1615 ERR_(module)("Invalid or unhandled MODREF type %d encountered (wm=%p)\n", wm->type, wm);
1620 /***********************************************************************
1623 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
1628 EnterCriticalSection( &PROCESS_Current()->crit_section );
1629 PROCESS_Current()->free_lib_count++;
1631 wm = MODULE32_LookupHMODULE( hLibModule );
1632 if ( !wm || !hLibModule )
1633 SetLastError( ERROR_INVALID_HANDLE );
1635 retv = MODULE_FreeLibrary( wm );
1637 PROCESS_Current()->free_lib_count--;
1638 LeaveCriticalSection( &PROCESS_Current()->crit_section );
1643 /***********************************************************************
1644 * MODULE_DecRefCount
1646 * NOTE: Assumes that the process critical section is held!
1648 static void MODULE_DecRefCount( WINE_MODREF *wm )
1652 if ( wm->flags & WINE_MODREF_MARKER )
1655 if ( wm->refCount <= 0 )
1659 TRACE_(module)("(%s) refCount: %d\n", wm->modname, wm->refCount );
1661 if ( wm->refCount == 0 )
1663 wm->flags |= WINE_MODREF_MARKER;
1665 for ( i = 0; i < wm->nDeps; i++ )
1667 MODULE_DecRefCount( wm->deps[i] );
1669 wm->flags &= ~WINE_MODREF_MARKER;
1673 /***********************************************************************
1674 * MODULE_FreeLibrary
1676 * NOTE: Assumes that the process critical section is held!
1678 BOOL MODULE_FreeLibrary( WINE_MODREF *wm )
1680 TRACE_(module)("(%s) - START\n", wm->modname );
1682 /* Recursively decrement reference counts */
1683 MODULE_DecRefCount( wm );
1685 /* Call process detach notifications */
1686 if ( PROCESS_Current()->free_lib_count <= 1 )
1688 MODULE_DllProcessDetach( FALSE, NULL );
1689 if (PROCESS_Current()->flags & PDB32_DEBUGGED)
1690 DEBUG_SendUnloadDLLEvent( wm->module );
1693 MODULE_FlushModrefs();
1695 TRACE_(module)("(%s) - END\n", wm->modname );
1701 /***********************************************************************
1702 * FreeLibraryAndExitThread
1704 VOID WINAPI FreeLibraryAndExitThread(HINSTANCE hLibModule, DWORD dwExitCode)
1706 FreeLibrary(hLibModule);
1707 ExitThread(dwExitCode);
1710 /***********************************************************************
1711 * PrivateLoadLibrary (KERNEL32)
1713 * FIXME: rough guesswork, don't know what "Private" means
1715 HINSTANCE WINAPI PrivateLoadLibrary(LPCSTR libname)
1717 return (HINSTANCE)LoadLibrary16(libname);
1722 /***********************************************************************
1723 * PrivateFreeLibrary (KERNEL32)
1725 * FIXME: rough guesswork, don't know what "Private" means
1727 void WINAPI PrivateFreeLibrary(HINSTANCE handle)
1729 FreeLibrary16((HINSTANCE16)handle);
1733 /***********************************************************************
1734 * WIN32_GetProcAddress16 (KERNEL32.36)
1735 * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
1737 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
1743 WARN_(module)("hModule may not be 0!\n");
1744 return (FARPROC16)0;
1746 if (HIWORD(hModule))
1748 WARN_(module)("hModule is Win32 handle (%08x)\n", hModule );
1749 return (FARPROC16)0;
1751 hModule = GetExePtr( hModule );
1753 ordinal = NE_GetOrdinal( hModule, name );
1754 TRACE_(module)("%04x '%s'\n",
1757 ordinal = LOWORD(name);
1758 TRACE_(module)("%04x %04x\n",
1761 if (!ordinal) return (FARPROC16)0;
1762 ret = NE_GetEntryPoint( hModule, ordinal );
1763 TRACE_(module)("returning %08x\n",(UINT)ret);
1767 /***********************************************************************
1768 * GetProcAddress16 (KERNEL.50)
1770 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, SEGPTR name )
1775 if (!hModule) hModule = GetCurrentTask();
1776 hModule = GetExePtr( hModule );
1778 if (HIWORD(name) != 0)
1780 ordinal = NE_GetOrdinal( hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1781 TRACE_(module)("%04x '%s'\n",
1782 hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1786 ordinal = LOWORD(name);
1787 TRACE_(module)("%04x %04x\n",
1790 if (!ordinal) return (FARPROC16)0;
1792 ret = NE_GetEntryPoint( hModule, ordinal );
1794 TRACE_(module)("returning %08x\n", (UINT)ret );
1799 /***********************************************************************
1800 * GetProcAddress32 (KERNEL32.257)
1802 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1804 return MODULE_GetProcAddress( hModule, function, TRUE );
1807 /***********************************************************************
1808 * WIN16_GetProcAddress32 (KERNEL.453)
1810 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
1812 return MODULE_GetProcAddress( hModule, function, FALSE );
1815 /***********************************************************************
1816 * MODULE_GetProcAddress32 (internal)
1818 FARPROC MODULE_GetProcAddress(
1819 HMODULE hModule, /* [in] current module handle */
1820 LPCSTR function, /* [in] function to be looked up */
1823 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1826 if (HIWORD(function))
1827 TRACE_(win32)("(%08lx,%s)\n",(DWORD)hModule,function);
1829 TRACE_(win32)("(%08lx,%p)\n",(DWORD)hModule,function);
1831 SetLastError(ERROR_INVALID_HANDLE);
1837 retproc = PE_FindExportedFunction( wm, function, snoop );
1838 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1841 retproc = ELF_FindExportedFunction( wm, function);
1842 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1845 ERR_(module)("wine_modref type %d not handled.\n",wm->type);
1846 SetLastError(ERROR_INVALID_HANDLE);
1852 /***********************************************************************
1853 * RtlImageNtHeaders (NTDLL)
1855 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
1858 * return hModule+(((IMAGE_DOS_HEADER*)hModule)->e_lfanew);
1859 * but we could get HMODULE16 or the like (think builtin modules)
1862 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1863 if (!wm || (wm->type != MODULE32_PE)) return (PIMAGE_NT_HEADERS)0;
1864 return PE_HEADER(wm->module);
1868 /***************************************************************************
1869 * HasGPHandler (KERNEL.338)
1872 #include "pshpack1.h"
1873 typedef struct _GPHANDLERDEF
1880 #include "poppack.h"
1882 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1887 GPHANDLERDEF *gpHandler;
1889 if ( (hModule = FarGetOwner16( SELECTOROF(address) )) != 0
1890 && (gpOrdinal = NE_GetOrdinal( hModule, "__GP" )) != 0
1891 && (gpPtr = (SEGPTR)NE_GetEntryPointEx( hModule, gpOrdinal, FALSE )) != 0
1892 && !IsBadReadPtr16( gpPtr, sizeof(GPHANDLERDEF) )
1893 && (gpHandler = PTR_SEG_TO_LIN( gpPtr )) != NULL )
1895 while (gpHandler->selector)
1897 if ( SELECTOROF(address) == gpHandler->selector
1898 && OFFSETOF(address) >= gpHandler->rangeStart
1899 && OFFSETOF(address) < gpHandler->rangeEnd )
1900 return PTR_SEG_OFF_TO_SEGPTR( gpHandler->selector,
1901 gpHandler->handler );