4 * Copyright 1995 Alexandre Julliard
11 #include <sys/types.h>
13 #include "wine/winuser16.h"
14 #include "wine/winbase16.h"
27 #include "selectors.h"
28 #include "stackframe.h"
30 #include "debugtools.h"
32 #include "loadorder.h"
35 DECLARE_DEBUG_CHANNEL(module)
36 DECLARE_DEBUG_CHANNEL(win32)
39 /*************************************************************************
40 * MODULE32_LookupHMODULE
41 * looks for the referenced HMODULE in the current process
43 WINE_MODREF *MODULE32_LookupHMODULE( HMODULE hmod )
48 return PROCESS_Current()->exe_modref;
51 ERR_(module)("tried to lookup 0x%04x in win32 module handler!\n",hmod);
54 for ( wm = PROCESS_Current()->modref_list; wm; wm=wm->next )
55 if (wm->module == hmod)
60 /*************************************************************************
63 static BOOL MODULE_InitDll( WINE_MODREF *wm, DWORD type, LPVOID lpReserved )
67 static LPCSTR typeName[] = { "PROCESS_DETACH", "PROCESS_ATTACH",
68 "THREAD_ATTACH", "THREAD_DETACH" };
72 /* Skip calls for modules loaded with special load flags */
74 if ( ( wm->flags & WINE_MODREF_DONT_RESOLVE_REFS )
75 || ( wm->flags & WINE_MODREF_LOAD_AS_DATAFILE ) )
79 TRACE_(module)("(%s,%s,%p) - CALL\n",
80 wm->modname, typeName[type], lpReserved );
82 /* Call the initialization routine */
86 retv = PE_InitDLL( wm, type, lpReserved );
90 /* no need to do that, dlopen() already does */
94 ERR_(module)("wine_modref type %d not handled.\n", wm->type );
99 TRACE_(module)("(%s,%s,%p) - RETURN %d\n",
100 wm->modname, typeName[type], lpReserved, retv );
105 /*************************************************************************
106 * MODULE_DllProcessAttach
108 * Send the process attach notification to all DLLs the given module
109 * depends on (recursively). This is somewhat complicated due to the fact that
111 * - we have to respect the module dependencies, i.e. modules implicitly
112 * referenced by another module have to be initialized before the module
113 * itself can be initialized
115 * - the initialization routine of a DLL can itself call LoadLibrary,
116 * thereby introducing a whole new set of dependencies (even involving
117 * the 'old' modules) at any time during the whole process
119 * (Note that this routine can be recursively entered not only directly
120 * from itself, but also via LoadLibrary from one of the called initialization
123 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
124 * the process *detach* notifications to be sent in the correct order.
125 * This must not only take into account module dependencies, but also
126 * 'hidden' dependencies created by modules calling LoadLibrary in their
127 * attach notification routine.
129 * The strategy is rather simple: we move a WINE_MODREF to the head of the
130 * list after the attach notification has returned. This implies that the
131 * detach notifications are called in the reverse of the sequence the attach
132 * notifications *returned*.
134 * NOTE: Assumes that the process critical section is held!
137 BOOL MODULE_DllProcessAttach( WINE_MODREF *wm, LPVOID lpReserved )
143 /* prevent infinite recursion in case of cyclical dependencies */
144 if ( ( wm->flags & WINE_MODREF_MARKER )
145 || ( wm->flags & WINE_MODREF_PROCESS_ATTACHED ) )
148 TRACE_(module)("(%s,%p) - START\n",
149 wm->modname, lpReserved );
151 /* Tag current MODREF to prevent recursive loop */
152 wm->flags |= WINE_MODREF_MARKER;
154 /* Recursively attach all DLLs this one depends on */
155 for ( i = 0; retv && i < wm->nDeps; i++ )
157 retv = MODULE_DllProcessAttach( wm->deps[i], lpReserved );
159 /* Call DLL entry point */
162 retv = MODULE_InitDll( wm, DLL_PROCESS_ATTACH, lpReserved );
164 wm->flags |= WINE_MODREF_PROCESS_ATTACHED;
167 /* Re-insert MODREF at head of list */
168 if ( retv && wm->prev )
170 wm->prev->next = wm->next;
171 if ( wm->next ) wm->next->prev = wm->prev;
174 wm->next = PROCESS_Current()->modref_list;
175 PROCESS_Current()->modref_list = wm->next->prev = wm;
178 /* Remove recursion flag */
179 wm->flags &= ~WINE_MODREF_MARKER;
181 TRACE_(module)("(%s,%p) - END\n",
182 wm->modname, lpReserved );
187 /*************************************************************************
188 * MODULE_DllProcessDetach
190 * Send DLL process detach notifications. See the comment about calling
191 * sequence at MODULE_DllProcessAttach. Unless the bForceDetach flag
192 * is set, only DLLs with zero refcount are notified.
194 * NOTE: Assumes that the process critical section is held!
197 void MODULE_DllProcessDetach( BOOL bForceDetach, LPVOID lpReserved )
203 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
205 /* Check whether to detach this DLL */
206 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
208 if ( wm->refCount > 0 && !bForceDetach )
211 /* Call detach notification */
212 wm->flags &= ~WINE_MODREF_PROCESS_ATTACHED;
213 MODULE_InitDll( wm, DLL_PROCESS_DETACH, lpReserved );
215 /* Restart at head of WINE_MODREF list, as entries might have
216 been added and/or removed while performing the call ... */
222 /*************************************************************************
223 * MODULE_DllThreadAttach
225 * Send DLL thread attach notifications. These are sent in the
226 * reverse sequence of process detach notification.
229 void MODULE_DllThreadAttach( LPVOID lpReserved )
233 EnterCriticalSection( &PROCESS_Current()->crit_section );
235 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
239 for ( ; wm; wm = wm->prev )
241 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
243 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
246 MODULE_InitDll( wm, DLL_THREAD_ATTACH, lpReserved );
249 LeaveCriticalSection( &PROCESS_Current()->crit_section );
252 /*************************************************************************
253 * MODULE_DllThreadDetach
255 * Send DLL thread detach notifications. These are sent in the
256 * same sequence as process detach notification.
259 void MODULE_DllThreadDetach( LPVOID lpReserved )
263 EnterCriticalSection( &PROCESS_Current()->crit_section );
265 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
267 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
269 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
272 MODULE_InitDll( wm, DLL_THREAD_DETACH, lpReserved );
275 LeaveCriticalSection( &PROCESS_Current()->crit_section );
278 /****************************************************************************
279 * DisableThreadLibraryCalls (KERNEL32.74)
281 * Don't call DllEntryPoint for DLL_THREAD_{ATTACH,DETACH} if set.
283 BOOL WINAPI DisableThreadLibraryCalls( HMODULE hModule )
288 EnterCriticalSection( &PROCESS_Current()->crit_section );
290 wm = MODULE32_LookupHMODULE( hModule );
294 wm->flags |= WINE_MODREF_NO_DLL_CALLS;
296 LeaveCriticalSection( &PROCESS_Current()->crit_section );
302 /***********************************************************************
303 * MODULE_CreateDummyModule
305 * Create a dummy NE module for Win32 or Winelib.
307 HMODULE MODULE_CreateDummyModule( const OFSTRUCT *ofs, LPCSTR modName )
311 SEGTABLEENTRY *pSegment;
314 const char* basename;
316 INT of_size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName)
317 + strlen(ofs->szPathName) + 1;
318 INT size = sizeof(NE_MODULE) +
319 /* loaded file info */
321 /* segment table: DS,CS */
322 2 * sizeof(SEGTABLEENTRY) +
325 /* several empty tables */
328 hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
329 if (!hModule) return (HMODULE)11; /* invalid exe */
331 FarSetOwner16( hModule, hModule );
332 pModule = (NE_MODULE *)GlobalLock16( hModule );
334 /* Set all used entries */
335 pModule->magic = IMAGE_OS2_SIGNATURE;
342 pModule->heap_size = 0;
343 pModule->stack_size = 0;
344 pModule->seg_count = 2;
345 pModule->modref_count = 0;
346 pModule->nrname_size = 0;
347 pModule->fileinfo = sizeof(NE_MODULE);
348 pModule->os_flags = NE_OSFLAGS_WINDOWS;
349 pModule->expected_version = 0x030a;
350 pModule->self = hModule;
352 /* Set loaded file information */
353 memcpy( pModule + 1, ofs, of_size );
354 ((OFSTRUCT *)(pModule+1))->cBytes = of_size - 1;
356 pSegment = (SEGTABLEENTRY*)((char*)(pModule + 1) + of_size);
357 pModule->seg_table = (int)pSegment - (int)pModule;
360 pSegment->flags = NE_SEGFLAGS_DATA;
361 pSegment->minsize = 0x1000;
368 pStr = (char *)pSegment;
369 pModule->name_table = (int)pStr - (int)pModule;
374 basename = strrchr(ofs->szPathName,'\\');
375 if (!basename) basename = ofs->szPathName;
378 len = strlen(basename);
379 if ((s = strchr(basename,'.'))) len = s - basename;
380 if (len > 8) len = 8;
382 strncpy( pStr+1, basename, len );
383 if (len < 8) pStr[len+1] = 0;
386 /* All tables zero terminated */
387 pModule->res_table = pModule->import_table = pModule->entry_table =
388 (int)pStr - (int)pModule;
390 NE_RegisterModule( pModule );
395 /***********************************************************************
396 * MODULE_GetWndProcEntry16 (not a Windows API function)
398 * Return an entry point from the WPROCS dll.
400 FARPROC16 MODULE_GetWndProcEntry16( LPCSTR name )
402 FARPROC16 ret = NULL;
406 /* FIXME: hack for Winelib */
407 extern LRESULT ColorDlgProc16(HWND16,UINT16,WPARAM16,LPARAM);
408 extern LRESULT FileOpenDlgProc16(HWND16,UINT16,WPARAM16,LPARAM);
409 extern LRESULT FileSaveDlgProc16(HWND16,UINT16,WPARAM16,LPARAM);
410 extern LRESULT FindTextDlgProc16(HWND16,UINT16,WPARAM16,LPARAM);
411 extern LRESULT PrintDlgProc16(HWND16,UINT16,WPARAM16,LPARAM);
412 extern LRESULT PrintSetupDlgProc16(HWND16,UINT16,WPARAM16,LPARAM);
413 extern LRESULT ReplaceTextDlgProc16(HWND16,UINT16,WPARAM16,LPARAM);
415 if (!strcmp(name,"ColorDlgProc"))
416 return (FARPROC16)ColorDlgProc16;
417 if (!strcmp(name,"FileOpenDlgProc"))
418 return (FARPROC16)FileOpenDlgProc16;
419 if (!strcmp(name,"FileSaveDlgProc"))
420 return (FARPROC16)FileSaveDlgProc16;
421 if (!strcmp(name,"FindTextDlgProc"))
422 return (FARPROC16)FindTextDlgProc16;
423 if (!strcmp(name,"PrintDlgProc"))
424 return (FARPROC16)PrintDlgProc16;
425 if (!strcmp(name,"PrintSetupDlgProc"))
426 return (FARPROC16)PrintSetupDlgProc16;
427 if (!strcmp(name,"ReplaceTextDlgProc"))
428 return (FARPROC16)ReplaceTextDlgProc16;
429 FIXME_(module)("No mapping for %s(), add one in library/miscstubs.c\n",name);
436 static HMODULE hModule = 0;
438 if (!hModule) hModule = GetModuleHandle16( "WPROCS" );
439 ordinal = NE_GetOrdinal( hModule, name );
440 if (!(ret = NE_GetEntryPoint( hModule, ordinal )))
442 WARN_(module)("%s not found\n", name );
450 /**********************************************************************
451 * MODULE_FindModule32
453 * Find a (loaded) win32 module depending on path
454 * The handling of '.' is a bit weird, but we need it that way,
455 * for sometimes the programs use '<name>.exe' and '<name>.dll' and
456 * this is the only way to differentiate. (mainly hypertrm.exe)
459 * the module handle if found
462 WINE_MODREF *MODULE_FindModule(
463 LPCSTR path /* [in] pathname of module/library to be found */
469 if (!(filename = strrchr( path, '\\' )))
470 filename = HEAP_strdupA( GetProcessHeap(), 0, path );
472 filename = HEAP_strdupA( GetProcessHeap(), 0, filename+1 );
473 dotptr=strrchr(filename,'.');
475 for ( wm = PROCESS_Current()->modref_list; wm; wm=wm->next ) {
476 LPSTR xmodname,xdotptr;
478 assert (wm->modname);
479 xmodname = HEAP_strdupA( GetProcessHeap(), 0, wm->modname );
480 xdotptr=strrchr(xmodname,'.');
481 if ( (xdotptr && !dotptr) ||
484 if (dotptr) *dotptr = '\0';
485 if (xdotptr) *xdotptr = '\0';
487 if (!strcasecmp( filename, xmodname)) {
488 HeapFree( GetProcessHeap(), 0, filename );
489 HeapFree( GetProcessHeap(), 0, xmodname );
492 if (dotptr) *dotptr='.';
493 /* FIXME: add paths, shortname */
494 HeapFree( GetProcessHeap(), 0, xmodname );
496 /* if that fails, try looking for the filename... */
497 for ( wm = PROCESS_Current()->modref_list; wm; wm=wm->next ) {
498 LPSTR xlname,xdotptr;
500 assert (wm->longname);
501 xlname = strrchr(wm->longname,'\\');
503 xlname = wm->longname;
506 xlname = HEAP_strdupA( GetProcessHeap(), 0, xlname );
507 xdotptr=strrchr(xlname,'.');
508 if ( (xdotptr && !dotptr) ||
511 if (dotptr) *dotptr = '\0';
512 if (xdotptr) *xdotptr = '\0';
514 if (!strcasecmp( filename, xlname)) {
515 HeapFree( GetProcessHeap(), 0, filename );
516 HeapFree( GetProcessHeap(), 0, xlname );
519 if (dotptr) *dotptr='.';
520 /* FIXME: add paths, shortname */
521 HeapFree( GetProcessHeap(), 0, xlname );
523 HeapFree( GetProcessHeap(), 0, filename );
527 /***********************************************************************
528 * MODULE_GetBinaryType
530 * The GetBinaryType function determines whether a file is executable
531 * or not and if it is it returns what type of executable it is.
532 * The type of executable is a property that determines in which
533 * subsystem an executable file runs under.
535 * Binary types returned:
536 * SCS_32BIT_BINARY: A Win32 based application
537 * SCS_DOS_BINARY: An MS-Dos based application
538 * SCS_WOW_BINARY: A Win16 based application
539 * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
540 * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
541 * SCS_OS216_BINARY: A 16bit OS/2 based application
543 * Returns TRUE if the file is an executable in which case
544 * the value pointed by lpBinaryType is set.
545 * Returns FALSE if the file is not an executable or if the function fails.
547 * To do so it opens the file and reads in the header information
548 * if the extended header information is not presend it will
549 * assume that that the file is a DOS executable.
550 * If the extended header information is present it will
551 * determine if the file is an 16 or 32 bit Windows executable
552 * by check the flags in the header.
554 * Note that .COM and .PIF files are only recognized by their
555 * file name extension; but Windows does it the same way ...
557 static BOOL MODULE_GetBinaryType( HFILE hfile, OFSTRUCT *ofs,
558 LPDWORD lpBinaryType )
560 IMAGE_DOS_HEADER mz_header;
563 /* Seek to the start of the file and read the DOS header information.
565 if ( _llseek( hfile, 0, SEEK_SET ) >= 0 &&
566 _lread( hfile, &mz_header, sizeof(mz_header) ) == sizeof(mz_header) )
568 /* Now that we have the header check the e_magic field
569 * to see if this is a dos image.
571 if ( mz_header.e_magic == IMAGE_DOS_SIGNATURE )
573 BOOL lfanewValid = FALSE;
574 /* We do have a DOS image so we will now try to seek into
575 * the file by the amount indicated by the field
576 * "Offset to extended header" and read in the
577 * "magic" field information at that location.
578 * This will tell us if there is more header information
581 /* But before we do we will make sure that header
582 * structure encompasses the "Offset to extended header"
585 if ( (mz_header.e_cparhdr<<4) >= sizeof(IMAGE_DOS_HEADER) )
586 if ( ( mz_header.e_crlc == 0 && mz_header.e_lfarlc == 0 ) ||
587 ( mz_header.e_lfarlc >= sizeof(IMAGE_DOS_HEADER) ) )
588 if ( mz_header.e_lfanew >= sizeof(IMAGE_DOS_HEADER) &&
589 _llseek( hfile, mz_header.e_lfanew, SEEK_SET ) >= 0 &&
590 _lread( hfile, magic, sizeof(magic) ) == sizeof(magic) )
595 /* If we cannot read this "extended header" we will
596 * assume that we have a simple DOS executable.
598 *lpBinaryType = SCS_DOS_BINARY;
603 /* Reading the magic field succeeded so
604 * we will try to determine what type it is.
606 if ( *(DWORD*)magic == IMAGE_NT_SIGNATURE )
608 /* This is an NT signature.
610 *lpBinaryType = SCS_32BIT_BINARY;
613 else if ( *(WORD*)magic == IMAGE_OS2_SIGNATURE )
615 /* The IMAGE_OS2_SIGNATURE indicates that the
616 * "extended header is a Windows executable (NE)
617 * header." This can mean either a 16-bit OS/2
618 * or a 16-bit Windows or even a DOS program
619 * (running under a DOS extender). To decide
620 * which, we'll have to read the NE header.
624 if ( _llseek( hfile, mz_header.e_lfanew, SEEK_SET ) >= 0 &&
625 _lread( hfile, &ne, sizeof(ne) ) == sizeof(ne) )
627 switch ( ne.operating_system )
629 case 2: *lpBinaryType = SCS_WOW_BINARY; return TRUE;
630 case 5: *lpBinaryType = SCS_DOS_BINARY; return TRUE;
631 default: *lpBinaryType = SCS_OS216_BINARY; return TRUE;
634 /* Couldn't read header, so abort. */
639 /* Unknown extended header, so abort.
647 /* If we get here, we don't even have a correct MZ header.
648 * Try to check the file extension for known types ...
650 ptr = strrchr( ofs->szPathName, '.' );
651 if ( ptr && !strchr( ptr, '\\' ) && !strchr( ptr, '/' ) )
653 if ( !lstrcmpiA( ptr, ".COM" ) )
655 *lpBinaryType = SCS_DOS_BINARY;
659 if ( !lstrcmpiA( ptr, ".PIF" ) )
661 *lpBinaryType = SCS_PIF_BINARY;
669 /***********************************************************************
670 * GetBinaryTypeA [KERNEL32.280]
672 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
678 TRACE_(win32)("%s\n", lpApplicationName );
682 if ( lpApplicationName == NULL || lpBinaryType == NULL )
685 /* Open the file indicated by lpApplicationName for reading.
687 if ( (hfile = OpenFile( lpApplicationName, &ofs, OF_READ )) == HFILE_ERROR )
692 ret = MODULE_GetBinaryType( hfile, &ofs, lpBinaryType );
696 CloseHandle( hfile );
701 /***********************************************************************
702 * GetBinaryTypeW [KERNEL32.281]
704 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
709 TRACE_(win32)("%s\n", debugstr_w(lpApplicationName) );
713 if ( lpApplicationName == NULL || lpBinaryType == NULL )
716 /* Convert the wide string to a ascii string.
718 strNew = HEAP_strdupWtoA( GetProcessHeap(), 0, lpApplicationName );
720 if ( strNew != NULL )
722 ret = GetBinaryTypeA( strNew, lpBinaryType );
724 /* Free the allocated string.
726 HeapFree( GetProcessHeap(), 0, strNew );
732 /**********************************************************************
733 * MODULE_CreateUnixProcess
735 static BOOL MODULE_CreateUnixProcess( LPCSTR filename, LPCSTR lpCmdLine,
736 LPSTARTUPINFOA lpStartupInfo,
737 LPPROCESS_INFORMATION lpProcessInfo,
740 DOS_FULL_NAME full_name;
741 const char *unixfilename = filename;
742 const char *argv[256], **argptr;
745 /* Get Unix file name and iconic flag */
747 if ( lpStartupInfo->dwFlags & STARTF_USESHOWWINDOW )
748 if ( lpStartupInfo->wShowWindow == SW_SHOWMINIMIZED
749 || lpStartupInfo->wShowWindow == SW_SHOWMINNOACTIVE )
752 if ( strchr(filename, '/')
753 || strchr(filename, ':')
754 || strchr(filename, '\\') )
756 if ( DOSFS_GetFullName( filename, TRUE, &full_name ) )
757 unixfilename = full_name.long_name;
762 SetLastError( ERROR_FILE_NOT_FOUND );
766 /* Build argument list */
771 char *p = strdup(lpCmdLine);
772 *argptr++ = unixfilename;
773 if (iconic) *argptr++ = "-iconic";
776 while (*p && (*p == ' ' || *p == '\t')) *p++ = '\0';
779 while (*p && *p != ' ' && *p != '\t') p++;
785 if (iconic) *argptr++ = "-iconic";
786 *argptr++ = lpCmdLine;
790 /* Fork and execute */
794 /* Note: don't use Wine routines here, as this process
795 has not been correctly initialized! */
797 execvp( argv[0], (char**)argv );
801 fprintf( stderr, "CreateProcess: can't exec 'wine %s'\n",
806 /* Fake success return value */
808 memset( lpProcessInfo, '\0', sizeof( *lpProcessInfo ) );
809 lpProcessInfo->hProcess = INVALID_HANDLE_VALUE;
810 lpProcessInfo->hThread = INVALID_HANDLE_VALUE;
812 SetLastError( ERROR_SUCCESS );
816 /***********************************************************************
817 * WinExec16 (KERNEL.166)
819 HINSTANCE16 WINAPI WinExec16( LPCSTR lpCmdLine, UINT16 nCmdShow )
823 SYSLEVEL_ReleaseWin16Lock();
824 hInst = WinExec( lpCmdLine, nCmdShow );
825 SYSLEVEL_RestoreWin16Lock();
830 /***********************************************************************
831 * WinExec (KERNEL32.566)
833 HINSTANCE WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
836 UINT16 paramCmdShow[2];
839 return 2; /* File not found */
841 /* Set up LOADPARAMS buffer for LoadModule */
843 memset( ¶ms, '\0', sizeof(params) );
844 params.lpCmdLine = (LPSTR)lpCmdLine;
845 params.lpCmdShow = paramCmdShow;
846 params.lpCmdShow[0] = 2;
847 params.lpCmdShow[1] = nCmdShow;
849 /* Now load the executable file */
851 return LoadModule( NULL, ¶ms );
854 /**********************************************************************
855 * LoadModule (KERNEL32.499)
857 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
859 LOADPARAMS *params = (LOADPARAMS *)paramBlock;
860 PROCESS_INFORMATION info;
861 STARTUPINFOA startup;
866 memset( &startup, '\0', sizeof(startup) );
867 startup.cb = sizeof(startup);
868 startup.dwFlags = STARTF_USESHOWWINDOW;
869 startup.wShowWindow = params->lpCmdShow? params->lpCmdShow[1] : 0;
871 if ( !CreateProcessA( name, params->lpCmdLine,
872 NULL, NULL, FALSE, 0, params->lpEnvAddress,
873 NULL, &startup, &info ) )
875 hInstance = GetLastError();
876 if ( hInstance < 32 ) return hInstance;
878 FIXME_(module)("Strange error set by CreateProcess: %d\n", hInstance );
882 /* Get 16-bit hInstance/hTask from process */
883 pdb = PROCESS_IdToPDB( info.dwProcessId );
884 tdb = pdb? (TDB *)GlobalLock16( pdb->task ) : NULL;
885 hInstance = tdb && tdb->hInstance? tdb->hInstance : pdb? pdb->task : 0;
886 /* If there is no hInstance (32-bit process) return a dummy value
888 * FIXME: should do this in all cases and fix Win16 callers */
889 if (!hInstance) hInstance = 33;
891 /* Close off the handles */
892 CloseHandle( info.hThread );
893 CloseHandle( info.hProcess );
898 /*************************************************************************
901 * Get next blank delimited token from input string. If quoted then
902 * process till matching quote and then till blank.
904 * Returns number of characters in token (not including \0). On
905 * end of string (EOS), returns a 0.
907 * from (IO) address of start of input string to scan, updated to
908 * next non-processed character.
909 * to (IO) address of start of output string (previous token \0
910 * char), updated to end of new output string (the \0
913 static int get_makename_token(LPCSTR *from, LPSTR *to )
916 LPCSTR to_old = *to; /* only used for tracing */
918 while ( **from == ' ') {
919 /* Copy leading blanks (separators between previous */
920 /* token and this token). */
927 while ( (**from != 0) && (**from != ' ') && (**from != '"') ) {
928 **to = **from; (*from)++; (*to)++; len++;
930 if ( **from == '"' ) {
931 /* Handle quoted string. */
933 if ( !strchr(*from, '"') ) {
934 /* fail - no closing quote. Return entire string */
935 while ( **from != 0 ) {
936 **to = **from; (*from)++; (*to)++; len++;
940 while( **from != '"') {
950 /* either EOS or ' ' */
955 **to = 0; /* terminate output string */
957 TRACE_(module)("returning token len=%d, string=%s\n",
963 /*************************************************************************
964 * make_lpCommandLine_name
966 * Try longer and longer strings from "line" to find an existing
967 * file name. Each attempt is delimited by a blank outside of quotes.
968 * Also will attempt to append ".exe" if requested and not already
969 * present. Returns the address of the remaining portion of the
974 static BOOL make_lpCommandLine_name( LPCSTR line, LPSTR name, int namelen,
986 /* scan over initial blanks if any */
987 while ( *from == ' ') from++;
989 /* get a token and append to previous data the check for existance */
991 if ( !get_makename_token( &from, &to ) ) {
992 /* EOS has occured and not found - exit */
997 TRACE_(module)("checking if file exists '%s'\n", name);
998 retlen = SearchPathA( NULL, name, ".exe", sizeof(buffer), buffer, &lastpart);
999 if ( retlen && (retlen < sizeof(buffer)) ) break;
1002 /* if we have a non-null full path name in buffer then move to output */
1004 if ( strlen(buffer) <= namelen )
1005 strcpy( name, buffer );
1007 /* not enough space to return full path string */
1008 FIXME_(module)("internal string not long enough, need %d\n",
1012 /* all done, indicate end of module name and then trace and exit */
1013 if (after) *after = from;
1014 TRACE_(module)("%i, selected file name '%s'\n and cmdline as %s\n",
1015 found, name, debugstr_a(from));
1019 /*************************************************************************
1020 * make_lpApplicationName_name
1022 * Scan input string (the lpApplicationName) and remove any quotes
1023 * if they are balanced.
1027 static BOOL make_lpApplicationName_name( LPCSTR line, LPSTR name, int namelen)
1030 LPSTR to, to_end, to_old;
1031 DOS_FULL_NAME full_name;
1034 to_end = to + namelen - 1;
1037 while ( *line == ' ' ) line++; /* point to beginning of string */
1040 /* Copy all input till end, or quote */
1041 while((*from != 0) && (*from != '"') && (to < to_end))
1043 if (to >= to_end) { *to = 0; break; }
1047 /* Handle quoted string. If there is a closing quote, copy all */
1048 /* that is inside. */
1050 if (!strchr(from, '"'))
1052 /* fail - no closing quote */
1053 to = to_old; /* restore to previous attempt */
1054 *to = 0; /* end string */
1055 break; /* exit with previous attempt */
1057 while((*from != '"') && (to < to_end)) *to++ = *from++;
1058 if (to >= to_end) { *to = 0; break; }
1060 continue; /* past quoted string, so restart from top */
1063 *to = 0; /* terminate output string */
1064 to_old = to; /* save for possible use in unmatched quote case */
1066 /* loop around keeping the blank as part of file name */
1068 break; /* exit if out of input string */
1071 if (!DOSFS_GetFullName(name, TRUE, &full_name)) {
1072 TRACE_(module)("file not found '%s'\n", name );
1076 if (strlen(full_name.long_name) >= namelen ) {
1077 FIXME_(module)("name longer than buffer (len=%d), file=%s\n",
1078 namelen, full_name.long_name);
1081 strcpy(name, full_name.long_name);
1083 TRACE_(module)("selected as file name '%s'\n", name );
1087 /**********************************************************************
1088 * CreateProcessA (KERNEL32.171)
1090 BOOL WINAPI CreateProcessA( LPCSTR lpApplicationName, LPSTR lpCommandLine,
1091 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1092 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1093 BOOL bInheritHandles, DWORD dwCreationFlags,
1094 LPVOID lpEnvironment, LPCSTR lpCurrentDirectory,
1095 LPSTARTUPINFOA lpStartupInfo,
1096 LPPROCESS_INFORMATION lpProcessInfo )
1099 BOOL found_file = FALSE;
1104 LPCSTR cmdline = NULL;
1106 /* Get name and command line */
1108 if (!lpApplicationName && !lpCommandLine)
1110 SetLastError( ERROR_FILE_NOT_FOUND );
1114 /* Warn if unsupported features are used */
1116 if (dwCreationFlags & CREATE_SUSPENDED)
1117 FIXME_(module)("(%s,...): CREATE_SUSPENDED ignored\n", name);
1118 if (dwCreationFlags & DETACHED_PROCESS)
1119 FIXME_(module)("(%s,...): DETACHED_PROCESS ignored\n", name);
1120 if (dwCreationFlags & CREATE_NEW_CONSOLE)
1121 FIXME_(module)("(%s,...): CREATE_NEW_CONSOLE ignored\n", name);
1122 if (dwCreationFlags & NORMAL_PRIORITY_CLASS)
1123 FIXME_(module)("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
1124 if (dwCreationFlags & IDLE_PRIORITY_CLASS)
1125 FIXME_(module)("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
1126 if (dwCreationFlags & HIGH_PRIORITY_CLASS)
1127 FIXME_(module)("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
1128 if (dwCreationFlags & REALTIME_PRIORITY_CLASS)
1129 FIXME_(module)("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
1130 if (dwCreationFlags & CREATE_NEW_PROCESS_GROUP)
1131 FIXME_(module)("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
1132 if (dwCreationFlags & CREATE_UNICODE_ENVIRONMENT)
1133 FIXME_(module)("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
1134 if (dwCreationFlags & CREATE_SEPARATE_WOW_VDM)
1135 FIXME_(module)("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
1136 if (dwCreationFlags & CREATE_SHARED_WOW_VDM)
1137 FIXME_(module)("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
1138 if (dwCreationFlags & CREATE_DEFAULT_ERROR_MODE)
1139 FIXME_(module)("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
1140 if (dwCreationFlags & CREATE_NO_WINDOW)
1141 FIXME_(module)("(%s,...): CREATE_NO_WINDOW ignored\n", name);
1142 if (dwCreationFlags & PROFILE_USER)
1143 FIXME_(module)("(%s,...): PROFILE_USER ignored\n", name);
1144 if (dwCreationFlags & PROFILE_KERNEL)
1145 FIXME_(module)("(%s,...): PROFILE_KERNEL ignored\n", name);
1146 if (dwCreationFlags & PROFILE_SERVER)
1147 FIXME_(module)("(%s,...): PROFILE_SERVER ignored\n", name);
1148 if (lpCurrentDirectory)
1149 FIXME_(module)("(%s,...): lpCurrentDirectory %s ignored\n",
1150 name, lpCurrentDirectory);
1151 if (lpStartupInfo->lpDesktop)
1152 FIXME_(module)("(%s,...): lpStartupInfo->lpDesktop %s ignored\n",
1153 name, lpStartupInfo->lpDesktop);
1154 if (lpStartupInfo->lpTitle)
1155 FIXME_(module)("(%s,...): lpStartupInfo->lpTitle %s ignored\n",
1156 name, lpStartupInfo->lpTitle);
1157 if (lpStartupInfo->dwFlags & STARTF_USECOUNTCHARS)
1158 FIXME_(module)("(%s,...): STARTF_USECOUNTCHARS (%ld,%ld) ignored\n",
1159 name, lpStartupInfo->dwXCountChars, lpStartupInfo->dwYCountChars);
1160 if (lpStartupInfo->dwFlags & STARTF_USEFILLATTRIBUTE)
1161 FIXME_(module)("(%s,...): STARTF_USEFILLATTRIBUTE %lx ignored\n",
1162 name, lpStartupInfo->dwFillAttribute);
1163 if (lpStartupInfo->dwFlags & STARTF_RUNFULLSCREEN)
1164 FIXME_(module)("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
1165 if (lpStartupInfo->dwFlags & STARTF_FORCEONFEEDBACK)
1166 FIXME_(module)("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
1167 if (lpStartupInfo->dwFlags & STARTF_FORCEOFFFEEDBACK)
1168 FIXME_(module)("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
1169 if (lpStartupInfo->dwFlags & STARTF_USEHOTKEY)
1170 FIXME_(module)("(%s,...): STARTF_USEHOTKEY ignored\n", name);
1172 /* Process the AppName or CmdLine to get module name and path */
1176 if (lpApplicationName) {
1177 found_file = make_lpApplicationName_name( lpApplicationName, name, sizeof(name) );
1178 cmdline = (lpCommandLine) ? lpCommandLine : lpApplicationName ;
1181 found_file = make_lpCommandLine_name( lpCommandLine, name, sizeof ( name ), &cmdline );
1183 if ( !found_file ) {
1184 /* make an early exit if file not found - save second pass */
1185 SetLastError( ERROR_FILE_NOT_FOUND );
1190 /* When in WineLib, always fork new Unix process */
1193 return MODULE_CreateUnixProcess( name, cmdline,
1194 lpStartupInfo, lpProcessInfo, TRUE );
1196 /* Check for special case: second instance of NE module */
1198 lstrcpynA( ofs.szPathName, name, sizeof( ofs.szPathName ) );
1199 retv = NE_CreateProcess( HFILE_ERROR, &ofs, cmdline, lpEnvironment,
1200 lpProcessAttributes, lpThreadAttributes,
1201 bInheritHandles, dwCreationFlags,
1202 lpStartupInfo, lpProcessInfo );
1204 /* Load file and create process */
1208 /* Open file and determine executable type */
1210 if ( (hFile = OpenFile( name, &ofs, OF_READ )) == HFILE_ERROR )
1212 SetLastError( ERROR_FILE_NOT_FOUND );
1216 if ( !MODULE_GetBinaryType( hFile, &ofs, &type ) )
1218 CloseHandle( hFile );
1220 /* FIXME: Try Unix executable only when appropriate! */
1221 if ( MODULE_CreateUnixProcess( name, cmdline,
1222 lpStartupInfo, lpProcessInfo, FALSE ) )
1225 SetLastError( ERROR_BAD_FORMAT );
1230 /* Create process */
1234 case SCS_32BIT_BINARY:
1235 retv = PE_CreateProcess( hFile, &ofs, cmdline, lpEnvironment,
1236 lpProcessAttributes, lpThreadAttributes,
1237 bInheritHandles, dwCreationFlags,
1238 lpStartupInfo, lpProcessInfo );
1241 case SCS_DOS_BINARY:
1242 retv = MZ_CreateProcess( hFile, &ofs, cmdline, lpEnvironment,
1243 lpProcessAttributes, lpThreadAttributes,
1244 bInheritHandles, dwCreationFlags,
1245 lpStartupInfo, lpProcessInfo );
1248 case SCS_WOW_BINARY:
1249 retv = NE_CreateProcess( hFile, &ofs, cmdline, lpEnvironment,
1250 lpProcessAttributes, lpThreadAttributes,
1251 bInheritHandles, dwCreationFlags,
1252 lpStartupInfo, lpProcessInfo );
1255 case SCS_PIF_BINARY:
1256 case SCS_POSIX_BINARY:
1257 case SCS_OS216_BINARY:
1258 FIXME_(module)("Unsupported executable type: %ld\n", type );
1262 SetLastError( ERROR_BAD_FORMAT );
1267 CloseHandle( hFile );
1272 /**********************************************************************
1273 * CreateProcessW (KERNEL32.172)
1275 * lpReserved is not converted
1277 BOOL WINAPI CreateProcessW( LPCWSTR lpApplicationName, LPWSTR lpCommandLine,
1278 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1279 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1280 BOOL bInheritHandles, DWORD dwCreationFlags,
1281 LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory,
1282 LPSTARTUPINFOW lpStartupInfo,
1283 LPPROCESS_INFORMATION lpProcessInfo )
1285 STARTUPINFOA StartupInfoA;
1287 LPSTR lpApplicationNameA = HEAP_strdupWtoA (GetProcessHeap(),0,lpApplicationName);
1288 LPSTR lpCommandLineA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCommandLine);
1289 LPSTR lpCurrentDirectoryA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCurrentDirectory);
1291 memcpy (&StartupInfoA, lpStartupInfo, sizeof(STARTUPINFOA));
1292 StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpDesktop);
1293 StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpTitle);
1295 TRACE_(win32)("(%s,%s,...)\n", debugstr_w(lpApplicationName), debugstr_w(lpCommandLine));
1297 if (lpStartupInfo->lpReserved)
1298 FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n", debugstr_w(lpStartupInfo->lpReserved));
1300 ret = CreateProcessA( lpApplicationNameA, lpCommandLineA,
1301 lpProcessAttributes, lpThreadAttributes,
1302 bInheritHandles, dwCreationFlags,
1303 lpEnvironment, lpCurrentDirectoryA,
1304 &StartupInfoA, lpProcessInfo );
1306 HeapFree( GetProcessHeap(), 0, lpCurrentDirectoryA );
1307 HeapFree( GetProcessHeap(), 0, lpCommandLineA );
1308 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1309 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1314 /***********************************************************************
1315 * GetModuleHandle (KERNEL32.237)
1317 HMODULE WINAPI GetModuleHandleA(LPCSTR module)
1321 if ( module == NULL )
1322 wm = PROCESS_Current()->exe_modref;
1324 wm = MODULE_FindModule( module );
1326 return wm? wm->module : 0;
1329 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
1332 LPSTR modulea = HEAP_strdupWtoA( GetProcessHeap(), 0, module );
1333 hModule = GetModuleHandleA( modulea );
1334 HeapFree( GetProcessHeap(), 0, modulea );
1339 /***********************************************************************
1340 * GetModuleFileName32A (KERNEL32.235)
1342 DWORD WINAPI GetModuleFileNameA(
1343 HMODULE hModule, /* [in] module handle (32bit) */
1344 LPSTR lpFileName, /* [out] filenamebuffer */
1345 DWORD size /* [in] size of filenamebuffer */
1347 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1349 if (!wm) /* can happen on start up or the like */
1352 if (PE_HEADER(wm->module)->OptionalHeader.MajorOperatingSystemVersion >= 4.0)
1353 lstrcpynA( lpFileName, wm->longname, size );
1355 lstrcpynA( lpFileName, wm->shortname, size );
1357 TRACE_(module)("%s\n", lpFileName );
1358 return strlen(lpFileName);
1362 /***********************************************************************
1363 * GetModuleFileName32W (KERNEL32.236)
1365 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName,
1368 LPSTR fnA = (char*)HeapAlloc( GetProcessHeap(), 0, size );
1369 DWORD res = GetModuleFileNameA( hModule, fnA, size );
1370 lstrcpynAtoW( lpFileName, fnA, size );
1371 HeapFree( GetProcessHeap(), 0, fnA );
1376 /***********************************************************************
1377 * LoadLibraryEx32W (KERNEL.513)
1379 HMODULE WINAPI LoadLibraryEx32W16( LPCSTR libname, HANDLE16 hf,
1384 SYSLEVEL_ReleaseWin16Lock();
1385 hModule = LoadLibraryExA( libname, hf, flags );
1386 SYSLEVEL_RestoreWin16Lock();
1391 /***********************************************************************
1392 * LoadLibrary32_16 (KERNEL.452)
1394 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
1396 return LoadLibraryEx32W16( libname, 0, 0 );
1399 /***********************************************************************
1400 * LoadLibraryExA (KERNEL32)
1402 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HFILE hfile, DWORD flags)
1408 SetLastError(ERROR_INVALID_PARAMETER);
1412 EnterCriticalSection(&PROCESS_Current()->crit_section);
1414 wm = MODULE_LoadLibraryExA( libname, hfile, flags );
1416 if(wm && !MODULE_DllProcessAttach(wm, NULL))
1418 WARN_(module)("Attach failed for module '%s', \n", libname);
1419 MODULE_FreeLibrary(wm);
1420 SetLastError(ERROR_DLL_INIT_FAILED);
1424 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1426 return wm ? wm->module : 0;
1429 /***********************************************************************
1430 * MODULE_LoadLibraryExA (internal)
1432 * Load a PE style module according to the load order.
1434 * The HFILE parameter is not used and marked reserved in the SDK. I can
1435 * only guess that it should force a file to be mapped, but I rather
1436 * ignore the parameter because it would be extremely difficult to
1437 * integrate this with different types of module represenations.
1440 WINE_MODREF *MODULE_LoadLibraryExA( LPCSTR libname, HFILE hfile, DWORD flags )
1445 module_loadorder_t *plo;
1447 EnterCriticalSection(&PROCESS_Current()->crit_section);
1449 /* Check for already loaded module */
1450 if((pwm = MODULE_FindModule(libname)))
1452 if(!(pwm->flags & WINE_MODREF_MARKER))
1454 TRACE_(module)("Already loaded module '%s' at 0x%08x, count=%d, \n", libname, pwm->module, pwm->refCount);
1455 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1459 plo = MODULE_GetLoadOrder(libname);
1461 for(i = 0; i < MODULE_LOADORDER_NTYPES; i++)
1463 switch(plo->loadorder[i])
1465 case MODULE_LOADORDER_DLL:
1466 TRACE_(module)("Trying native dll '%s'\n", libname);
1467 pwm = PE_LoadLibraryExA(libname, flags, &err);
1470 case MODULE_LOADORDER_ELFDLL:
1471 TRACE_(module)("Trying elfdll '%s'\n", libname);
1472 pwm = ELFDLL_LoadLibraryExA(libname, flags, &err);
1475 case MODULE_LOADORDER_SO:
1476 TRACE_(module)("Trying so-library '%s'\n", libname);
1477 pwm = ELF_LoadLibraryExA(libname, flags, &err);
1480 case MODULE_LOADORDER_BI:
1481 TRACE_(module)("Trying built-in '%s'\n", libname);
1482 pwm = BUILTIN32_LoadLibraryExA(libname, flags, &err);
1486 ERR_(module)("Got invalid loadorder type %d (%s index %d)\n", plo->loadorder[i], plo->modulename, i);
1489 case MODULE_LOADORDER_INVALID: /* We ignore this as it is an empty entry */
1496 /* Initialize DLL just loaded */
1497 TRACE_(module)("Loaded module '%s' at 0x%08x, \n", libname, pwm->module);
1499 /* Set the refCount here so that an attach failure will */
1500 /* decrement the dependencies through the MODULE_FreeLibrary call. */
1503 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1505 if (PROCESS_Current()->flags & PDB32_DEBUGGED)
1506 DEBUG_SendLoadDLLEvent( -1 /*FIXME*/, pwm->module, pwm->modname );
1511 if(err != ERROR_FILE_NOT_FOUND)
1515 ERR_(module)("Failed to load module '%s'; error=0x%08lx, \n", libname, err);
1517 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1521 /***********************************************************************
1522 * LoadLibraryA (KERNEL32)
1524 HMODULE WINAPI LoadLibraryA(LPCSTR libname) {
1525 return LoadLibraryExA(libname,0,0);
1528 /***********************************************************************
1529 * LoadLibraryW (KERNEL32)
1531 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
1533 return LoadLibraryExW(libnameW,0,0);
1536 /***********************************************************************
1537 * LoadLibraryExW (KERNEL32)
1539 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW,HFILE hfile,DWORD flags)
1541 LPSTR libnameA = HEAP_strdupWtoA( GetProcessHeap(), 0, libnameW );
1542 HMODULE ret = LoadLibraryExA( libnameA , hfile, flags );
1544 HeapFree( GetProcessHeap(), 0, libnameA );
1548 /***********************************************************************
1549 * MODULE_FlushModrefs
1551 * NOTE: Assumes that the process critical section is held!
1553 * Remove all unused modrefs and call the internal unloading routines
1554 * for the library type.
1556 static void MODULE_FlushModrefs(void)
1558 WINE_MODREF *wm, *next;
1560 for(wm = PROCESS_Current()->modref_list; wm; wm = next)
1567 /* Unlink this modref from the chain */
1569 wm->next->prev = wm->prev;
1571 wm->prev->next = wm->next;
1572 if(wm == PROCESS_Current()->modref_list)
1573 PROCESS_Current()->modref_list = wm->next;
1576 * The unloaders are also responsible for freeing the modref itself
1577 * because the loaders were responsible for allocating it.
1581 case MODULE32_PE: PE_UnloadLibrary(wm); break;
1582 case MODULE32_ELF: ELF_UnloadLibrary(wm); break;
1583 case MODULE32_ELFDLL: ELFDLL_UnloadLibrary(wm); break;
1584 case MODULE32_BI: BUILTIN32_UnloadLibrary(wm); break;
1587 ERR_(module)("Invalid or unhandled MODREF type %d encountered (wm=%p)\n", wm->type, wm);
1592 /***********************************************************************
1595 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
1600 EnterCriticalSection( &PROCESS_Current()->crit_section );
1601 PROCESS_Current()->free_lib_count++;
1603 wm = MODULE32_LookupHMODULE( hLibModule );
1604 if ( !wm || !hLibModule )
1605 SetLastError( ERROR_INVALID_HANDLE );
1607 retv = MODULE_FreeLibrary( wm );
1609 PROCESS_Current()->free_lib_count--;
1610 LeaveCriticalSection( &PROCESS_Current()->crit_section );
1615 /***********************************************************************
1616 * MODULE_DecRefCount
1618 * NOTE: Assumes that the process critical section is held!
1620 static void MODULE_DecRefCount( WINE_MODREF *wm )
1624 if ( wm->flags & WINE_MODREF_MARKER )
1627 if ( wm->refCount <= 0 )
1631 TRACE_(module)("(%s) refCount: %d\n", wm->modname, wm->refCount );
1633 if ( wm->refCount == 0 )
1635 wm->flags |= WINE_MODREF_MARKER;
1637 for ( i = 0; i < wm->nDeps; i++ )
1639 MODULE_DecRefCount( wm->deps[i] );
1641 wm->flags &= ~WINE_MODREF_MARKER;
1645 /***********************************************************************
1646 * MODULE_FreeLibrary
1648 * NOTE: Assumes that the process critical section is held!
1650 BOOL MODULE_FreeLibrary( WINE_MODREF *wm )
1652 TRACE_(module)("(%s) - START\n", wm->modname );
1654 /* Recursively decrement reference counts */
1655 MODULE_DecRefCount( wm );
1657 /* Call process detach notifications */
1658 if ( PROCESS_Current()->free_lib_count <= 1 )
1660 MODULE_DllProcessDetach( FALSE, NULL );
1661 if (PROCESS_Current()->flags & PDB32_DEBUGGED)
1662 DEBUG_SendUnloadDLLEvent( wm->module );
1665 MODULE_FlushModrefs();
1667 TRACE_(module)("(%s) - END\n", wm->modname );
1673 /***********************************************************************
1674 * FreeLibraryAndExitThread
1676 VOID WINAPI FreeLibraryAndExitThread(HINSTANCE hLibModule, DWORD dwExitCode)
1678 FreeLibrary(hLibModule);
1679 ExitThread(dwExitCode);
1682 /***********************************************************************
1683 * PrivateLoadLibrary (KERNEL32)
1685 * FIXME: rough guesswork, don't know what "Private" means
1687 HINSTANCE WINAPI PrivateLoadLibrary(LPCSTR libname)
1689 return (HINSTANCE)LoadLibrary16(libname);
1694 /***********************************************************************
1695 * PrivateFreeLibrary (KERNEL32)
1697 * FIXME: rough guesswork, don't know what "Private" means
1699 void WINAPI PrivateFreeLibrary(HINSTANCE handle)
1701 FreeLibrary16((HINSTANCE16)handle);
1705 /***********************************************************************
1706 * WIN32_GetProcAddress16 (KERNEL32.36)
1707 * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
1709 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
1715 WARN_(module)("hModule may not be 0!\n");
1716 return (FARPROC16)0;
1718 if (HIWORD(hModule))
1720 WARN_(module)("hModule is Win32 handle (%08x)\n", hModule );
1721 return (FARPROC16)0;
1723 hModule = GetExePtr( hModule );
1725 ordinal = NE_GetOrdinal( hModule, name );
1726 TRACE_(module)("%04x '%s'\n",
1729 ordinal = LOWORD(name);
1730 TRACE_(module)("%04x %04x\n",
1733 if (!ordinal) return (FARPROC16)0;
1734 ret = NE_GetEntryPoint( hModule, ordinal );
1735 TRACE_(module)("returning %08x\n",(UINT)ret);
1739 /***********************************************************************
1740 * GetProcAddress16 (KERNEL.50)
1742 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, SEGPTR name )
1747 if (!hModule) hModule = GetCurrentTask();
1748 hModule = GetExePtr( hModule );
1750 if (HIWORD(name) != 0)
1752 ordinal = NE_GetOrdinal( hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1753 TRACE_(module)("%04x '%s'\n",
1754 hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1758 ordinal = LOWORD(name);
1759 TRACE_(module)("%04x %04x\n",
1762 if (!ordinal) return (FARPROC16)0;
1764 ret = NE_GetEntryPoint( hModule, ordinal );
1766 TRACE_(module)("returning %08x\n", (UINT)ret );
1771 /***********************************************************************
1772 * GetProcAddress32 (KERNEL32.257)
1774 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1776 return MODULE_GetProcAddress( hModule, function, TRUE );
1779 /***********************************************************************
1780 * WIN16_GetProcAddress32 (KERNEL.453)
1782 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
1784 return MODULE_GetProcAddress( hModule, function, FALSE );
1787 /***********************************************************************
1788 * MODULE_GetProcAddress32 (internal)
1790 FARPROC MODULE_GetProcAddress(
1791 HMODULE hModule, /* [in] current module handle */
1792 LPCSTR function, /* [in] function to be looked up */
1795 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1798 if (HIWORD(function))
1799 TRACE_(win32)("(%08lx,%s)\n",(DWORD)hModule,function);
1801 TRACE_(win32)("(%08lx,%p)\n",(DWORD)hModule,function);
1803 SetLastError(ERROR_INVALID_HANDLE);
1809 retproc = PE_FindExportedFunction( wm, function, snoop );
1810 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1813 retproc = ELF_FindExportedFunction( wm, function);
1814 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1817 ERR_(module)("wine_modref type %d not handled.\n",wm->type);
1818 SetLastError(ERROR_INVALID_HANDLE);
1824 /***********************************************************************
1825 * RtlImageNtHeaders (NTDLL)
1827 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
1830 * return hModule+(((IMAGE_DOS_HEADER*)hModule)->e_lfanew);
1831 * but we could get HMODULE16 or the like (think builtin modules)
1834 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1835 if (!wm || (wm->type != MODULE32_PE)) return (PIMAGE_NT_HEADERS)0;
1836 return PE_HEADER(wm->module);
1840 /***************************************************************************
1841 * HasGPHandler (KERNEL.338)
1844 #include "pshpack1.h"
1845 typedef struct _GPHANDLERDEF
1852 #include "poppack.h"
1854 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1859 GPHANDLERDEF *gpHandler;
1861 if ( (hModule = FarGetOwner16( SELECTOROF(address) )) != 0
1862 && (gpOrdinal = NE_GetOrdinal( hModule, "__GP" )) != 0
1863 && (gpPtr = (SEGPTR)NE_GetEntryPointEx( hModule, gpOrdinal, FALSE )) != 0
1864 && !IsBadReadPtr16( gpPtr, sizeof(GPHANDLERDEF) )
1865 && (gpHandler = PTR_SEG_TO_LIN( gpPtr )) != NULL )
1867 while (gpHandler->selector)
1869 if ( SELECTOROF(address) == gpHandler->selector
1870 && OFFSETOF(address) >= gpHandler->rangeStart
1871 && OFFSETOF(address) < gpHandler->rangeEnd )
1872 return PTR_SEG_OFF_TO_SEGPTR( gpHandler->selector,
1873 gpHandler->handler );