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)
38 /*************************************************************************
40 * Walk MODREFs for input process ID
42 void MODULE_WalkModref( DWORD id )
45 WINE_MODREF *zwm, *prev = NULL;
46 PDB *pdb = PROCESS_IdToPDB( id );
49 MESSAGE("Invalid process id (pid)\n");
53 MESSAGE("Modref list for process pdb=%p\n", pdb);
54 MESSAGE("Modref next prev handle deps flags name\n");
55 for ( zwm = pdb->modref_list; zwm; zwm = zwm->next) {
56 MESSAGE("%p %p %p %04x %5d %04x %s\n", zwm, zwm->next, zwm->prev,
57 zwm->module, zwm->nDeps, zwm->flags, zwm->modname);
58 for ( i = 0; i < zwm->nDeps; i++ ) {
60 MESSAGE(" %d %p %s\n", i, zwm->deps[i], zwm->deps[i]->modname);
62 if (prev != zwm->prev)
63 MESSAGE(" --> modref corrupt, previous pointer wrong!!\n");
68 /*************************************************************************
69 * MODULE32_LookupHMODULE
70 * looks for the referenced HMODULE in the current process
72 WINE_MODREF *MODULE32_LookupHMODULE( HMODULE hmod )
77 return PROCESS_Current()->exe_modref;
80 ERR_(module)("tried to lookup 0x%04x in win32 module handler!\n",hmod);
83 for ( wm = PROCESS_Current()->modref_list; wm; wm=wm->next )
84 if (wm->module == hmod)
89 /*************************************************************************
92 static BOOL MODULE_InitDll( WINE_MODREF *wm, DWORD type, LPVOID lpReserved )
96 static LPCSTR typeName[] = { "PROCESS_DETACH", "PROCESS_ATTACH",
97 "THREAD_ATTACH", "THREAD_DETACH" };
101 /* Skip calls for modules loaded with special load flags */
103 if ( ( wm->flags & WINE_MODREF_DONT_RESOLVE_REFS )
104 || ( wm->flags & WINE_MODREF_LOAD_AS_DATAFILE ) )
108 TRACE_(module)("(%s,%s,%p) - CALL\n",
109 wm->modname, typeName[type], lpReserved );
111 /* Call the initialization routine */
115 retv = PE_InitDLL( wm, type, lpReserved );
119 /* no need to do that, dlopen() already does */
123 ERR_(module)("wine_modref type %d not handled.\n", wm->type );
128 TRACE_(module)("(%s,%s,%p) - RETURN %d\n",
129 wm->modname, typeName[type], lpReserved, retv );
134 /*************************************************************************
135 * MODULE_DllProcessAttach
137 * Send the process attach notification to all DLLs the given module
138 * depends on (recursively). This is somewhat complicated due to the fact that
140 * - we have to respect the module dependencies, i.e. modules implicitly
141 * referenced by another module have to be initialized before the module
142 * itself can be initialized
144 * - the initialization routine of a DLL can itself call LoadLibrary,
145 * thereby introducing a whole new set of dependencies (even involving
146 * the 'old' modules) at any time during the whole process
148 * (Note that this routine can be recursively entered not only directly
149 * from itself, but also via LoadLibrary from one of the called initialization
152 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
153 * the process *detach* notifications to be sent in the correct order.
154 * This must not only take into account module dependencies, but also
155 * 'hidden' dependencies created by modules calling LoadLibrary in their
156 * attach notification routine.
158 * The strategy is rather simple: we move a WINE_MODREF to the head of the
159 * list after the attach notification has returned. This implies that the
160 * detach notifications are called in the reverse of the sequence the attach
161 * notifications *returned*.
163 * NOTE: Assumes that the process critical section is held!
166 BOOL MODULE_DllProcessAttach( WINE_MODREF *wm, LPVOID lpReserved )
172 /* prevent infinite recursion in case of cyclical dependencies */
173 if ( ( wm->flags & WINE_MODREF_MARKER )
174 || ( wm->flags & WINE_MODREF_PROCESS_ATTACHED ) )
177 TRACE_(module)("(%s,%p) - START\n",
178 wm->modname, lpReserved );
180 /* Tag current MODREF to prevent recursive loop */
181 wm->flags |= WINE_MODREF_MARKER;
183 /* Recursively attach all DLLs this one depends on */
184 for ( i = 0; retv && i < wm->nDeps; i++ )
186 retv = MODULE_DllProcessAttach( wm->deps[i], lpReserved );
188 /* Call DLL entry point */
191 retv = MODULE_InitDll( wm, DLL_PROCESS_ATTACH, lpReserved );
193 wm->flags |= WINE_MODREF_PROCESS_ATTACHED;
196 /* Re-insert MODREF at head of list */
197 if ( retv && wm->prev )
199 wm->prev->next = wm->next;
200 if ( wm->next ) wm->next->prev = wm->prev;
203 wm->next = PROCESS_Current()->modref_list;
204 PROCESS_Current()->modref_list = wm->next->prev = wm;
207 /* Remove recursion flag */
208 wm->flags &= ~WINE_MODREF_MARKER;
210 TRACE_(module)("(%s,%p) - END\n",
211 wm->modname, lpReserved );
216 /*************************************************************************
217 * MODULE_DllProcessDetach
219 * Send DLL process detach notifications. See the comment about calling
220 * sequence at MODULE_DllProcessAttach. Unless the bForceDetach flag
221 * is set, only DLLs with zero refcount are notified.
223 * NOTE: Assumes that the process critical section is held!
226 void MODULE_DllProcessDetach( BOOL bForceDetach, LPVOID lpReserved )
232 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
234 /* Check whether to detach this DLL */
235 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
237 if ( wm->refCount > 0 && !bForceDetach )
240 /* Call detach notification */
241 wm->flags &= ~WINE_MODREF_PROCESS_ATTACHED;
242 MODULE_InitDll( wm, DLL_PROCESS_DETACH, lpReserved );
244 /* Restart at head of WINE_MODREF list, as entries might have
245 been added and/or removed while performing the call ... */
251 /*************************************************************************
252 * MODULE_DllThreadAttach
254 * Send DLL thread attach notifications. These are sent in the
255 * reverse sequence of process detach notification.
258 void MODULE_DllThreadAttach( LPVOID lpReserved )
262 EnterCriticalSection( &PROCESS_Current()->crit_section );
264 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
268 for ( ; wm; wm = wm->prev )
270 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
272 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
275 MODULE_InitDll( wm, DLL_THREAD_ATTACH, lpReserved );
278 LeaveCriticalSection( &PROCESS_Current()->crit_section );
281 /*************************************************************************
282 * MODULE_DllThreadDetach
284 * Send DLL thread detach notifications. These are sent in the
285 * same sequence as process detach notification.
288 void MODULE_DllThreadDetach( LPVOID lpReserved )
292 EnterCriticalSection( &PROCESS_Current()->crit_section );
294 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
296 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
298 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
301 MODULE_InitDll( wm, DLL_THREAD_DETACH, lpReserved );
304 LeaveCriticalSection( &PROCESS_Current()->crit_section );
307 /****************************************************************************
308 * DisableThreadLibraryCalls (KERNEL32.74)
310 * Don't call DllEntryPoint for DLL_THREAD_{ATTACH,DETACH} if set.
312 BOOL WINAPI DisableThreadLibraryCalls( HMODULE hModule )
317 EnterCriticalSection( &PROCESS_Current()->crit_section );
319 wm = MODULE32_LookupHMODULE( hModule );
323 wm->flags |= WINE_MODREF_NO_DLL_CALLS;
325 LeaveCriticalSection( &PROCESS_Current()->crit_section );
331 /***********************************************************************
332 * MODULE_CreateDummyModule
334 * Create a dummy NE module for Win32 or Winelib.
336 HMODULE MODULE_CreateDummyModule( const OFSTRUCT *ofs, LPCSTR modName )
340 SEGTABLEENTRY *pSegment;
343 const char* basename;
345 INT of_size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName)
346 + strlen(ofs->szPathName) + 1;
347 INT size = sizeof(NE_MODULE) +
348 /* loaded file info */
350 /* segment table: DS,CS */
351 2 * sizeof(SEGTABLEENTRY) +
354 /* several empty tables */
357 hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
358 if (!hModule) return (HMODULE)11; /* invalid exe */
360 FarSetOwner16( hModule, hModule );
361 pModule = (NE_MODULE *)GlobalLock16( hModule );
363 /* Set all used entries */
364 pModule->magic = IMAGE_OS2_SIGNATURE;
371 pModule->heap_size = 0;
372 pModule->stack_size = 0;
373 pModule->seg_count = 2;
374 pModule->modref_count = 0;
375 pModule->nrname_size = 0;
376 pModule->fileinfo = sizeof(NE_MODULE);
377 pModule->os_flags = NE_OSFLAGS_WINDOWS;
378 pModule->expected_version = 0x030a;
379 pModule->self = hModule;
381 /* Set loaded file information */
382 memcpy( pModule + 1, ofs, of_size );
383 ((OFSTRUCT *)(pModule+1))->cBytes = of_size - 1;
385 pSegment = (SEGTABLEENTRY*)((char*)(pModule + 1) + of_size);
386 pModule->seg_table = (int)pSegment - (int)pModule;
389 pSegment->flags = NE_SEGFLAGS_DATA;
390 pSegment->minsize = 0x1000;
397 pStr = (char *)pSegment;
398 pModule->name_table = (int)pStr - (int)pModule;
403 basename = strrchr(ofs->szPathName,'\\');
404 if (!basename) basename = ofs->szPathName;
407 len = strlen(basename);
408 if ((s = strchr(basename,'.'))) len = s - basename;
409 if (len > 8) len = 8;
411 strncpy( pStr+1, basename, len );
412 if (len < 8) pStr[len+1] = 0;
415 /* All tables zero terminated */
416 pModule->res_table = pModule->import_table = pModule->entry_table =
417 (int)pStr - (int)pModule;
419 NE_RegisterModule( pModule );
424 /**********************************************************************
425 * MODULE_FindModule32
427 * Find a (loaded) win32 module depending on path
428 * The handling of '.' is a bit weird, but we need it that way,
429 * for sometimes the programs use '<name>.exe' and '<name>.dll' and
430 * this is the only way to differentiate. (mainly hypertrm.exe)
433 * the module handle if found
436 WINE_MODREF *MODULE_FindModule(
437 LPCSTR path /* [in] pathname of module/library to be found */
443 if (!(filename = strrchr( path, '\\' )))
444 filename = HEAP_strdupA( GetProcessHeap(), 0, path );
446 filename = HEAP_strdupA( GetProcessHeap(), 0, filename+1 );
447 dotptr=strrchr(filename,'.');
449 for ( wm = PROCESS_Current()->modref_list; wm; wm=wm->next ) {
450 LPSTR xmodname,xdotptr;
452 assert (wm->modname);
453 xmodname = HEAP_strdupA( GetProcessHeap(), 0, wm->modname );
454 xdotptr=strrchr(xmodname,'.');
455 if ( (xdotptr && !dotptr) ||
458 if (dotptr) *dotptr = '\0';
459 if (xdotptr) *xdotptr = '\0';
461 if (!strcasecmp( filename, xmodname)) {
462 HeapFree( GetProcessHeap(), 0, filename );
463 HeapFree( GetProcessHeap(), 0, xmodname );
466 if (dotptr) *dotptr='.';
467 /* FIXME: add paths, shortname */
468 HeapFree( GetProcessHeap(), 0, xmodname );
470 /* if that fails, try looking for the filename... */
471 for ( wm = PROCESS_Current()->modref_list; wm; wm=wm->next ) {
472 LPSTR xlname,xdotptr;
474 assert (wm->longname);
475 xlname = strrchr(wm->longname,'\\');
477 xlname = wm->longname;
480 xlname = HEAP_strdupA( GetProcessHeap(), 0, xlname );
481 xdotptr=strrchr(xlname,'.');
482 if ( (xdotptr && !dotptr) ||
485 if (dotptr) *dotptr = '\0';
486 if (xdotptr) *xdotptr = '\0';
488 if (!strcasecmp( filename, xlname)) {
489 HeapFree( GetProcessHeap(), 0, filename );
490 HeapFree( GetProcessHeap(), 0, xlname );
493 if (dotptr) *dotptr='.';
494 /* FIXME: add paths, shortname */
495 HeapFree( GetProcessHeap(), 0, xlname );
497 HeapFree( GetProcessHeap(), 0, filename );
501 /***********************************************************************
502 * MODULE_GetBinaryType
504 * The GetBinaryType function determines whether a file is executable
505 * or not and if it is it returns what type of executable it is.
506 * The type of executable is a property that determines in which
507 * subsystem an executable file runs under.
509 * Binary types returned:
510 * SCS_32BIT_BINARY: A Win32 based application
511 * SCS_DOS_BINARY: An MS-Dos based application
512 * SCS_WOW_BINARY: A Win16 based application
513 * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
514 * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
515 * SCS_OS216_BINARY: A 16bit OS/2 based application
517 * Returns TRUE if the file is an executable in which case
518 * the value pointed by lpBinaryType is set.
519 * Returns FALSE if the file is not an executable or if the function fails.
521 * To do so it opens the file and reads in the header information
522 * if the extended header information is not presend it will
523 * assume that that the file is a DOS executable.
524 * If the extended header information is present it will
525 * determine if the file is an 16 or 32 bit Windows executable
526 * by check the flags in the header.
528 * Note that .COM and .PIF files are only recognized by their
529 * file name extension; but Windows does it the same way ...
531 static BOOL MODULE_GetBinaryType( HFILE hfile, OFSTRUCT *ofs,
532 LPDWORD lpBinaryType )
534 IMAGE_DOS_HEADER mz_header;
537 /* Seek to the start of the file and read the DOS header information.
539 if ( _llseek( hfile, 0, SEEK_SET ) >= 0 &&
540 _lread( hfile, &mz_header, sizeof(mz_header) ) == sizeof(mz_header) )
542 /* Now that we have the header check the e_magic field
543 * to see if this is a dos image.
545 if ( mz_header.e_magic == IMAGE_DOS_SIGNATURE )
547 BOOL lfanewValid = FALSE;
548 /* We do have a DOS image so we will now try to seek into
549 * the file by the amount indicated by the field
550 * "Offset to extended header" and read in the
551 * "magic" field information at that location.
552 * This will tell us if there is more header information
555 /* But before we do we will make sure that header
556 * structure encompasses the "Offset to extended header"
559 if ( (mz_header.e_cparhdr<<4) >= sizeof(IMAGE_DOS_HEADER) )
560 if ( ( mz_header.e_crlc == 0 && mz_header.e_lfarlc == 0 ) ||
561 ( mz_header.e_lfarlc >= sizeof(IMAGE_DOS_HEADER) ) )
562 if ( mz_header.e_lfanew >= sizeof(IMAGE_DOS_HEADER) &&
563 _llseek( hfile, mz_header.e_lfanew, SEEK_SET ) >= 0 &&
564 _lread( hfile, magic, sizeof(magic) ) == sizeof(magic) )
569 /* If we cannot read this "extended header" we will
570 * assume that we have a simple DOS executable.
572 *lpBinaryType = SCS_DOS_BINARY;
577 /* Reading the magic field succeeded so
578 * we will try to determine what type it is.
580 if ( *(DWORD*)magic == IMAGE_NT_SIGNATURE )
582 /* This is an NT signature.
584 *lpBinaryType = SCS_32BIT_BINARY;
587 else if ( *(WORD*)magic == IMAGE_OS2_SIGNATURE )
589 /* The IMAGE_OS2_SIGNATURE indicates that the
590 * "extended header is a Windows executable (NE)
591 * header." This can mean either a 16-bit OS/2
592 * or a 16-bit Windows or even a DOS program
593 * (running under a DOS extender). To decide
594 * which, we'll have to read the NE header.
598 if ( _llseek( hfile, mz_header.e_lfanew, SEEK_SET ) >= 0 &&
599 _lread( hfile, &ne, sizeof(ne) ) == sizeof(ne) )
601 switch ( ne.operating_system )
603 case 2: *lpBinaryType = SCS_WOW_BINARY; return TRUE;
604 case 5: *lpBinaryType = SCS_DOS_BINARY; return TRUE;
605 default: *lpBinaryType = SCS_OS216_BINARY; return TRUE;
608 /* Couldn't read header, so abort. */
613 /* Unknown extended header, so abort.
621 /* If we get here, we don't even have a correct MZ header.
622 * Try to check the file extension for known types ...
624 ptr = strrchr( ofs->szPathName, '.' );
625 if ( ptr && !strchr( ptr, '\\' ) && !strchr( ptr, '/' ) )
627 if ( !lstrcmpiA( ptr, ".COM" ) )
629 *lpBinaryType = SCS_DOS_BINARY;
633 if ( !lstrcmpiA( ptr, ".PIF" ) )
635 *lpBinaryType = SCS_PIF_BINARY;
643 /***********************************************************************
644 * GetBinaryTypeA [KERNEL32.280]
646 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
652 TRACE_(win32)("%s\n", lpApplicationName );
656 if ( lpApplicationName == NULL || lpBinaryType == NULL )
659 /* Open the file indicated by lpApplicationName for reading.
661 if ( (hfile = OpenFile( lpApplicationName, &ofs, OF_READ )) == HFILE_ERROR )
666 ret = MODULE_GetBinaryType( hfile, &ofs, lpBinaryType );
670 CloseHandle( hfile );
675 /***********************************************************************
676 * GetBinaryTypeW [KERNEL32.281]
678 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
683 TRACE_(win32)("%s\n", debugstr_w(lpApplicationName) );
687 if ( lpApplicationName == NULL || lpBinaryType == NULL )
690 /* Convert the wide string to a ascii string.
692 strNew = HEAP_strdupWtoA( GetProcessHeap(), 0, lpApplicationName );
694 if ( strNew != NULL )
696 ret = GetBinaryTypeA( strNew, lpBinaryType );
698 /* Free the allocated string.
700 HeapFree( GetProcessHeap(), 0, strNew );
706 /**********************************************************************
707 * MODULE_CreateUnixProcess
709 static BOOL MODULE_CreateUnixProcess( LPCSTR filename, LPCSTR lpCmdLine,
710 LPSTARTUPINFOA lpStartupInfo,
711 LPPROCESS_INFORMATION lpProcessInfo,
714 DOS_FULL_NAME full_name;
715 const char *unixfilename = filename;
716 const char *argv[256], **argptr;
719 /* Get Unix file name and iconic flag */
721 if ( lpStartupInfo->dwFlags & STARTF_USESHOWWINDOW )
722 if ( lpStartupInfo->wShowWindow == SW_SHOWMINIMIZED
723 || lpStartupInfo->wShowWindow == SW_SHOWMINNOACTIVE )
726 /* Build argument list */
731 char *p = strdup(lpCmdLine);
732 if ( strchr(filename, '/')
733 || strchr(filename, ':')
734 || strchr(filename, '\\') )
736 if ( DOSFS_GetFullName( filename, TRUE, &full_name ) )
737 unixfilename = full_name.long_name;
739 *argptr++ = unixfilename;
740 if (iconic) *argptr++ = "-iconic";
743 while (*p && (*p == ' ' || *p == '\t')) *p++ = '\0';
746 while (*p && *p != ' ' && *p != '\t') p++;
753 if (iconic) *argptr++ = "-iconic";
754 *argptr++ = lpCmdLine;
758 /* Fork and execute */
762 /* Note: don't use Wine routines here, as this process
763 has not been correctly initialized! */
765 execvp( argv[0], (char**)argv );
769 fprintf( stderr, "CreateProcess: can't exec 'wine %s'\n",
774 /* Fake success return value */
776 memset( lpProcessInfo, '\0', sizeof( *lpProcessInfo ) );
777 lpProcessInfo->hProcess = INVALID_HANDLE_VALUE;
778 lpProcessInfo->hThread = INVALID_HANDLE_VALUE;
780 SetLastError( ERROR_SUCCESS );
784 /***********************************************************************
785 * WinExec16 (KERNEL.166)
787 HINSTANCE16 WINAPI WinExec16( LPCSTR lpCmdLine, UINT16 nCmdShow )
791 SYSLEVEL_ReleaseWin16Lock();
792 hInst = WinExec( lpCmdLine, nCmdShow );
793 SYSLEVEL_RestoreWin16Lock();
798 /***********************************************************************
799 * WinExec (KERNEL32.566)
801 HINSTANCE WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
804 UINT16 paramCmdShow[2];
807 return 2; /* File not found */
809 /* Set up LOADPARAMS buffer for LoadModule */
811 memset( ¶ms, '\0', sizeof(params) );
812 params.lpCmdLine = (LPSTR)lpCmdLine;
813 params.lpCmdShow = paramCmdShow;
814 params.lpCmdShow[0] = 2;
815 params.lpCmdShow[1] = nCmdShow;
817 /* Now load the executable file */
819 return LoadModule( NULL, ¶ms );
822 /**********************************************************************
823 * LoadModule (KERNEL32.499)
825 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
827 LOADPARAMS *params = (LOADPARAMS *)paramBlock;
828 PROCESS_INFORMATION info;
829 STARTUPINFOA startup;
834 memset( &startup, '\0', sizeof(startup) );
835 startup.cb = sizeof(startup);
836 startup.dwFlags = STARTF_USESHOWWINDOW;
837 startup.wShowWindow = params->lpCmdShow? params->lpCmdShow[1] : 0;
839 if ( !CreateProcessA( name, params->lpCmdLine,
840 NULL, NULL, FALSE, 0, params->lpEnvAddress,
841 NULL, &startup, &info ) )
843 hInstance = GetLastError();
844 if ( hInstance < 32 ) return hInstance;
846 FIXME_(module)("Strange error set by CreateProcess: %d\n", hInstance );
850 /* Get 16-bit hInstance/hTask from process */
851 pdb = PROCESS_IdToPDB( info.dwProcessId );
852 tdb = pdb? (TDB *)GlobalLock16( pdb->task ) : NULL;
853 hInstance = tdb && tdb->hInstance? tdb->hInstance : pdb? pdb->task : 0;
854 /* If there is no hInstance (32-bit process) return a dummy value
856 * FIXME: should do this in all cases and fix Win16 callers */
857 if (!hInstance) hInstance = 33;
859 /* Close off the handles */
860 CloseHandle( info.hThread );
861 CloseHandle( info.hProcess );
866 /*************************************************************************
869 * Get next blank delimited token from input string. If quoted then
870 * process till matching quote and then till blank.
872 * Returns number of characters in token (not including \0). On
873 * end of string (EOS), returns a 0.
875 * from (IO) address of start of input string to scan, updated to
876 * next non-processed character.
877 * to (IO) address of start of output string (previous token \0
878 * char), updated to end of new output string (the \0
881 static int get_makename_token(LPCSTR *from, LPSTR *to )
884 LPCSTR to_old = *to; /* only used for tracing */
886 while ( **from == ' ') {
887 /* Copy leading blanks (separators between previous */
888 /* token and this token). */
895 while ( (**from != 0) && (**from != ' ') && (**from != '"') ) {
896 **to = **from; (*from)++; (*to)++; len++;
898 if ( **from == '"' ) {
899 /* Handle quoted string. */
901 if ( !strchr(*from, '"') ) {
902 /* fail - no closing quote. Return entire string */
903 while ( **from != 0 ) {
904 **to = **from; (*from)++; (*to)++; len++;
908 while( **from != '"') {
918 /* either EOS or ' ' */
923 **to = 0; /* terminate output string */
925 TRACE_(module)("returning token len=%d, string=%s\n",
931 /*************************************************************************
932 * make_lpCommandLine_name
934 * Try longer and longer strings from "line" to find an existing
935 * file name. Each attempt is delimited by a blank outside of quotes.
936 * Also will attempt to append ".exe" if requested and not already
937 * present. Returns the address of the remaining portion of the
942 static BOOL make_lpCommandLine_name( LPCSTR line, LPSTR name, int namelen,
954 /* scan over initial blanks if any */
955 while ( *from == ' ') from++;
957 /* get a token and append to previous data the check for existance */
959 if ( !get_makename_token( &from, &to ) ) {
960 /* EOS has occured and not found - exit */
965 TRACE_(module)("checking if file exists '%s'\n", name);
966 retlen = SearchPathA( NULL, name, ".exe", sizeof(buffer), buffer, &lastpart);
967 if ( retlen && (retlen < sizeof(buffer)) ) break;
970 /* if we have a non-null full path name in buffer then move to output */
972 if ( strlen(buffer) <= namelen ) {
973 strcpy( name, buffer );
975 /* not enough space to return full path string */
976 FIXME_(module)("internal string not long enough, need %d\n",
981 /* all done, indicate end of module name and then trace and exit */
982 if (after) *after = from;
983 TRACE_(module)("%i, selected file name '%s'\n and cmdline as %s\n",
984 found, name, debugstr_a(from));
988 /*************************************************************************
989 * make_lpApplicationName_name
991 * Scan input string (the lpApplicationName) and remove any quotes
992 * if they are balanced.
996 static BOOL make_lpApplicationName_name( LPCSTR line, LPSTR name, int namelen)
999 LPSTR to, to_end, to_old;
1000 DOS_FULL_NAME full_name;
1003 to_end = to + namelen - 1;
1006 while ( *line == ' ' ) line++; /* point to beginning of string */
1009 /* Copy all input till end, or quote */
1010 while((*from != 0) && (*from != '"') && (to < to_end))
1012 if (to >= to_end) { *to = 0; break; }
1016 /* Handle quoted string. If there is a closing quote, copy all */
1017 /* that is inside. */
1019 if (!strchr(from, '"'))
1021 /* fail - no closing quote */
1022 to = to_old; /* restore to previous attempt */
1023 *to = 0; /* end string */
1024 break; /* exit with previous attempt */
1026 while((*from != '"') && (to < to_end)) *to++ = *from++;
1027 if (to >= to_end) { *to = 0; break; }
1029 continue; /* past quoted string, so restart from top */
1032 *to = 0; /* terminate output string */
1033 to_old = to; /* save for possible use in unmatched quote case */
1035 /* loop around keeping the blank as part of file name */
1037 break; /* exit if out of input string */
1040 if (!DOSFS_GetFullName(name, TRUE, &full_name)) {
1041 TRACE_(module)("file not found '%s'\n", name );
1045 if (strlen(full_name.long_name) >= namelen ) {
1046 FIXME_(module)("name longer than buffer (len=%d), file=%s\n",
1047 namelen, full_name.long_name);
1050 strcpy(name, full_name.long_name);
1052 TRACE_(module)("selected as file name '%s'\n", name );
1056 /**********************************************************************
1057 * CreateProcessA (KERNEL32.171)
1059 BOOL WINAPI CreateProcessA( LPCSTR lpApplicationName, LPSTR lpCommandLine,
1060 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1061 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1062 BOOL bInheritHandles, DWORD dwCreationFlags,
1063 LPVOID lpEnvironment, LPCSTR lpCurrentDirectory,
1064 LPSTARTUPINFOA lpStartupInfo,
1065 LPPROCESS_INFORMATION lpProcessInfo )
1068 BOOL found_file = FALSE;
1072 char name[256], dummy[256];
1073 LPCSTR cmdline = NULL;
1077 /* Get name and command line */
1079 if (!lpApplicationName && !lpCommandLine)
1081 SetLastError( ERROR_FILE_NOT_FOUND );
1085 /* Process the AppName and/or CmdLine to get module name and path */
1089 if (lpApplicationName) {
1090 found_file = make_lpApplicationName_name( lpApplicationName, name, sizeof(name) );
1091 if (lpCommandLine) {
1092 make_lpCommandLine_name( lpCommandLine, dummy, sizeof ( dummy ), &cmdline );
1095 cmdline = lpApplicationName;
1097 len += strlen(lpApplicationName);
1100 found_file = make_lpCommandLine_name( lpCommandLine, name, sizeof ( name ), &cmdline );
1101 if (lpCommandLine) len = strlen(lpCommandLine);
1104 if ( !found_file ) {
1105 /* make an early exit if file not found - save second pass */
1106 SetLastError( ERROR_FILE_NOT_FOUND );
1110 len += strlen(name) + 2;
1111 tidy_cmdline = HeapAlloc( GetProcessHeap(), 0, len );
1112 sprintf( tidy_cmdline, "\"%s\"%s", name, cmdline);
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 /* When in WineLib, always fork new Unix process */
1175 retv = MODULE_CreateUnixProcess( name, tidy_cmdline,
1176 lpStartupInfo, lpProcessInfo, TRUE );
1177 HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1181 /* Check for special case: second instance of NE module */
1183 lstrcpynA( ofs.szPathName, name, sizeof( ofs.szPathName ) );
1184 retv = NE_CreateProcess( HFILE_ERROR, &ofs, tidy_cmdline, lpEnvironment,
1185 lpProcessAttributes, lpThreadAttributes,
1186 bInheritHandles, dwCreationFlags,
1187 lpStartupInfo, lpProcessInfo );
1189 /* Load file and create process */
1193 /* Open file and determine executable type */
1195 if ( (hFile = OpenFile( name, &ofs, OF_READ )) == HFILE_ERROR )
1197 SetLastError( ERROR_FILE_NOT_FOUND );
1198 HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1202 if ( !MODULE_GetBinaryType( hFile, &ofs, &type ) )
1204 CloseHandle( hFile );
1206 /* FIXME: Try Unix executable only when appropriate! */
1207 if ( MODULE_CreateUnixProcess( name, tidy_cmdline,
1208 lpStartupInfo, lpProcessInfo, FALSE ) )
1210 HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1213 HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1214 SetLastError( ERROR_BAD_FORMAT );
1219 /* Create process */
1223 case SCS_32BIT_BINARY:
1224 retv = PE_CreateProcess( hFile, &ofs, tidy_cmdline, lpEnvironment,
1225 lpProcessAttributes, lpThreadAttributes,
1226 bInheritHandles, dwCreationFlags,
1227 lpStartupInfo, lpProcessInfo );
1230 case SCS_DOS_BINARY:
1231 retv = MZ_CreateProcess( hFile, &ofs, tidy_cmdline, lpEnvironment,
1232 lpProcessAttributes, lpThreadAttributes,
1233 bInheritHandles, dwCreationFlags,
1234 lpStartupInfo, lpProcessInfo );
1237 case SCS_WOW_BINARY:
1238 retv = NE_CreateProcess( hFile, &ofs, tidy_cmdline, lpEnvironment,
1239 lpProcessAttributes, lpThreadAttributes,
1240 bInheritHandles, dwCreationFlags,
1241 lpStartupInfo, lpProcessInfo );
1244 case SCS_PIF_BINARY:
1245 case SCS_POSIX_BINARY:
1246 case SCS_OS216_BINARY:
1247 FIXME_(module)("Unsupported executable type: %ld\n", type );
1251 SetLastError( ERROR_BAD_FORMAT );
1256 CloseHandle( hFile );
1258 HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1262 /**********************************************************************
1263 * CreateProcessW (KERNEL32.172)
1265 * lpReserved is not converted
1267 BOOL WINAPI CreateProcessW( LPCWSTR lpApplicationName, LPWSTR lpCommandLine,
1268 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1269 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1270 BOOL bInheritHandles, DWORD dwCreationFlags,
1271 LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory,
1272 LPSTARTUPINFOW lpStartupInfo,
1273 LPPROCESS_INFORMATION lpProcessInfo )
1275 STARTUPINFOA StartupInfoA;
1277 LPSTR lpApplicationNameA = HEAP_strdupWtoA (GetProcessHeap(),0,lpApplicationName);
1278 LPSTR lpCommandLineA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCommandLine);
1279 LPSTR lpCurrentDirectoryA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCurrentDirectory);
1281 memcpy (&StartupInfoA, lpStartupInfo, sizeof(STARTUPINFOA));
1282 StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpDesktop);
1283 StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpTitle);
1285 TRACE_(win32)("(%s,%s,...)\n", debugstr_w(lpApplicationName), debugstr_w(lpCommandLine));
1287 if (lpStartupInfo->lpReserved)
1288 FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n", debugstr_w(lpStartupInfo->lpReserved));
1290 ret = CreateProcessA( lpApplicationNameA, lpCommandLineA,
1291 lpProcessAttributes, lpThreadAttributes,
1292 bInheritHandles, dwCreationFlags,
1293 lpEnvironment, lpCurrentDirectoryA,
1294 &StartupInfoA, lpProcessInfo );
1296 HeapFree( GetProcessHeap(), 0, lpCurrentDirectoryA );
1297 HeapFree( GetProcessHeap(), 0, lpCommandLineA );
1298 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1299 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1304 /***********************************************************************
1305 * GetModuleHandle (KERNEL32.237)
1307 HMODULE WINAPI GetModuleHandleA(LPCSTR module)
1311 if ( module == NULL )
1312 wm = PROCESS_Current()->exe_modref;
1314 wm = MODULE_FindModule( module );
1316 return wm? wm->module : 0;
1319 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
1322 LPSTR modulea = HEAP_strdupWtoA( GetProcessHeap(), 0, module );
1323 hModule = GetModuleHandleA( modulea );
1324 HeapFree( GetProcessHeap(), 0, modulea );
1329 /***********************************************************************
1330 * GetModuleFileName32A (KERNEL32.235)
1332 DWORD WINAPI GetModuleFileNameA(
1333 HMODULE hModule, /* [in] module handle (32bit) */
1334 LPSTR lpFileName, /* [out] filenamebuffer */
1335 DWORD size /* [in] size of filenamebuffer */
1337 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1339 if (!wm) /* can happen on start up or the like */
1342 if (PE_HEADER(wm->module)->OptionalHeader.MajorOperatingSystemVersion >= 4.0)
1343 lstrcpynA( lpFileName, wm->longname, size );
1345 lstrcpynA( lpFileName, wm->shortname, size );
1347 TRACE_(module)("%s\n", lpFileName );
1348 return strlen(lpFileName);
1352 /***********************************************************************
1353 * GetModuleFileName32W (KERNEL32.236)
1355 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName,
1358 LPSTR fnA = (char*)HeapAlloc( GetProcessHeap(), 0, size );
1359 DWORD res = GetModuleFileNameA( hModule, fnA, size );
1360 lstrcpynAtoW( lpFileName, fnA, size );
1361 HeapFree( GetProcessHeap(), 0, fnA );
1366 /***********************************************************************
1367 * LoadLibraryEx32W (KERNEL.513)
1369 HMODULE WINAPI LoadLibraryEx32W16( LPCSTR libname, HANDLE16 hf,
1374 SYSLEVEL_ReleaseWin16Lock();
1375 hModule = LoadLibraryExA( libname, hf, flags );
1376 SYSLEVEL_RestoreWin16Lock();
1381 /***********************************************************************
1382 * LoadLibrary32_16 (KERNEL.452)
1384 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
1386 return LoadLibraryEx32W16( libname, 0, 0 );
1389 /***********************************************************************
1390 * LoadLibraryExA (KERNEL32)
1392 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HFILE hfile, DWORD flags)
1398 SetLastError(ERROR_INVALID_PARAMETER);
1402 EnterCriticalSection(&PROCESS_Current()->crit_section);
1404 wm = MODULE_LoadLibraryExA( libname, hfile, flags );
1406 if(wm && !MODULE_DllProcessAttach(wm, NULL))
1408 WARN_(module)("Attach failed for module '%s', \n", libname);
1409 MODULE_FreeLibrary(wm);
1410 SetLastError(ERROR_DLL_INIT_FAILED);
1414 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1416 return wm ? wm->module : 0;
1419 /***********************************************************************
1420 * MODULE_LoadLibraryExA (internal)
1422 * Load a PE style module according to the load order.
1424 * The HFILE parameter is not used and marked reserved in the SDK. I can
1425 * only guess that it should force a file to be mapped, but I rather
1426 * ignore the parameter because it would be extremely difficult to
1427 * integrate this with different types of module represenations.
1430 WINE_MODREF *MODULE_LoadLibraryExA( LPCSTR libname, HFILE hfile, DWORD flags )
1435 module_loadorder_t *plo;
1437 EnterCriticalSection(&PROCESS_Current()->crit_section);
1439 /* Check for already loaded module */
1440 if((pwm = MODULE_FindModule(libname)))
1442 if(!(pwm->flags & WINE_MODREF_MARKER))
1444 TRACE_(module)("Already loaded module '%s' at 0x%08x, count=%d, \n", libname, pwm->module, pwm->refCount);
1445 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1449 plo = MODULE_GetLoadOrder(libname);
1451 for(i = 0; i < MODULE_LOADORDER_NTYPES; i++)
1453 switch(plo->loadorder[i])
1455 case MODULE_LOADORDER_DLL:
1456 TRACE_(module)("Trying native dll '%s'\n", libname);
1457 pwm = PE_LoadLibraryExA(libname, flags, &err);
1460 case MODULE_LOADORDER_ELFDLL:
1461 TRACE_(module)("Trying elfdll '%s'\n", libname);
1462 pwm = ELFDLL_LoadLibraryExA(libname, flags, &err);
1465 case MODULE_LOADORDER_SO:
1466 TRACE_(module)("Trying so-library '%s'\n", libname);
1467 pwm = ELF_LoadLibraryExA(libname, flags, &err);
1470 case MODULE_LOADORDER_BI:
1471 TRACE_(module)("Trying built-in '%s'\n", libname);
1472 pwm = BUILTIN32_LoadLibraryExA(libname, flags, &err);
1476 ERR_(module)("Got invalid loadorder type %d (%s index %d)\n", plo->loadorder[i], plo->modulename, i);
1479 case MODULE_LOADORDER_INVALID: /* We ignore this as it is an empty entry */
1486 /* Initialize DLL just loaded */
1487 TRACE_(module)("Loaded module '%s' at 0x%08x, \n", libname, pwm->module);
1489 /* Set the refCount here so that an attach failure will */
1490 /* decrement the dependencies through the MODULE_FreeLibrary call. */
1493 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1495 if (PROCESS_Current()->flags & PDB32_DEBUGGED)
1496 DEBUG_SendLoadDLLEvent( -1 /*FIXME*/, pwm->module, pwm->modname );
1501 if(err != ERROR_FILE_NOT_FOUND)
1505 ERR_(module)("Failed to load module '%s'; error=0x%08lx, \n", libname, err);
1507 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1511 /***********************************************************************
1512 * LoadLibraryA (KERNEL32)
1514 HMODULE WINAPI LoadLibraryA(LPCSTR libname) {
1515 return LoadLibraryExA(libname,0,0);
1518 /***********************************************************************
1519 * LoadLibraryW (KERNEL32)
1521 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
1523 return LoadLibraryExW(libnameW,0,0);
1526 /***********************************************************************
1527 * LoadLibraryExW (KERNEL32)
1529 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW,HFILE hfile,DWORD flags)
1531 LPSTR libnameA = HEAP_strdupWtoA( GetProcessHeap(), 0, libnameW );
1532 HMODULE ret = LoadLibraryExA( libnameA , hfile, flags );
1534 HeapFree( GetProcessHeap(), 0, libnameA );
1538 /***********************************************************************
1539 * MODULE_FlushModrefs
1541 * NOTE: Assumes that the process critical section is held!
1543 * Remove all unused modrefs and call the internal unloading routines
1544 * for the library type.
1546 static void MODULE_FlushModrefs(void)
1548 WINE_MODREF *wm, *next;
1550 for(wm = PROCESS_Current()->modref_list; wm; wm = next)
1557 /* Unlink this modref from the chain */
1559 wm->next->prev = wm->prev;
1561 wm->prev->next = wm->next;
1562 if(wm == PROCESS_Current()->modref_list)
1563 PROCESS_Current()->modref_list = wm->next;
1566 * The unloaders are also responsible for freeing the modref itself
1567 * because the loaders were responsible for allocating it.
1571 case MODULE32_PE: PE_UnloadLibrary(wm); break;
1572 case MODULE32_ELF: ELF_UnloadLibrary(wm); break;
1573 case MODULE32_ELFDLL: ELFDLL_UnloadLibrary(wm); break;
1574 case MODULE32_BI: BUILTIN32_UnloadLibrary(wm); break;
1577 ERR_(module)("Invalid or unhandled MODREF type %d encountered (wm=%p)\n", wm->type, wm);
1582 /***********************************************************************
1585 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
1590 EnterCriticalSection( &PROCESS_Current()->crit_section );
1591 PROCESS_Current()->free_lib_count++;
1593 wm = MODULE32_LookupHMODULE( hLibModule );
1594 if ( !wm || !hLibModule )
1595 SetLastError( ERROR_INVALID_HANDLE );
1597 retv = MODULE_FreeLibrary( wm );
1599 PROCESS_Current()->free_lib_count--;
1600 LeaveCriticalSection( &PROCESS_Current()->crit_section );
1605 /***********************************************************************
1606 * MODULE_DecRefCount
1608 * NOTE: Assumes that the process critical section is held!
1610 static void MODULE_DecRefCount( WINE_MODREF *wm )
1614 if ( wm->flags & WINE_MODREF_MARKER )
1617 if ( wm->refCount <= 0 )
1621 TRACE_(module)("(%s) refCount: %d\n", wm->modname, wm->refCount );
1623 if ( wm->refCount == 0 )
1625 wm->flags |= WINE_MODREF_MARKER;
1627 for ( i = 0; i < wm->nDeps; i++ )
1629 MODULE_DecRefCount( wm->deps[i] );
1631 wm->flags &= ~WINE_MODREF_MARKER;
1635 /***********************************************************************
1636 * MODULE_FreeLibrary
1638 * NOTE: Assumes that the process critical section is held!
1640 BOOL MODULE_FreeLibrary( WINE_MODREF *wm )
1642 TRACE_(module)("(%s) - START\n", wm->modname );
1644 /* Recursively decrement reference counts */
1645 MODULE_DecRefCount( wm );
1647 /* Call process detach notifications */
1648 if ( PROCESS_Current()->free_lib_count <= 1 )
1650 MODULE_DllProcessDetach( FALSE, NULL );
1651 if (PROCESS_Current()->flags & PDB32_DEBUGGED)
1652 DEBUG_SendUnloadDLLEvent( wm->module );
1655 MODULE_FlushModrefs();
1657 TRACE_(module)("(%s) - END\n", wm->modname );
1663 /***********************************************************************
1664 * FreeLibraryAndExitThread
1666 VOID WINAPI FreeLibraryAndExitThread(HINSTANCE hLibModule, DWORD dwExitCode)
1668 FreeLibrary(hLibModule);
1669 ExitThread(dwExitCode);
1672 /***********************************************************************
1673 * PrivateLoadLibrary (KERNEL32)
1675 * FIXME: rough guesswork, don't know what "Private" means
1677 HINSTANCE WINAPI PrivateLoadLibrary(LPCSTR libname)
1679 return (HINSTANCE)LoadLibrary16(libname);
1684 /***********************************************************************
1685 * PrivateFreeLibrary (KERNEL32)
1687 * FIXME: rough guesswork, don't know what "Private" means
1689 void WINAPI PrivateFreeLibrary(HINSTANCE handle)
1691 FreeLibrary16((HINSTANCE16)handle);
1695 /***********************************************************************
1696 * WIN32_GetProcAddress16 (KERNEL32.36)
1697 * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
1699 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
1705 WARN_(module)("hModule may not be 0!\n");
1706 return (FARPROC16)0;
1708 if (HIWORD(hModule))
1710 WARN_(module)("hModule is Win32 handle (%08x)\n", hModule );
1711 return (FARPROC16)0;
1713 hModule = GetExePtr( hModule );
1715 ordinal = NE_GetOrdinal( hModule, name );
1716 TRACE_(module)("%04x '%s'\n",
1719 ordinal = LOWORD(name);
1720 TRACE_(module)("%04x %04x\n",
1723 if (!ordinal) return (FARPROC16)0;
1724 ret = NE_GetEntryPoint( hModule, ordinal );
1725 TRACE_(module)("returning %08x\n",(UINT)ret);
1729 /***********************************************************************
1730 * GetProcAddress16 (KERNEL.50)
1732 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, SEGPTR name )
1737 if (!hModule) hModule = GetCurrentTask();
1738 hModule = GetExePtr( hModule );
1740 if (HIWORD(name) != 0)
1742 ordinal = NE_GetOrdinal( hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1743 TRACE_(module)("%04x '%s'\n",
1744 hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1748 ordinal = LOWORD(name);
1749 TRACE_(module)("%04x %04x\n",
1752 if (!ordinal) return (FARPROC16)0;
1754 ret = NE_GetEntryPoint( hModule, ordinal );
1756 TRACE_(module)("returning %08x\n", (UINT)ret );
1761 /***********************************************************************
1762 * GetProcAddress32 (KERNEL32.257)
1764 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1766 return MODULE_GetProcAddress( hModule, function, TRUE );
1769 /***********************************************************************
1770 * WIN16_GetProcAddress32 (KERNEL.453)
1772 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
1774 return MODULE_GetProcAddress( hModule, function, FALSE );
1777 /***********************************************************************
1778 * MODULE_GetProcAddress32 (internal)
1780 FARPROC MODULE_GetProcAddress(
1781 HMODULE hModule, /* [in] current module handle */
1782 LPCSTR function, /* [in] function to be looked up */
1785 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1788 if (HIWORD(function))
1789 TRACE_(win32)("(%08lx,%s)\n",(DWORD)hModule,function);
1791 TRACE_(win32)("(%08lx,%p)\n",(DWORD)hModule,function);
1793 SetLastError(ERROR_INVALID_HANDLE);
1799 retproc = PE_FindExportedFunction( wm, function, snoop );
1800 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1803 retproc = ELF_FindExportedFunction( wm, function);
1804 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1807 ERR_(module)("wine_modref type %d not handled.\n",wm->type);
1808 SetLastError(ERROR_INVALID_HANDLE);
1814 /***********************************************************************
1815 * RtlImageNtHeaders (NTDLL)
1817 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
1820 * return hModule+(((IMAGE_DOS_HEADER*)hModule)->e_lfanew);
1821 * but we could get HMODULE16 or the like (think builtin modules)
1824 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1825 if (!wm || (wm->type != MODULE32_PE)) return (PIMAGE_NT_HEADERS)0;
1826 return PE_HEADER(wm->module);
1830 /***************************************************************************
1831 * HasGPHandler (KERNEL.338)
1834 #include "pshpack1.h"
1835 typedef struct _GPHANDLERDEF
1842 #include "poppack.h"
1844 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1849 GPHANDLERDEF *gpHandler;
1851 if ( (hModule = FarGetOwner16( SELECTOROF(address) )) != 0
1852 && (gpOrdinal = NE_GetOrdinal( hModule, "__GP" )) != 0
1853 && (gpPtr = (SEGPTR)NE_GetEntryPointEx( hModule, gpOrdinal, FALSE )) != 0
1854 && !IsBadReadPtr16( gpPtr, sizeof(GPHANDLERDEF) )
1855 && (gpHandler = PTR_SEG_TO_LIN( gpPtr )) != NULL )
1857 while (gpHandler->selector)
1859 if ( SELECTOROF(address) == gpHandler->selector
1860 && OFFSETOF(address) >= gpHandler->rangeStart
1861 && OFFSETOF(address) < gpHandler->rangeEnd )
1862 return PTR_SEG_OFF_TO_SEGPTR( gpHandler->selector,
1863 gpHandler->handler );