Authors: Gavriel State <gavriels@corel.com>, Ulrich Czekalla <ulrichc@corel.com>
[wine/multimedia.git] / loader / module.c
blob79ff9bb79d4d4e976decb1b8f6df605bfbbe3480
1 /*
2 * Modules
4 * Copyright 1995 Alexandre Julliard
5 */
7 #include <assert.h>
8 #include <fcntl.h>
9 #include <stdlib.h>
10 #include <stdio.h>
11 #include <string.h>
12 #include <sys/types.h>
13 #include <unistd.h>
14 #include "windef.h"
15 #include "wingdi.h"
16 #include "wine/winbase16.h"
17 #include "wine/winuser16.h"
18 #include "winerror.h"
19 #include "file.h"
20 #include "global.h"
21 #include "heap.h"
22 #include "module.h"
23 #include "snoop.h"
24 #include "neexe.h"
25 #include "pe_image.h"
26 #include "dosexe.h"
27 #include "process.h"
28 #include "syslevel.h"
29 #include "thread.h"
30 #include "selectors.h"
31 #include "stackframe.h"
32 #include "task.h"
33 #include "debugtools.h"
34 #include "callback.h"
35 #include "loadorder.h"
36 #include "elfdll.h"
37 #include "server.h"
39 DEFAULT_DEBUG_CHANNEL(module);
40 DECLARE_DEBUG_CHANNEL(win32);
42 /*************************************************************************
43 * MODULE_WalkModref
44 * Walk MODREFs for input process ID
46 void MODULE_WalkModref( DWORD id )
48 int i;
49 WINE_MODREF *zwm, *prev = NULL;
50 PDB *pdb = PROCESS_IdToPDB( id );
52 if (!pdb) {
53 MESSAGE("Invalid process id (pid)\n");
54 return;
57 MESSAGE("Modref list for process pdb=%p\n", pdb);
58 MESSAGE("Modref next prev handle deps flags name\n");
59 for ( zwm = pdb->modref_list; zwm; zwm = zwm->next) {
60 MESSAGE("%p %p %p %04x %5d %04x %s\n", zwm, zwm->next, zwm->prev,
61 zwm->module, zwm->nDeps, zwm->flags, zwm->modname);
62 for ( i = 0; i < zwm->nDeps; i++ ) {
63 if ( zwm->deps[i] )
64 MESSAGE(" %d %p %s\n", i, zwm->deps[i], zwm->deps[i]->modname);
66 if (prev != zwm->prev)
67 MESSAGE(" --> modref corrupt, previous pointer wrong!!\n");
68 prev = zwm;
72 /*************************************************************************
73 * MODULE32_LookupHMODULE
74 * looks for the referenced HMODULE in the current process
76 WINE_MODREF *MODULE32_LookupHMODULE( HMODULE hmod )
78 WINE_MODREF *wm;
80 if (!hmod)
81 return PROCESS_Current()->exe_modref;
83 if (!HIWORD(hmod)) {
84 ERR("tried to lookup 0x%04x in win32 module handler!\n",hmod);
85 return NULL;
87 for ( wm = PROCESS_Current()->modref_list; wm; wm=wm->next )
88 if (wm->module == hmod)
89 return wm;
90 return NULL;
93 /*************************************************************************
94 * MODULE_InitDll
96 static BOOL MODULE_InitDll( WINE_MODREF *wm, DWORD type, LPVOID lpReserved )
98 BOOL retv = TRUE;
100 static LPCSTR typeName[] = { "PROCESS_DETACH", "PROCESS_ATTACH",
101 "THREAD_ATTACH", "THREAD_DETACH" };
102 assert( wm );
105 /* Skip calls for modules loaded with special load flags */
107 if ( ( wm->flags & WINE_MODREF_DONT_RESOLVE_REFS )
108 || ( wm->flags & WINE_MODREF_LOAD_AS_DATAFILE ) )
109 return TRUE;
112 TRACE("(%s,%s,%p) - CALL\n", wm->modname, typeName[type], lpReserved );
114 /* Call the initialization routine */
115 switch ( wm->type )
117 case MODULE32_PE:
118 retv = PE_InitDLL( wm, type, lpReserved );
119 break;
121 case MODULE32_ELF:
122 /* no need to do that, dlopen() already does */
123 break;
125 default:
126 ERR("wine_modref type %d not handled.\n", wm->type );
127 retv = FALSE;
128 break;
131 /* The state of the module list may have changed due to the call
132 to PE_InitDLL. We cannot assume that this module has not been
133 deleted. */
134 TRACE("(%p,%s,%p) - RETURN %d\n", wm, typeName[type], lpReserved, retv );
136 return retv;
139 /*************************************************************************
140 * MODULE_DllProcessAttach
142 * Send the process attach notification to all DLLs the given module
143 * depends on (recursively). This is somewhat complicated due to the fact that
145 * - we have to respect the module dependencies, i.e. modules implicitly
146 * referenced by another module have to be initialized before the module
147 * itself can be initialized
149 * - the initialization routine of a DLL can itself call LoadLibrary,
150 * thereby introducing a whole new set of dependencies (even involving
151 * the 'old' modules) at any time during the whole process
153 * (Note that this routine can be recursively entered not only directly
154 * from itself, but also via LoadLibrary from one of the called initialization
155 * routines.)
157 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
158 * the process *detach* notifications to be sent in the correct order.
159 * This must not only take into account module dependencies, but also
160 * 'hidden' dependencies created by modules calling LoadLibrary in their
161 * attach notification routine.
163 * The strategy is rather simple: we move a WINE_MODREF to the head of the
164 * list after the attach notification has returned. This implies that the
165 * detach notifications are called in the reverse of the sequence the attach
166 * notifications *returned*.
168 * NOTE: Assumes that the process critical section is held!
171 BOOL MODULE_DllProcessAttach( WINE_MODREF *wm, LPVOID lpReserved )
173 BOOL retv = TRUE;
174 int i;
175 assert( wm );
177 /* prevent infinite recursion in case of cyclical dependencies */
178 if ( ( wm->flags & WINE_MODREF_MARKER )
179 || ( wm->flags & WINE_MODREF_PROCESS_ATTACHED ) )
180 return retv;
182 TRACE("(%s,%p) - START\n", wm->modname, lpReserved );
184 /* Tag current MODREF to prevent recursive loop */
185 wm->flags |= WINE_MODREF_MARKER;
187 /* Recursively attach all DLLs this one depends on */
188 for ( i = 0; retv && i < wm->nDeps; i++ )
189 if ( wm->deps[i] )
190 retv = MODULE_DllProcessAttach( wm->deps[i], lpReserved );
192 /* Call DLL entry point */
193 if ( retv )
195 retv = MODULE_InitDll( wm, DLL_PROCESS_ATTACH, lpReserved );
196 if ( retv )
197 wm->flags |= WINE_MODREF_PROCESS_ATTACHED;
200 /* Re-insert MODREF at head of list */
201 if ( retv && wm->prev )
203 wm->prev->next = wm->next;
204 if ( wm->next ) wm->next->prev = wm->prev;
206 wm->prev = NULL;
207 wm->next = PROCESS_Current()->modref_list;
208 PROCESS_Current()->modref_list = wm->next->prev = wm;
211 /* Remove recursion flag */
212 wm->flags &= ~WINE_MODREF_MARKER;
214 TRACE("(%s,%p) - END\n", wm->modname, lpReserved );
216 return retv;
219 /*************************************************************************
220 * MODULE_DllProcessDetach
222 * Send DLL process detach notifications. See the comment about calling
223 * sequence at MODULE_DllProcessAttach. Unless the bForceDetach flag
224 * is set, only DLLs with zero refcount are notified.
226 void MODULE_DllProcessDetach( BOOL bForceDetach, LPVOID lpReserved )
228 WINE_MODREF *wm;
230 EnterCriticalSection( &PROCESS_Current()->crit_section );
234 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
236 /* Check whether to detach this DLL */
237 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
238 continue;
239 if ( wm->refCount > 0 && !bForceDetach )
240 continue;
242 /* Call detach notification */
243 wm->flags &= ~WINE_MODREF_PROCESS_ATTACHED;
244 MODULE_InitDll( wm, DLL_PROCESS_DETACH, lpReserved );
246 /* Restart at head of WINE_MODREF list, as entries might have
247 been added and/or removed while performing the call ... */
248 break;
250 } while ( wm );
252 LeaveCriticalSection( &PROCESS_Current()->crit_section );
255 /*************************************************************************
256 * MODULE_DllThreadAttach
258 * Send DLL thread attach notifications. These are sent in the
259 * reverse sequence of process detach notification.
262 void MODULE_DllThreadAttach( LPVOID lpReserved )
264 WINE_MODREF *wm;
266 EnterCriticalSection( &PROCESS_Current()->crit_section );
268 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
269 if ( !wm->next )
270 break;
272 for ( ; wm; wm = wm->prev )
274 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
275 continue;
276 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
277 continue;
279 MODULE_InitDll( wm, DLL_THREAD_ATTACH, lpReserved );
282 LeaveCriticalSection( &PROCESS_Current()->crit_section );
285 /*************************************************************************
286 * MODULE_DllThreadDetach
288 * Send DLL thread detach notifications. These are sent in the
289 * same sequence as process detach notification.
292 void MODULE_DllThreadDetach( LPVOID lpReserved )
294 WINE_MODREF *wm;
296 EnterCriticalSection( &PROCESS_Current()->crit_section );
298 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
300 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
301 continue;
302 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
303 continue;
305 MODULE_InitDll( wm, DLL_THREAD_DETACH, lpReserved );
308 LeaveCriticalSection( &PROCESS_Current()->crit_section );
311 /****************************************************************************
312 * DisableThreadLibraryCalls (KERNEL32.74)
314 * Don't call DllEntryPoint for DLL_THREAD_{ATTACH,DETACH} if set.
316 BOOL WINAPI DisableThreadLibraryCalls( HMODULE hModule )
318 WINE_MODREF *wm;
319 BOOL retval = TRUE;
321 EnterCriticalSection( &PROCESS_Current()->crit_section );
323 wm = MODULE32_LookupHMODULE( hModule );
324 if ( !wm )
325 retval = FALSE;
326 else
327 wm->flags |= WINE_MODREF_NO_DLL_CALLS;
329 LeaveCriticalSection( &PROCESS_Current()->crit_section );
331 return retval;
335 /***********************************************************************
336 * MODULE_CreateDummyModule
338 * Create a dummy NE module for Win32 or Winelib.
340 HMODULE MODULE_CreateDummyModule( LPCSTR filename, HMODULE module32 )
342 HMODULE hModule;
343 NE_MODULE *pModule;
344 SEGTABLEENTRY *pSegment;
345 char *pStr,*s;
346 unsigned int len;
347 const char* basename;
348 OFSTRUCT *ofs;
349 int of_size, size;
351 /* Extract base filename */
352 basename = strrchr(filename, '\\');
353 if (!basename) basename = filename;
354 else basename++;
355 len = strlen(basename);
356 if ((s = strchr(basename, '.'))) len = s - basename;
358 /* Allocate module */
359 of_size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName)
360 + strlen(filename) + 1;
361 size = sizeof(NE_MODULE) +
362 /* loaded file info */
363 of_size +
364 /* segment table: DS,CS */
365 2 * sizeof(SEGTABLEENTRY) +
366 /* name table */
367 len + 2 +
368 /* several empty tables */
371 hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
372 if (!hModule) return (HMODULE)11; /* invalid exe */
374 FarSetOwner16( hModule, hModule );
375 pModule = (NE_MODULE *)GlobalLock16( hModule );
377 /* Set all used entries */
378 pModule->magic = IMAGE_OS2_SIGNATURE;
379 pModule->count = 1;
380 pModule->next = 0;
381 pModule->flags = 0;
382 pModule->dgroup = 0;
383 pModule->ss = 1;
384 pModule->cs = 2;
385 pModule->heap_size = 0;
386 pModule->stack_size = 0;
387 pModule->seg_count = 2;
388 pModule->modref_count = 0;
389 pModule->nrname_size = 0;
390 pModule->fileinfo = sizeof(NE_MODULE);
391 pModule->os_flags = NE_OSFLAGS_WINDOWS;
392 pModule->self = hModule;
393 pModule->module32 = module32;
395 /* Set version and flags */
396 if (module32)
398 pModule->expected_version =
399 ((PE_HEADER(module32)->OptionalHeader.MajorSubsystemVersion & 0xff) << 8 ) |
400 (PE_HEADER(module32)->OptionalHeader.MinorSubsystemVersion & 0xff);
401 pModule->flags |= NE_FFLAGS_WIN32;
402 if (PE_HEADER(module32)->FileHeader.Characteristics & IMAGE_FILE_DLL)
403 pModule->flags |= NE_FFLAGS_LIBMODULE | NE_FFLAGS_SINGLEDATA;
406 /* Set loaded file information */
407 ofs = (OFSTRUCT *)(pModule + 1);
408 memset( ofs, 0, of_size );
409 ofs->cBytes = of_size < 256 ? of_size : 255; /* FIXME */
410 strcpy( ofs->szPathName, filename );
412 pSegment = (SEGTABLEENTRY*)((char*)(pModule + 1) + of_size);
413 pModule->seg_table = (int)pSegment - (int)pModule;
414 /* Data segment */
415 pSegment->size = 0;
416 pSegment->flags = NE_SEGFLAGS_DATA;
417 pSegment->minsize = 0x1000;
418 pSegment++;
419 /* Code segment */
420 pSegment->flags = 0;
421 pSegment++;
423 /* Module name */
424 pStr = (char *)pSegment;
425 pModule->name_table = (int)pStr - (int)pModule;
426 assert(len<256);
427 *pStr = len;
428 lstrcpynA( pStr+1, basename, len+1 );
429 pStr += len+2;
431 /* All tables zero terminated */
432 pModule->res_table = pModule->import_table = pModule->entry_table =
433 (int)pStr - (int)pModule;
435 NE_RegisterModule( pModule );
436 return hModule;
440 /**********************************************************************
441 * MODULE_FindModule32
443 * Find a (loaded) win32 module depending on path
445 * RETURNS
446 * the module handle if found
447 * 0 if not
449 WINE_MODREF *MODULE_FindModule(
450 LPCSTR path /* [in] pathname of module/library to be found */
452 WINE_MODREF *wm;
453 char dllname[260], *p;
455 /* Append .DLL to name if no extension present */
456 strcpy( dllname, path );
457 if (!(p = strrchr( dllname, '.')) || strchr( p, '/' ) || strchr( p, '\\'))
458 strcat( dllname, ".DLL" );
460 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
462 if ( !strcasecmp( dllname, wm->modname ) )
463 break;
464 if ( !strcasecmp( dllname, wm->filename ) )
465 break;
466 if ( !strcasecmp( dllname, wm->short_modname ) )
467 break;
468 if ( !strcasecmp( dllname, wm->short_filename ) )
469 break;
472 return wm;
475 /***********************************************************************
476 * MODULE_GetBinaryType
478 * The GetBinaryType function determines whether a file is executable
479 * or not and if it is it returns what type of executable it is.
480 * The type of executable is a property that determines in which
481 * subsystem an executable file runs under.
483 * Binary types returned:
484 * SCS_32BIT_BINARY: A Win32 based application
485 * SCS_DOS_BINARY: An MS-Dos based application
486 * SCS_WOW_BINARY: A Win16 based application
487 * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
488 * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
489 * SCS_OS216_BINARY: A 16bit OS/2 based application
491 * Returns TRUE if the file is an executable in which case
492 * the value pointed by lpBinaryType is set.
493 * Returns FALSE if the file is not an executable or if the function fails.
495 * To do so it opens the file and reads in the header information
496 * if the extended header information is not present it will
497 * assume that the file is a DOS executable.
498 * If the extended header information is present it will
499 * determine if the file is a 16 or 32 bit Windows executable
500 * by check the flags in the header.
502 * Note that .COM and .PIF files are only recognized by their
503 * file name extension; but Windows does it the same way ...
505 static BOOL MODULE_GetBinaryType( HANDLE hfile, LPCSTR filename,
506 LPDWORD lpBinaryType )
508 IMAGE_DOS_HEADER mz_header;
509 char magic[4], *ptr;
510 DWORD len;
512 /* Seek to the start of the file and read the DOS header information.
514 if ( SetFilePointer( hfile, 0, NULL, SEEK_SET ) != -1
515 && ReadFile( hfile, &mz_header, sizeof(mz_header), &len, NULL )
516 && len == sizeof(mz_header) )
518 /* Now that we have the header check the e_magic field
519 * to see if this is a dos image.
521 if ( mz_header.e_magic == IMAGE_DOS_SIGNATURE )
523 BOOL lfanewValid = FALSE;
524 /* We do have a DOS image so we will now try to seek into
525 * the file by the amount indicated by the field
526 * "Offset to extended header" and read in the
527 * "magic" field information at that location.
528 * This will tell us if there is more header information
529 * to read or not.
531 /* But before we do we will make sure that header
532 * structure encompasses the "Offset to extended header"
533 * field.
535 if ( (mz_header.e_cparhdr<<4) >= sizeof(IMAGE_DOS_HEADER) )
536 if ( ( mz_header.e_crlc == 0 ) ||
537 ( mz_header.e_lfarlc >= sizeof(IMAGE_DOS_HEADER) ) )
538 if ( mz_header.e_lfanew >= sizeof(IMAGE_DOS_HEADER)
539 && SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET ) != -1
540 && ReadFile( hfile, magic, sizeof(magic), &len, NULL )
541 && len == sizeof(magic) )
542 lfanewValid = TRUE;
544 if ( !lfanewValid )
546 /* If we cannot read this "extended header" we will
547 * assume that we have a simple DOS executable.
549 *lpBinaryType = SCS_DOS_BINARY;
550 return TRUE;
552 else
554 /* Reading the magic field succeeded so
555 * we will try to determine what type it is.
557 if ( *(DWORD*)magic == IMAGE_NT_SIGNATURE )
559 /* This is an NT signature.
561 *lpBinaryType = SCS_32BIT_BINARY;
562 return TRUE;
564 else if ( *(WORD*)magic == IMAGE_OS2_SIGNATURE )
566 /* The IMAGE_OS2_SIGNATURE indicates that the
567 * "extended header is a Windows executable (NE)
568 * header." This can mean either a 16-bit OS/2
569 * or a 16-bit Windows or even a DOS program
570 * (running under a DOS extender). To decide
571 * which, we'll have to read the NE header.
574 IMAGE_OS2_HEADER ne;
575 if ( SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET ) != -1
576 && ReadFile( hfile, &ne, sizeof(ne), &len, NULL )
577 && len == sizeof(ne) )
579 switch ( ne.ne_exetyp )
581 case 2: *lpBinaryType = SCS_WOW_BINARY; return TRUE;
582 case 5: *lpBinaryType = SCS_DOS_BINARY; return TRUE;
583 default: *lpBinaryType = SCS_OS216_BINARY; return TRUE;
586 /* Couldn't read header, so abort. */
587 return FALSE;
589 else
591 /* Unknown extended header, but this file is nonetheless
592 DOS-executable.
594 *lpBinaryType = SCS_DOS_BINARY;
595 return TRUE;
601 /* If we get here, we don't even have a correct MZ header.
602 * Try to check the file extension for known types ...
604 ptr = strrchr( filename, '.' );
605 if ( ptr && !strchr( ptr, '\\' ) && !strchr( ptr, '/' ) )
607 if ( !lstrcmpiA( ptr, ".COM" ) )
609 *lpBinaryType = SCS_DOS_BINARY;
610 return TRUE;
613 if ( !lstrcmpiA( ptr, ".PIF" ) )
615 *lpBinaryType = SCS_PIF_BINARY;
616 return TRUE;
620 return FALSE;
623 /***********************************************************************
624 * GetBinaryTypeA [KERNEL32.280]
626 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
628 BOOL ret = FALSE;
629 HANDLE hfile;
631 TRACE_(win32)("%s\n", lpApplicationName );
633 /* Sanity check.
635 if ( lpApplicationName == NULL || lpBinaryType == NULL )
636 return FALSE;
638 /* Open the file indicated by lpApplicationName for reading.
640 hfile = CreateFileA( lpApplicationName, GENERIC_READ, 0,
641 NULL, OPEN_EXISTING, 0, -1 );
642 if ( hfile == INVALID_HANDLE_VALUE )
643 return FALSE;
645 /* Check binary type
647 ret = MODULE_GetBinaryType( hfile, lpApplicationName, lpBinaryType );
649 /* Close the file.
651 CloseHandle( hfile );
653 return ret;
656 /***********************************************************************
657 * GetBinaryTypeW [KERNEL32.281]
659 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
661 BOOL ret = FALSE;
662 LPSTR strNew = NULL;
664 TRACE_(win32)("%s\n", debugstr_w(lpApplicationName) );
666 /* Sanity check.
668 if ( lpApplicationName == NULL || lpBinaryType == NULL )
669 return FALSE;
671 /* Convert the wide string to a ascii string.
673 strNew = HEAP_strdupWtoA( GetProcessHeap(), 0, lpApplicationName );
675 if ( strNew != NULL )
677 ret = GetBinaryTypeA( strNew, lpBinaryType );
679 /* Free the allocated string.
681 HeapFree( GetProcessHeap(), 0, strNew );
684 return ret;
687 /**********************************************************************
688 * MODULE_CreateUnixProcess
690 static BOOL MODULE_CreateUnixProcess( LPCSTR filename, LPCSTR lpCmdLine,
691 LPSTARTUPINFOA lpStartupInfo,
692 LPPROCESS_INFORMATION lpProcessInfo )
694 const char *argv[256], **argptr;
695 char *cmdline = NULL;
696 char *p;
697 const char *unixfilename = filename;
698 DOS_FULL_NAME full_name;
700 /* Build argument list */
701 argptr = argv;
703 p = cmdline = strdup(lpCmdLine);
704 if (strchr(filename, '/') || strchr(filename, ':') || strchr(filename, '\\'))
706 if ( DOSFS_GetFullName( filename, TRUE, &full_name ) )
707 unixfilename = full_name.long_name;
709 while (1)
711 while (*p && (*p == ' ' || *p == '\t')) *p++ = '\0';
712 if (!*p) break;
713 *argptr++ = p;
714 while (*p && *p != ' ' && *p != '\t') p++;
716 *argptr++ = 0;
717 /* overwrite program name gotten from tidy_cmd */
718 argv[0] = unixfilename;
720 /* Fork and execute */
722 if ( !fork() )
724 /* Note: don't use Wine routines here, as this process
725 has not been correctly initialized! */
727 execvp( argv[0], (char**)argv );
728 exit( 1 );
731 /* Fake success return value */
733 memset( lpProcessInfo, '\0', sizeof( *lpProcessInfo ) );
734 lpProcessInfo->hProcess = INVALID_HANDLE_VALUE;
735 lpProcessInfo->hThread = INVALID_HANDLE_VALUE;
736 if (cmdline) free(cmdline);
738 SetLastError( ERROR_SUCCESS );
739 return TRUE;
742 /***********************************************************************
743 * WinExec16 (KERNEL.166)
745 HINSTANCE16 WINAPI WinExec16( LPCSTR lpCmdLine, UINT16 nCmdShow )
747 HINSTANCE16 hInst;
749 SYSLEVEL_ReleaseWin16Lock();
750 hInst = WinExec( lpCmdLine, nCmdShow );
751 SYSLEVEL_RestoreWin16Lock();
753 return hInst;
756 /***********************************************************************
757 * WinExec (KERNEL32.566)
759 HINSTANCE WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
761 PROCESS_INFORMATION info;
762 STARTUPINFOA startup;
763 HINSTANCE hInstance;
765 memset( &startup, 0, sizeof(startup) );
766 startup.cb = sizeof(startup);
767 startup.dwFlags = STARTF_USESHOWWINDOW;
768 startup.wShowWindow = nCmdShow;
770 if (CreateProcessA( NULL, (LPSTR)lpCmdLine, NULL, NULL, FALSE,
771 0, NULL, NULL, &startup, &info ))
773 /* Give 30 seconds to the app to come up */
774 if (Callout.WaitForInputIdle ( info.hProcess, 30000 ) == 0xFFFFFFFF)
775 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
777 /* Get 16-bit hInstance/hTask from process */
778 hInstance = GetProcessDword( info.dwProcessId, GPD_HINSTANCE16 );
779 /* If there is no hInstance (32-bit process) return a dummy value
780 * that must be > 31
781 * FIXME: should do this in all cases and fix Win16 callers */
782 if (!hInstance) hInstance = 33;
784 /* Close off the handles */
785 CloseHandle( info.hThread );
786 CloseHandle( info.hProcess );
788 else if ((hInstance = GetLastError()) >= 32)
790 FIXME("Strange error set by CreateProcess: %d\n", hInstance );
791 hInstance = 11;
794 return hInstance;
797 /**********************************************************************
798 * LoadModule (KERNEL32.499)
800 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
802 LOADPARAMS *params = (LOADPARAMS *)paramBlock;
803 PROCESS_INFORMATION info;
804 STARTUPINFOA startup;
805 HINSTANCE hInstance;
806 LPSTR cmdline, p;
807 char filename[MAX_PATH];
808 BYTE len;
810 if (!name) return ERROR_FILE_NOT_FOUND;
812 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
813 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
814 return GetLastError();
816 len = (BYTE)params->lpCmdLine[0];
817 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
818 return ERROR_NOT_ENOUGH_MEMORY;
820 strcpy( cmdline, filename );
821 p = cmdline + strlen(cmdline);
822 *p++ = ' ';
823 memcpy( p, params->lpCmdLine + 1, len );
824 p[len] = 0;
826 memset( &startup, 0, sizeof(startup) );
827 startup.cb = sizeof(startup);
828 if (params->lpCmdShow)
830 startup.dwFlags = STARTF_USESHOWWINDOW;
831 startup.wShowWindow = params->lpCmdShow[1];
834 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
835 params->lpEnvAddress, NULL, &startup, &info ))
837 /* Give 30 seconds to the app to come up */
838 if ( Callout.WaitForInputIdle ( info.hProcess, 30000 ) == 0xFFFFFFFF )
839 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
841 /* Get 16-bit hInstance/hTask from process */
842 hInstance = GetProcessDword( info.dwProcessId, GPD_HINSTANCE16 );
843 /* If there is no hInstance (32-bit process) return a dummy value
844 * that must be > 31
845 * FIXME: should do this in all cases and fix Win16 callers */
846 if (!hInstance) hInstance = 33;
847 /* Close off the handles */
848 CloseHandle( info.hThread );
849 CloseHandle( info.hProcess );
851 else if ((hInstance = GetLastError()) >= 32)
853 FIXME("Strange error set by CreateProcess: %d\n", hInstance );
854 hInstance = 11;
857 HeapFree( GetProcessHeap(), 0, cmdline );
858 return hInstance;
862 /*************************************************************************
863 * get_file_name
865 * Helper for CreateProcess: retrieve the file name to load from the
866 * app name and command line. Store the file name in buffer, and
867 * return a possibly modified command line.
869 static LPSTR get_file_name( LPCSTR appname, LPSTR cmdline, LPSTR buffer, int buflen )
871 char *name, *pos, *ret = NULL;
872 const char *p;
874 /* if we have an app name, everything is easy */
876 if (appname)
878 /* use the unmodified app name as file name */
879 lstrcpynA( buffer, appname, buflen );
880 if (!(ret = cmdline))
882 /* no command-line, create one */
883 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(appname) + 3 )))
884 sprintf( ret, "\"%s\"", appname );
886 return ret;
889 if (!cmdline)
891 SetLastError( ERROR_INVALID_PARAMETER );
892 return NULL;
895 /* first check for a quoted file name */
897 if ((cmdline[0] == '"') && ((p = strchr( cmdline + 1, '"' ))))
899 int len = p - cmdline - 1;
900 /* extract the quoted portion as file name */
901 if (!(name = HeapAlloc( GetProcessHeap(), 0, len + 1 ))) return NULL;
902 memcpy( name, cmdline + 1, len );
903 name[len] = 0;
905 if (SearchPathA( NULL, name, ".exe", buflen, buffer, NULL ) ||
906 SearchPathA( NULL, name, NULL, buflen, buffer, NULL ))
907 ret = cmdline; /* no change necessary */
908 goto done;
911 /* now try the command-line word by word */
913 if (!(name = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 1 ))) return NULL;
914 pos = name;
915 p = cmdline;
917 while (*p)
919 do *pos++ = *p++; while (*p && *p != ' ');
920 *pos = 0;
921 TRACE("trying '%s'\n", name );
922 if (SearchPathA( NULL, name, ".exe", buflen, buffer, NULL ) ||
923 SearchPathA( NULL, name, NULL, buflen, buffer, NULL ))
925 ret = cmdline;
926 break;
930 if (!ret || !strchr( name, ' ' )) goto done; /* no change necessary */
932 /* now build a new command-line with quotes */
934 if (!(ret = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 3 ))) goto done;
935 sprintf( ret, "\"%s\"%s", name, p );
937 done:
938 HeapFree( GetProcessHeap(), 0, name );
939 return ret;
943 /**********************************************************************
944 * CreateProcessA (KERNEL32.171)
946 BOOL WINAPI CreateProcessA( LPCSTR lpApplicationName, LPSTR lpCommandLine,
947 LPSECURITY_ATTRIBUTES lpProcessAttributes,
948 LPSECURITY_ATTRIBUTES lpThreadAttributes,
949 BOOL bInheritHandles, DWORD dwCreationFlags,
950 LPVOID lpEnvironment, LPCSTR lpCurrentDirectory,
951 LPSTARTUPINFOA lpStartupInfo,
952 LPPROCESS_INFORMATION lpProcessInfo )
954 BOOL retv = FALSE;
955 HANDLE hFile;
956 DWORD type;
957 char name[MAX_PATH];
958 LPSTR tidy_cmdline;
960 /* Process the AppName and/or CmdLine to get module name and path */
962 if (!(tidy_cmdline = get_file_name( lpApplicationName, lpCommandLine, name, sizeof(name) )))
963 return FALSE;
965 /* Warn if unsupported features are used */
967 if (dwCreationFlags & DETACHED_PROCESS)
968 FIXME("(%s,...): DETACHED_PROCESS ignored\n", name);
969 if (dwCreationFlags & CREATE_NEW_CONSOLE)
970 FIXME("(%s,...): CREATE_NEW_CONSOLE ignored\n", name);
971 if (dwCreationFlags & NORMAL_PRIORITY_CLASS)
972 FIXME("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
973 if (dwCreationFlags & IDLE_PRIORITY_CLASS)
974 FIXME("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
975 if (dwCreationFlags & HIGH_PRIORITY_CLASS)
976 FIXME("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
977 if (dwCreationFlags & REALTIME_PRIORITY_CLASS)
978 FIXME("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
979 if (dwCreationFlags & CREATE_NEW_PROCESS_GROUP)
980 FIXME("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
981 if (dwCreationFlags & CREATE_UNICODE_ENVIRONMENT)
982 FIXME("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
983 if (dwCreationFlags & CREATE_SEPARATE_WOW_VDM)
984 FIXME("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
985 if (dwCreationFlags & CREATE_SHARED_WOW_VDM)
986 FIXME("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
987 if (dwCreationFlags & CREATE_DEFAULT_ERROR_MODE)
988 FIXME("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
989 if (dwCreationFlags & CREATE_NO_WINDOW)
990 FIXME("(%s,...): CREATE_NO_WINDOW ignored\n", name);
991 if (dwCreationFlags & PROFILE_USER)
992 FIXME("(%s,...): PROFILE_USER ignored\n", name);
993 if (dwCreationFlags & PROFILE_KERNEL)
994 FIXME("(%s,...): PROFILE_KERNEL ignored\n", name);
995 if (dwCreationFlags & PROFILE_SERVER)
996 FIXME("(%s,...): PROFILE_SERVER ignored\n", name);
997 if (lpCurrentDirectory)
998 FIXME("(%s,...): lpCurrentDirectory %s ignored\n",
999 name, lpCurrentDirectory);
1000 if (lpStartupInfo->lpDesktop)
1001 FIXME("(%s,...): lpStartupInfo->lpDesktop %s ignored\n",
1002 name, lpStartupInfo->lpDesktop);
1003 if (lpStartupInfo->lpTitle)
1004 FIXME("(%s,...): lpStartupInfo->lpTitle %s ignored\n",
1005 name, lpStartupInfo->lpTitle);
1006 if (lpStartupInfo->dwFlags & STARTF_USECOUNTCHARS)
1007 FIXME("(%s,...): STARTF_USECOUNTCHARS (%ld,%ld) ignored\n",
1008 name, lpStartupInfo->dwXCountChars, lpStartupInfo->dwYCountChars);
1009 if (lpStartupInfo->dwFlags & STARTF_USEFILLATTRIBUTE)
1010 FIXME("(%s,...): STARTF_USEFILLATTRIBUTE %lx ignored\n",
1011 name, lpStartupInfo->dwFillAttribute);
1012 if (lpStartupInfo->dwFlags & STARTF_RUNFULLSCREEN)
1013 FIXME("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
1014 if (lpStartupInfo->dwFlags & STARTF_FORCEONFEEDBACK)
1015 FIXME("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
1016 if (lpStartupInfo->dwFlags & STARTF_FORCEOFFFEEDBACK)
1017 FIXME("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
1018 if (lpStartupInfo->dwFlags & STARTF_USEHOTKEY)
1019 FIXME("(%s,...): STARTF_USEHOTKEY ignored\n", name);
1021 /* Open file and determine executable type */
1023 hFile = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, -1 );
1024 if (hFile == INVALID_HANDLE_VALUE) goto done;
1026 if ( !MODULE_GetBinaryType( hFile, name, &type ) )
1028 CloseHandle( hFile );
1029 /* FIXME: Try Unix executable only when appropriate! */
1030 retv = MODULE_CreateUnixProcess( name, tidy_cmdline, lpStartupInfo, lpProcessInfo );
1031 goto done;
1034 /* Create process */
1036 switch ( type )
1038 case SCS_32BIT_BINARY:
1039 retv = PE_CreateProcess( hFile, name, tidy_cmdline, lpEnvironment,
1040 lpProcessAttributes, lpThreadAttributes,
1041 bInheritHandles, dwCreationFlags,
1042 lpStartupInfo, lpProcessInfo );
1043 break;
1045 case SCS_DOS_BINARY:
1046 retv = MZ_CreateProcess( hFile, name, tidy_cmdline, lpEnvironment,
1047 lpProcessAttributes, lpThreadAttributes,
1048 bInheritHandles, dwCreationFlags,
1049 lpStartupInfo, lpProcessInfo );
1050 break;
1052 case SCS_WOW_BINARY:
1053 retv = NE_CreateProcess( hFile, name, tidy_cmdline, lpEnvironment,
1054 lpProcessAttributes, lpThreadAttributes,
1055 bInheritHandles, dwCreationFlags,
1056 lpStartupInfo, lpProcessInfo );
1057 break;
1059 case SCS_PIF_BINARY:
1060 case SCS_POSIX_BINARY:
1061 case SCS_OS216_BINARY:
1062 FIXME("Unsupported executable type: %ld\n", type );
1063 /* fall through */
1065 default:
1066 SetLastError( ERROR_BAD_FORMAT );
1067 break;
1069 CloseHandle( hFile );
1071 done:
1072 if (tidy_cmdline != lpCommandLine) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1073 return retv;
1076 /**********************************************************************
1077 * CreateProcessW (KERNEL32.172)
1078 * NOTES
1079 * lpReserved is not converted
1081 BOOL WINAPI CreateProcessW( LPCWSTR lpApplicationName, LPWSTR lpCommandLine,
1082 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1083 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1084 BOOL bInheritHandles, DWORD dwCreationFlags,
1085 LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory,
1086 LPSTARTUPINFOW lpStartupInfo,
1087 LPPROCESS_INFORMATION lpProcessInfo )
1088 { BOOL ret;
1089 STARTUPINFOA StartupInfoA;
1091 LPSTR lpApplicationNameA = HEAP_strdupWtoA (GetProcessHeap(),0,lpApplicationName);
1092 LPSTR lpCommandLineA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCommandLine);
1093 LPSTR lpCurrentDirectoryA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCurrentDirectory);
1095 memcpy (&StartupInfoA, lpStartupInfo, sizeof(STARTUPINFOA));
1096 StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpDesktop);
1097 StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpTitle);
1099 TRACE_(win32)("(%s,%s,...)\n", debugstr_w(lpApplicationName), debugstr_w(lpCommandLine));
1101 if (lpStartupInfo->lpReserved)
1102 FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n", debugstr_w(lpStartupInfo->lpReserved));
1104 ret = CreateProcessA( lpApplicationNameA, lpCommandLineA,
1105 lpProcessAttributes, lpThreadAttributes,
1106 bInheritHandles, dwCreationFlags,
1107 lpEnvironment, lpCurrentDirectoryA,
1108 &StartupInfoA, lpProcessInfo );
1110 HeapFree( GetProcessHeap(), 0, lpCurrentDirectoryA );
1111 HeapFree( GetProcessHeap(), 0, lpCommandLineA );
1112 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1113 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1115 return ret;
1118 /***********************************************************************
1119 * GetModuleHandleA (KERNEL32.237)
1121 HMODULE WINAPI GetModuleHandleA(LPCSTR module)
1123 WINE_MODREF *wm;
1125 if ( module == NULL )
1126 wm = PROCESS_Current()->exe_modref;
1127 else
1128 wm = MODULE_FindModule( module );
1130 return wm? wm->module : 0;
1133 /***********************************************************************
1134 * GetModuleHandleW
1136 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
1138 HMODULE hModule;
1139 LPSTR modulea = HEAP_strdupWtoA( GetProcessHeap(), 0, module );
1140 hModule = GetModuleHandleA( modulea );
1141 HeapFree( GetProcessHeap(), 0, modulea );
1142 return hModule;
1146 /***********************************************************************
1147 * GetModuleFileNameA (KERNEL32.235)
1149 * GetModuleFileNameA seems to *always* return the long path;
1150 * it's only GetModuleFileName16 that decides between short/long path
1151 * by checking if exe version >= 4.0.
1152 * (SDK docu doesn't mention this)
1154 DWORD WINAPI GetModuleFileNameA(
1155 HMODULE hModule, /* [in] module handle (32bit) */
1156 LPSTR lpFileName, /* [out] filenamebuffer */
1157 DWORD size /* [in] size of filenamebuffer */
1158 ) {
1159 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1161 if (!wm) /* can happen on start up or the like */
1162 return 0;
1164 lstrcpynA( lpFileName, wm->filename, size );
1166 TRACE("%s\n", lpFileName );
1167 return strlen(lpFileName);
1171 /***********************************************************************
1172 * GetModuleFileNameW (KERNEL32.236)
1174 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName,
1175 DWORD size )
1177 LPSTR fnA = (char*)HeapAlloc( GetProcessHeap(), 0, size );
1178 DWORD res = GetModuleFileNameA( hModule, fnA, size );
1179 lstrcpynAtoW( lpFileName, fnA, size );
1180 HeapFree( GetProcessHeap(), 0, fnA );
1181 return res;
1185 /***********************************************************************
1186 * LoadLibraryExA (KERNEL32)
1188 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
1190 WINE_MODREF *wm;
1192 if(!libname)
1194 SetLastError(ERROR_INVALID_PARAMETER);
1195 return 0;
1198 EnterCriticalSection(&PROCESS_Current()->crit_section);
1200 wm = MODULE_LoadLibraryExA( libname, hfile, flags );
1201 if ( wm )
1203 if ( !MODULE_DllProcessAttach( wm, NULL ) )
1205 WARN_(module)("Attach failed for module '%s', \n", libname);
1206 MODULE_FreeLibrary(wm);
1207 SetLastError(ERROR_DLL_INIT_FAILED);
1208 wm = NULL;
1212 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1214 return wm ? wm->module : 0;
1217 /***********************************************************************
1218 * MODULE_LoadLibraryExA (internal)
1220 * Load a PE style module according to the load order.
1222 * The HFILE parameter is not used and marked reserved in the SDK. I can
1223 * only guess that it should force a file to be mapped, but I rather
1224 * ignore the parameter because it would be extremely difficult to
1225 * integrate this with different types of module represenations.
1228 WINE_MODREF *MODULE_LoadLibraryExA( LPCSTR libname, HFILE hfile, DWORD flags )
1230 DWORD err = GetLastError();
1231 WINE_MODREF *pwm;
1232 int i;
1233 module_loadorder_t *plo;
1235 EnterCriticalSection(&PROCESS_Current()->crit_section);
1237 /* Check for already loaded module */
1238 if((pwm = MODULE_FindModule(libname)))
1240 if(!(pwm->flags & WINE_MODREF_MARKER))
1241 pwm->refCount++;
1242 TRACE("Already loaded module '%s' at 0x%08x, count=%d, \n", libname, pwm->module, pwm->refCount);
1243 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1244 return pwm;
1247 plo = MODULE_GetLoadOrder(libname);
1249 for(i = 0; i < MODULE_LOADORDER_NTYPES; i++)
1251 SetLastError( ERROR_FILE_NOT_FOUND );
1252 switch(plo->loadorder[i])
1254 case MODULE_LOADORDER_DLL:
1255 TRACE("Trying native dll '%s'\n", libname);
1256 pwm = PE_LoadLibraryExA(libname, flags);
1257 break;
1259 case MODULE_LOADORDER_ELFDLL:
1260 TRACE("Trying elfdll '%s'\n", libname);
1261 if (!(pwm = BUILTIN32_LoadLibraryExA(libname, flags)))
1262 pwm = ELFDLL_LoadLibraryExA(libname, flags);
1263 break;
1265 case MODULE_LOADORDER_SO:
1266 TRACE("Trying so-library '%s'\n", libname);
1267 if (!(pwm = BUILTIN32_LoadLibraryExA(libname, flags)))
1268 pwm = ELF_LoadLibraryExA(libname, flags);
1269 break;
1271 case MODULE_LOADORDER_BI:
1272 TRACE("Trying built-in '%s'\n", libname);
1273 pwm = BUILTIN32_LoadLibraryExA(libname, flags);
1274 break;
1276 default:
1277 ERR("Got invalid loadorder type %d (%s index %d)\n", plo->loadorder[i], plo->modulename, i);
1278 /* Fall through */
1280 case MODULE_LOADORDER_INVALID: /* We ignore this as it is an empty entry */
1281 pwm = NULL;
1282 break;
1285 if(pwm)
1287 /* Initialize DLL just loaded */
1288 TRACE("Loaded module '%s' at 0x%08x, \n", libname, pwm->module);
1290 /* Set the refCount here so that an attach failure will */
1291 /* decrement the dependencies through the MODULE_FreeLibrary call. */
1292 pwm->refCount++;
1294 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1295 SetLastError( err ); /* restore last error */
1296 return pwm;
1299 if(GetLastError() != ERROR_FILE_NOT_FOUND)
1300 break;
1303 WARN("Failed to load module '%s'; error=0x%08lx, \n", libname, GetLastError());
1304 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1305 return NULL;
1308 /***********************************************************************
1309 * LoadLibraryA (KERNEL32)
1311 HMODULE WINAPI LoadLibraryA(LPCSTR libname) {
1312 return LoadLibraryExA(libname,0,0);
1315 /***********************************************************************
1316 * LoadLibraryW (KERNEL32)
1318 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
1320 return LoadLibraryExW(libnameW,0,0);
1323 /***********************************************************************
1324 * LoadLibrary32_16 (KERNEL.452)
1326 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
1328 HMODULE hModule;
1330 SYSLEVEL_ReleaseWin16Lock();
1331 hModule = LoadLibraryA( libname );
1332 SYSLEVEL_RestoreWin16Lock();
1334 return hModule;
1337 /***********************************************************************
1338 * LoadLibraryExW (KERNEL32)
1340 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW,HANDLE hfile,DWORD flags)
1342 LPSTR libnameA = HEAP_strdupWtoA( GetProcessHeap(), 0, libnameW );
1343 HMODULE ret = LoadLibraryExA( libnameA , hfile, flags );
1345 HeapFree( GetProcessHeap(), 0, libnameA );
1346 return ret;
1349 /***********************************************************************
1350 * MODULE_FlushModrefs
1352 * NOTE: Assumes that the process critical section is held!
1354 * Remove all unused modrefs and call the internal unloading routines
1355 * for the library type.
1357 static void MODULE_FlushModrefs(void)
1359 WINE_MODREF *wm, *next;
1361 for(wm = PROCESS_Current()->modref_list; wm; wm = next)
1363 next = wm->next;
1365 if(wm->refCount)
1366 continue;
1368 /* Unlink this modref from the chain */
1369 if(wm->next)
1370 wm->next->prev = wm->prev;
1371 if(wm->prev)
1372 wm->prev->next = wm->next;
1373 if(wm == PROCESS_Current()->modref_list)
1374 PROCESS_Current()->modref_list = wm->next;
1377 * The unloaders are also responsible for freeing the modref itself
1378 * because the loaders were responsible for allocating it.
1380 switch(wm->type)
1382 case MODULE32_PE: if ( !(wm->flags & WINE_MODREF_INTERNAL) )
1383 PE_UnloadLibrary(wm);
1384 else
1385 BUILTIN32_UnloadLibrary(wm);
1386 break;
1387 case MODULE32_ELF: ELF_UnloadLibrary(wm); break;
1388 case MODULE32_ELFDLL: ELFDLL_UnloadLibrary(wm); break;
1390 default:
1391 ERR("Invalid or unhandled MODREF type %d encountered (wm=%p)\n", wm->type, wm);
1396 /***********************************************************************
1397 * FreeLibrary
1399 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
1401 BOOL retv = FALSE;
1402 WINE_MODREF *wm;
1404 EnterCriticalSection( &PROCESS_Current()->crit_section );
1405 PROCESS_Current()->free_lib_count++;
1407 wm = MODULE32_LookupHMODULE( hLibModule );
1408 if ( !wm || !hLibModule )
1409 SetLastError( ERROR_INVALID_HANDLE );
1410 else
1411 retv = MODULE_FreeLibrary( wm );
1413 PROCESS_Current()->free_lib_count--;
1414 LeaveCriticalSection( &PROCESS_Current()->crit_section );
1416 return retv;
1419 /***********************************************************************
1420 * MODULE_DecRefCount
1422 * NOTE: Assumes that the process critical section is held!
1424 static void MODULE_DecRefCount( WINE_MODREF *wm )
1426 int i;
1428 if ( wm->flags & WINE_MODREF_MARKER )
1429 return;
1431 if ( wm->refCount <= 0 )
1432 return;
1434 --wm->refCount;
1435 TRACE("(%s) refCount: %d\n", wm->modname, wm->refCount );
1437 if ( wm->refCount == 0 )
1439 wm->flags |= WINE_MODREF_MARKER;
1441 for ( i = 0; i < wm->nDeps; i++ )
1442 if ( wm->deps[i] )
1443 MODULE_DecRefCount( wm->deps[i] );
1445 wm->flags &= ~WINE_MODREF_MARKER;
1449 /***********************************************************************
1450 * MODULE_FreeLibrary
1452 * NOTE: Assumes that the process critical section is held!
1454 BOOL MODULE_FreeLibrary( WINE_MODREF *wm )
1456 TRACE("(%s) - START\n", wm->modname );
1458 /* Recursively decrement reference counts */
1459 MODULE_DecRefCount( wm );
1461 /* Call process detach notifications */
1462 if ( PROCESS_Current()->free_lib_count <= 1 )
1464 struct unload_dll_request *req = get_req_buffer();
1466 MODULE_DllProcessDetach( FALSE, NULL );
1467 req->base = (void *)wm->module;
1468 server_call_noerr( REQ_UNLOAD_DLL );
1470 MODULE_FlushModrefs();
1473 TRACE("END\n");
1475 return TRUE;
1479 /***********************************************************************
1480 * FreeLibraryAndExitThread
1482 VOID WINAPI FreeLibraryAndExitThread(HINSTANCE hLibModule, DWORD dwExitCode)
1484 FreeLibrary(hLibModule);
1485 ExitThread(dwExitCode);
1488 /***********************************************************************
1489 * PrivateLoadLibrary (KERNEL32)
1491 * FIXME: rough guesswork, don't know what "Private" means
1493 HINSTANCE WINAPI PrivateLoadLibrary(LPCSTR libname)
1495 return (HINSTANCE)LoadLibrary16(libname);
1500 /***********************************************************************
1501 * PrivateFreeLibrary (KERNEL32)
1503 * FIXME: rough guesswork, don't know what "Private" means
1505 void WINAPI PrivateFreeLibrary(HINSTANCE handle)
1507 FreeLibrary16((HINSTANCE16)handle);
1511 /***********************************************************************
1512 * WIN32_GetProcAddress16 (KERNEL32.36)
1513 * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
1515 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
1517 WORD ordinal;
1518 FARPROC16 ret;
1520 if (!hModule) {
1521 WARN("hModule may not be 0!\n");
1522 return (FARPROC16)0;
1524 if (HIWORD(hModule))
1526 WARN("hModule is Win32 handle (%08x)\n", hModule );
1527 return (FARPROC16)0;
1529 hModule = GetExePtr( hModule );
1530 if (HIWORD(name)) {
1531 ordinal = NE_GetOrdinal( hModule, name );
1532 TRACE("%04x '%s'\n", hModule, name );
1533 } else {
1534 ordinal = LOWORD(name);
1535 TRACE("%04x %04x\n", hModule, ordinal );
1537 if (!ordinal) return (FARPROC16)0;
1538 ret = NE_GetEntryPoint( hModule, ordinal );
1539 TRACE("returning %08x\n",(UINT)ret);
1540 return ret;
1543 /***********************************************************************
1544 * GetProcAddress16 (KERNEL.50)
1546 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, SEGPTR name )
1548 WORD ordinal;
1549 FARPROC16 ret;
1551 if (!hModule) hModule = GetCurrentTask();
1552 hModule = GetExePtr( hModule );
1554 if (HIWORD(name) != 0)
1556 ordinal = NE_GetOrdinal( hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1557 TRACE("%04x '%s'\n", hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1559 else
1561 ordinal = LOWORD(name);
1562 TRACE("%04x %04x\n", hModule, ordinal );
1564 if (!ordinal) return (FARPROC16)0;
1566 ret = NE_GetEntryPoint( hModule, ordinal );
1568 TRACE("returning %08x\n", (UINT)ret );
1569 return ret;
1573 /***********************************************************************
1574 * GetProcAddress (KERNEL32.257)
1576 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1578 return MODULE_GetProcAddress( hModule, function, TRUE );
1581 /***********************************************************************
1582 * GetProcAddress32 (KERNEL.453)
1584 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
1586 return MODULE_GetProcAddress( hModule, function, FALSE );
1589 /***********************************************************************
1590 * MODULE_GetProcAddress (internal)
1592 FARPROC MODULE_GetProcAddress(
1593 HMODULE hModule, /* [in] current module handle */
1594 LPCSTR function, /* [in] function to be looked up */
1595 BOOL snoop )
1597 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1598 FARPROC retproc;
1600 if (HIWORD(function))
1601 TRACE_(win32)("(%08lx,%s)\n",(DWORD)hModule,function);
1602 else
1603 TRACE_(win32)("(%08lx,%p)\n",(DWORD)hModule,function);
1604 if (!wm) {
1605 SetLastError(ERROR_INVALID_HANDLE);
1606 return (FARPROC)0;
1608 switch (wm->type)
1610 case MODULE32_PE:
1611 retproc = PE_FindExportedFunction( wm, function, snoop );
1612 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1613 return retproc;
1614 case MODULE32_ELF:
1615 retproc = ELF_FindExportedFunction( wm, function);
1616 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1617 return retproc;
1618 default:
1619 ERR("wine_modref type %d not handled.\n",wm->type);
1620 SetLastError(ERROR_INVALID_HANDLE);
1621 return (FARPROC)0;
1626 /***********************************************************************
1627 * RtlImageNtHeader (NTDLL)
1629 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
1631 /* basically:
1632 * return hModule+(((IMAGE_DOS_HEADER*)hModule)->e_lfanew);
1633 * but we could get HMODULE16 or the like (think builtin modules)
1636 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1637 if (!wm || (wm->type != MODULE32_PE)) return (PIMAGE_NT_HEADERS)0;
1638 return PE_HEADER(wm->module);
1642 /***************************************************************************
1643 * HasGPHandler (KERNEL.338)
1646 #include "pshpack1.h"
1647 typedef struct _GPHANDLERDEF
1649 WORD selector;
1650 WORD rangeStart;
1651 WORD rangeEnd;
1652 WORD handler;
1653 } GPHANDLERDEF;
1654 #include "poppack.h"
1656 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1658 HMODULE16 hModule;
1659 int gpOrdinal;
1660 SEGPTR gpPtr;
1661 GPHANDLERDEF *gpHandler;
1663 if ( (hModule = FarGetOwner16( SELECTOROF(address) )) != 0
1664 && (gpOrdinal = NE_GetOrdinal( hModule, "__GP" )) != 0
1665 && (gpPtr = (SEGPTR)NE_GetEntryPointEx( hModule, gpOrdinal, FALSE )) != 0
1666 && !IsBadReadPtr16( gpPtr, sizeof(GPHANDLERDEF) )
1667 && (gpHandler = PTR_SEG_TO_LIN( gpPtr )) != NULL )
1669 while (gpHandler->selector)
1671 if ( SELECTOROF(address) == gpHandler->selector
1672 && OFFSETOF(address) >= gpHandler->rangeStart
1673 && OFFSETOF(address) < gpHandler->rangeEnd )
1674 return PTR_SEG_OFF_TO_SEGPTR( gpHandler->selector,
1675 gpHandler->handler );
1676 gpHandler++;
1680 return 0;