wm->modname might be invalid at the end of FreeLibrary.
[wine/gsoc_dplay.git] / loader / module.c
blobdd12615512ba9e124e716b2c0c459408a65d34cb
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"
38 DEFAULT_DEBUG_CHANNEL(module)
39 DECLARE_DEBUG_CHANNEL(win32)
41 /*************************************************************************
42 * MODULE_WalkModref
43 * Walk MODREFs for input process ID
45 void MODULE_WalkModref( DWORD id )
47 int i;
48 WINE_MODREF *zwm, *prev = NULL;
49 PDB *pdb = PROCESS_IdToPDB( id );
51 if (!pdb) {
52 MESSAGE("Invalid process id (pid)\n");
53 return;
56 MESSAGE("Modref list for process pdb=%p\n", pdb);
57 MESSAGE("Modref next prev handle deps flags name\n");
58 for ( zwm = pdb->modref_list; zwm; zwm = zwm->next) {
59 MESSAGE("%p %p %p %04x %5d %04x %s\n", zwm, zwm->next, zwm->prev,
60 zwm->module, zwm->nDeps, zwm->flags, zwm->modname);
61 for ( i = 0; i < zwm->nDeps; i++ ) {
62 if ( zwm->deps[i] )
63 MESSAGE(" %d %p %s\n", i, zwm->deps[i], zwm->deps[i]->modname);
65 if (prev != zwm->prev)
66 MESSAGE(" --> modref corrupt, previous pointer wrong!!\n");
67 prev = zwm;
71 /*************************************************************************
72 * MODULE32_LookupHMODULE
73 * looks for the referenced HMODULE in the current process
75 WINE_MODREF *MODULE32_LookupHMODULE( HMODULE hmod )
77 WINE_MODREF *wm;
79 if (!hmod)
80 return PROCESS_Current()->exe_modref;
82 if (!HIWORD(hmod)) {
83 ERR("tried to lookup 0x%04x in win32 module handler!\n",hmod);
84 return NULL;
86 for ( wm = PROCESS_Current()->modref_list; wm; wm=wm->next )
87 if (wm->module == hmod)
88 return wm;
89 return NULL;
92 /*************************************************************************
93 * MODULE_InitDll
95 static BOOL MODULE_InitDll( WINE_MODREF *wm, DWORD type, LPVOID lpReserved )
97 BOOL retv = TRUE;
99 static LPCSTR typeName[] = { "PROCESS_DETACH", "PROCESS_ATTACH",
100 "THREAD_ATTACH", "THREAD_DETACH" };
101 assert( wm );
104 /* Skip calls for modules loaded with special load flags */
106 if ( ( wm->flags & WINE_MODREF_DONT_RESOLVE_REFS )
107 || ( wm->flags & WINE_MODREF_LOAD_AS_DATAFILE ) )
108 return TRUE;
111 TRACE("(%s,%s,%p) - CALL\n",
112 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 TRACE("(%s,%s,%p) - RETURN %d\n",
132 wm->modname, typeName[type], lpReserved, retv );
134 return retv;
137 /*************************************************************************
138 * MODULE_DllProcessAttach
140 * Send the process attach notification to all DLLs the given module
141 * depends on (recursively). This is somewhat complicated due to the fact that
143 * - we have to respect the module dependencies, i.e. modules implicitly
144 * referenced by another module have to be initialized before the module
145 * itself can be initialized
147 * - the initialization routine of a DLL can itself call LoadLibrary,
148 * thereby introducing a whole new set of dependencies (even involving
149 * the 'old' modules) at any time during the whole process
151 * (Note that this routine can be recursively entered not only directly
152 * from itself, but also via LoadLibrary from one of the called initialization
153 * routines.)
155 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
156 * the process *detach* notifications to be sent in the correct order.
157 * This must not only take into account module dependencies, but also
158 * 'hidden' dependencies created by modules calling LoadLibrary in their
159 * attach notification routine.
161 * The strategy is rather simple: we move a WINE_MODREF to the head of the
162 * list after the attach notification has returned. This implies that the
163 * detach notifications are called in the reverse of the sequence the attach
164 * notifications *returned*.
166 * NOTE: Assumes that the process critical section is held!
169 BOOL MODULE_DllProcessAttach( WINE_MODREF *wm, LPVOID lpReserved )
171 BOOL retv = TRUE;
172 int i;
173 assert( wm );
175 /* prevent infinite recursion in case of cyclical dependencies */
176 if ( ( wm->flags & WINE_MODREF_MARKER )
177 || ( wm->flags & WINE_MODREF_PROCESS_ATTACHED ) )
178 return retv;
180 TRACE("(%s,%p) - START\n", wm->modname, lpReserved );
182 /* Tag current MODREF to prevent recursive loop */
183 wm->flags |= WINE_MODREF_MARKER;
185 /* Recursively attach all DLLs this one depends on */
186 for ( i = 0; retv && i < wm->nDeps; i++ )
187 if ( wm->deps[i] )
188 retv = MODULE_DllProcessAttach( wm->deps[i], lpReserved );
190 /* Call DLL entry point */
191 if ( retv )
193 retv = MODULE_InitDll( wm, DLL_PROCESS_ATTACH, lpReserved );
194 if ( retv )
195 wm->flags |= WINE_MODREF_PROCESS_ATTACHED;
198 /* Re-insert MODREF at head of list */
199 if ( retv && wm->prev )
201 wm->prev->next = wm->next;
202 if ( wm->next ) wm->next->prev = wm->prev;
204 wm->prev = NULL;
205 wm->next = PROCESS_Current()->modref_list;
206 PROCESS_Current()->modref_list = wm->next->prev = wm;
209 /* Remove recursion flag */
210 wm->flags &= ~WINE_MODREF_MARKER;
212 TRACE("(%s,%p) - END\n", wm->modname, lpReserved );
214 return retv;
217 /*************************************************************************
218 * MODULE_DllProcessDetach
220 * Send DLL process detach notifications. See the comment about calling
221 * sequence at MODULE_DllProcessAttach. Unless the bForceDetach flag
222 * is set, only DLLs with zero refcount are notified.
224 * NOTE: Assumes that the process critical section is held!
227 void MODULE_DllProcessDetach( BOOL bForceDetach, LPVOID lpReserved )
229 WINE_MODREF *wm;
233 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
235 /* Check whether to detach this DLL */
236 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
237 continue;
238 if ( wm->refCount > 0 && !bForceDetach )
239 continue;
241 /* Call detach notification */
242 wm->flags &= ~WINE_MODREF_PROCESS_ATTACHED;
243 MODULE_InitDll( wm, DLL_PROCESS_DETACH, lpReserved );
245 /* Restart at head of WINE_MODREF list, as entries might have
246 been added and/or removed while performing the call ... */
247 break;
249 } while ( wm );
252 /*************************************************************************
253 * MODULE_DllThreadAttach
255 * Send DLL thread attach notifications. These are sent in the
256 * reverse sequence of process detach notification.
259 void MODULE_DllThreadAttach( LPVOID lpReserved )
261 WINE_MODREF *wm;
263 EnterCriticalSection( &PROCESS_Current()->crit_section );
265 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
266 if ( !wm->next )
267 break;
269 for ( ; wm; wm = wm->prev )
271 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
272 continue;
273 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
274 continue;
276 MODULE_InitDll( wm, DLL_THREAD_ATTACH, lpReserved );
279 LeaveCriticalSection( &PROCESS_Current()->crit_section );
282 /*************************************************************************
283 * MODULE_DllThreadDetach
285 * Send DLL thread detach notifications. These are sent in the
286 * same sequence as process detach notification.
289 void MODULE_DllThreadDetach( LPVOID lpReserved )
291 WINE_MODREF *wm;
293 EnterCriticalSection( &PROCESS_Current()->crit_section );
295 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
297 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
298 continue;
299 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
300 continue;
302 MODULE_InitDll( wm, DLL_THREAD_DETACH, lpReserved );
305 LeaveCriticalSection( &PROCESS_Current()->crit_section );
308 /****************************************************************************
309 * DisableThreadLibraryCalls (KERNEL32.74)
311 * Don't call DllEntryPoint for DLL_THREAD_{ATTACH,DETACH} if set.
313 BOOL WINAPI DisableThreadLibraryCalls( HMODULE hModule )
315 WINE_MODREF *wm;
316 BOOL retval = TRUE;
318 EnterCriticalSection( &PROCESS_Current()->crit_section );
320 wm = MODULE32_LookupHMODULE( hModule );
321 if ( !wm )
322 retval = FALSE;
323 else
324 wm->flags |= WINE_MODREF_NO_DLL_CALLS;
326 LeaveCriticalSection( &PROCESS_Current()->crit_section );
328 return retval;
331 /*************************************************************************
332 * MODULE_SendLoadDLLEvents
334 * Sends DEBUG_DLL_LOAD events for all outstanding modules.
336 * NOTE: Assumes that the process critical section is held!
339 void MODULE_SendLoadDLLEvents( void )
341 WINE_MODREF *wm;
343 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
345 if ( wm->type != MODULE32_PE ) continue;
346 if ( wm == PROCESS_Current()->exe_modref ) continue;
347 if ( wm->flags & WINE_MODREF_DEBUG_EVENT_SENT ) continue;
349 DEBUG_SendLoadDLLEvent( -1 /*FIXME*/, wm->module, &wm->modname );
350 wm->flags |= WINE_MODREF_DEBUG_EVENT_SENT;
355 /***********************************************************************
356 * MODULE_CreateDummyModule
358 * Create a dummy NE module for Win32 or Winelib.
360 HMODULE MODULE_CreateDummyModule( LPCSTR filename, WORD version )
362 HMODULE hModule;
363 NE_MODULE *pModule;
364 SEGTABLEENTRY *pSegment;
365 char *pStr,*s;
366 unsigned int len;
367 const char* basename;
368 OFSTRUCT *ofs;
369 int of_size, size;
371 /* Extract base filename */
372 basename = strrchr(filename, '\\');
373 if (!basename) basename = filename;
374 else basename++;
375 len = strlen(basename);
376 if ((s = strchr(basename, '.'))) len = s - basename;
378 /* Allocate module */
379 of_size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName)
380 + strlen(filename) + 1;
381 size = sizeof(NE_MODULE) +
382 /* loaded file info */
383 of_size +
384 /* segment table: DS,CS */
385 2 * sizeof(SEGTABLEENTRY) +
386 /* name table */
387 len + 2 +
388 /* several empty tables */
391 hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
392 if (!hModule) return (HMODULE)11; /* invalid exe */
394 FarSetOwner16( hModule, hModule );
395 pModule = (NE_MODULE *)GlobalLock16( hModule );
397 /* Set all used entries */
398 pModule->magic = IMAGE_OS2_SIGNATURE;
399 pModule->count = 1;
400 pModule->next = 0;
401 pModule->flags = 0;
402 pModule->dgroup = 0;
403 pModule->ss = 1;
404 pModule->cs = 2;
405 pModule->heap_size = 0;
406 pModule->stack_size = 0;
407 pModule->seg_count = 2;
408 pModule->modref_count = 0;
409 pModule->nrname_size = 0;
410 pModule->fileinfo = sizeof(NE_MODULE);
411 pModule->os_flags = NE_OSFLAGS_WINDOWS;
412 pModule->expected_version = version;
413 pModule->self = hModule;
415 /* Set loaded file information */
416 ofs = (OFSTRUCT *)(pModule + 1);
417 memset( ofs, 0, of_size );
418 ofs->cBytes = of_size < 256 ? of_size : 255; /* FIXME */
419 strcpy( ofs->szPathName, filename );
421 pSegment = (SEGTABLEENTRY*)((char*)(pModule + 1) + of_size);
422 pModule->seg_table = (int)pSegment - (int)pModule;
423 /* Data segment */
424 pSegment->size = 0;
425 pSegment->flags = NE_SEGFLAGS_DATA;
426 pSegment->minsize = 0x1000;
427 pSegment++;
428 /* Code segment */
429 pSegment->flags = 0;
430 pSegment++;
432 /* Module name */
433 pStr = (char *)pSegment;
434 pModule->name_table = (int)pStr - (int)pModule;
435 assert(len<256);
436 *pStr = len;
437 lstrcpynA( pStr+1, basename, len+1 );
438 pStr += len+2;
440 /* All tables zero terminated */
441 pModule->res_table = pModule->import_table = pModule->entry_table =
442 (int)pStr - (int)pModule;
444 NE_RegisterModule( pModule );
445 return hModule;
449 /**********************************************************************
450 * MODULE_FindModule32
452 * Find a (loaded) win32 module depending on path
454 * RETURNS
455 * the module handle if found
456 * 0 if not
458 WINE_MODREF *MODULE_FindModule(
459 LPCSTR path /* [in] pathname of module/library to be found */
461 WINE_MODREF *wm;
462 char dllname[260], *p;
464 /* Append .DLL to name if no extension present */
465 strcpy( dllname, path );
466 if (!(p = strrchr( dllname, '.')) || strchr( p, '/' ) || strchr( p, '\\'))
467 strcat( dllname, ".DLL" );
469 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
471 if ( !strcasecmp( dllname, wm->modname ) )
472 break;
473 if ( !strcasecmp( dllname, wm->filename ) )
474 break;
475 if ( !strcasecmp( dllname, wm->short_modname ) )
476 break;
477 if ( !strcasecmp( dllname, wm->short_filename ) )
478 break;
481 return wm;
484 /***********************************************************************
485 * MODULE_GetBinaryType
487 * The GetBinaryType function determines whether a file is executable
488 * or not and if it is it returns what type of executable it is.
489 * The type of executable is a property that determines in which
490 * subsystem an executable file runs under.
492 * Binary types returned:
493 * SCS_32BIT_BINARY: A Win32 based application
494 * SCS_DOS_BINARY: An MS-Dos based application
495 * SCS_WOW_BINARY: A Win16 based application
496 * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
497 * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
498 * SCS_OS216_BINARY: A 16bit OS/2 based application
500 * Returns TRUE if the file is an executable in which case
501 * the value pointed by lpBinaryType is set.
502 * Returns FALSE if the file is not an executable or if the function fails.
504 * To do so it opens the file and reads in the header information
505 * if the extended header information is not present it will
506 * assume that the file is a DOS executable.
507 * If the extended header information is present it will
508 * determine if the file is a 16 or 32 bit Windows executable
509 * by check the flags in the header.
511 * Note that .COM and .PIF files are only recognized by their
512 * file name extension; but Windows does it the same way ...
514 static BOOL MODULE_GetBinaryType( HANDLE hfile, LPCSTR filename,
515 LPDWORD lpBinaryType )
517 IMAGE_DOS_HEADER mz_header;
518 char magic[4], *ptr;
519 DWORD len;
521 /* Seek to the start of the file and read the DOS header information.
523 if ( SetFilePointer( hfile, 0, NULL, SEEK_SET ) != -1
524 && ReadFile( hfile, &mz_header, sizeof(mz_header), &len, NULL )
525 && len == sizeof(mz_header) )
527 /* Now that we have the header check the e_magic field
528 * to see if this is a dos image.
530 if ( mz_header.e_magic == IMAGE_DOS_SIGNATURE )
532 BOOL lfanewValid = FALSE;
533 /* We do have a DOS image so we will now try to seek into
534 * the file by the amount indicated by the field
535 * "Offset to extended header" and read in the
536 * "magic" field information at that location.
537 * This will tell us if there is more header information
538 * to read or not.
540 /* But before we do we will make sure that header
541 * structure encompasses the "Offset to extended header"
542 * field.
544 if ( (mz_header.e_cparhdr<<4) >= sizeof(IMAGE_DOS_HEADER) )
545 if ( ( mz_header.e_crlc == 0 ) ||
546 ( mz_header.e_lfarlc >= sizeof(IMAGE_DOS_HEADER) ) )
547 if ( mz_header.e_lfanew >= sizeof(IMAGE_DOS_HEADER)
548 && SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET ) != -1
549 && ReadFile( hfile, magic, sizeof(magic), &len, NULL )
550 && len == sizeof(magic) )
551 lfanewValid = TRUE;
553 if ( !lfanewValid )
555 /* If we cannot read this "extended header" we will
556 * assume that we have a simple DOS executable.
558 *lpBinaryType = SCS_DOS_BINARY;
559 return TRUE;
561 else
563 /* Reading the magic field succeeded so
564 * we will try to determine what type it is.
566 if ( *(DWORD*)magic == IMAGE_NT_SIGNATURE )
568 /* This is an NT signature.
570 *lpBinaryType = SCS_32BIT_BINARY;
571 return TRUE;
573 else if ( *(WORD*)magic == IMAGE_OS2_SIGNATURE )
575 /* The IMAGE_OS2_SIGNATURE indicates that the
576 * "extended header is a Windows executable (NE)
577 * header." This can mean either a 16-bit OS/2
578 * or a 16-bit Windows or even a DOS program
579 * (running under a DOS extender). To decide
580 * which, we'll have to read the NE header.
583 IMAGE_OS2_HEADER ne;
584 if ( SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET ) != -1
585 && ReadFile( hfile, &ne, sizeof(ne), &len, NULL )
586 && len == sizeof(ne) )
588 switch ( ne.operating_system )
590 case 2: *lpBinaryType = SCS_WOW_BINARY; return TRUE;
591 case 5: *lpBinaryType = SCS_DOS_BINARY; return TRUE;
592 default: *lpBinaryType = SCS_OS216_BINARY; return TRUE;
595 /* Couldn't read header, so abort. */
596 return FALSE;
598 else
600 /* Unknown extended header, but this file is nonetheless
601 DOS-executable.
603 *lpBinaryType = SCS_DOS_BINARY;
604 return TRUE;
610 /* If we get here, we don't even have a correct MZ header.
611 * Try to check the file extension for known types ...
613 ptr = strrchr( filename, '.' );
614 if ( ptr && !strchr( ptr, '\\' ) && !strchr( ptr, '/' ) )
616 if ( !lstrcmpiA( ptr, ".COM" ) )
618 *lpBinaryType = SCS_DOS_BINARY;
619 return TRUE;
622 if ( !lstrcmpiA( ptr, ".PIF" ) )
624 *lpBinaryType = SCS_PIF_BINARY;
625 return TRUE;
629 return FALSE;
632 /***********************************************************************
633 * GetBinaryTypeA [KERNEL32.280]
635 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
637 BOOL ret = FALSE;
638 HANDLE hfile;
640 TRACE_(win32)("%s\n", lpApplicationName );
642 /* Sanity check.
644 if ( lpApplicationName == NULL || lpBinaryType == NULL )
645 return FALSE;
647 /* Open the file indicated by lpApplicationName for reading.
649 hfile = CreateFileA( lpApplicationName, GENERIC_READ, 0,
650 NULL, OPEN_EXISTING, 0, -1 );
651 if ( hfile == INVALID_HANDLE_VALUE )
652 return FALSE;
654 /* Check binary type
656 ret = MODULE_GetBinaryType( hfile, lpApplicationName, lpBinaryType );
658 /* Close the file.
660 CloseHandle( hfile );
662 return ret;
665 /***********************************************************************
666 * GetBinaryTypeW [KERNEL32.281]
668 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
670 BOOL ret = FALSE;
671 LPSTR strNew = NULL;
673 TRACE_(win32)("%s\n", debugstr_w(lpApplicationName) );
675 /* Sanity check.
677 if ( lpApplicationName == NULL || lpBinaryType == NULL )
678 return FALSE;
680 /* Convert the wide string to a ascii string.
682 strNew = HEAP_strdupWtoA( GetProcessHeap(), 0, lpApplicationName );
684 if ( strNew != NULL )
686 ret = GetBinaryTypeA( strNew, lpBinaryType );
688 /* Free the allocated string.
690 HeapFree( GetProcessHeap(), 0, strNew );
693 return ret;
696 /**********************************************************************
697 * MODULE_CreateUnixProcess
699 static BOOL MODULE_CreateUnixProcess( LPCSTR filename, LPCSTR lpCmdLine,
700 LPSTARTUPINFOA lpStartupInfo,
701 LPPROCESS_INFORMATION lpProcessInfo,
702 BOOL useWine )
704 DOS_FULL_NAME full_name;
705 const char *unixfilename = filename;
706 const char *argv[256], **argptr;
707 char *cmdline = NULL;
708 BOOL iconic = FALSE;
710 /* Get Unix file name and iconic flag */
712 if ( lpStartupInfo->dwFlags & STARTF_USESHOWWINDOW )
713 if ( lpStartupInfo->wShowWindow == SW_SHOWMINIMIZED
714 || lpStartupInfo->wShowWindow == SW_SHOWMINNOACTIVE )
715 iconic = TRUE;
717 /* Build argument list */
719 argptr = argv;
720 if ( !useWine )
722 char *p;
723 p = cmdline = strdup(lpCmdLine);
724 if (strchr(filename, '/') || strchr(filename, ':') || strchr(filename, '\\'))
726 if ( DOSFS_GetFullName( filename, TRUE, &full_name ) )
727 unixfilename = full_name.long_name;
729 *argptr++ = unixfilename;
730 if (iconic) *argptr++ = "-iconic";
731 while (1)
733 while (*p && (*p == ' ' || *p == '\t')) *p++ = '\0';
734 if (!*p) break;
735 *argptr++ = p;
736 while (*p && *p != ' ' && *p != '\t') p++;
739 else
741 *argptr++ = "wine";
742 if (iconic) *argptr++ = "-iconic";
743 *argptr++ = lpCmdLine;
745 *argptr++ = 0;
747 /* Fork and execute */
749 if ( !fork() )
751 /* Note: don't use Wine routines here, as this process
752 has not been correctly initialized! */
754 execvp( argv[0], (char**)argv );
756 /* Failed ! */
757 if ( useWine )
758 fprintf( stderr, "CreateProcess: can't exec 'wine %s'\n",
759 lpCmdLine );
760 exit( 1 );
763 /* Fake success return value */
765 memset( lpProcessInfo, '\0', sizeof( *lpProcessInfo ) );
766 lpProcessInfo->hProcess = INVALID_HANDLE_VALUE;
767 lpProcessInfo->hThread = INVALID_HANDLE_VALUE;
768 if (cmdline) free(cmdline);
770 SetLastError( ERROR_SUCCESS );
771 return TRUE;
774 /***********************************************************************
775 * WinExec16 (KERNEL.166)
777 HINSTANCE16 WINAPI WinExec16( LPCSTR lpCmdLine, UINT16 nCmdShow )
779 HINSTANCE16 hInst;
781 SYSLEVEL_ReleaseWin16Lock();
782 hInst = WinExec( lpCmdLine, nCmdShow );
783 SYSLEVEL_RestoreWin16Lock();
785 return hInst;
788 /***********************************************************************
789 * WinExec (KERNEL32.566)
791 HINSTANCE WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
793 LOADPARAMS params;
794 UINT16 paramCmdShow[2];
796 if (!lpCmdLine)
797 return 2; /* File not found */
799 /* Set up LOADPARAMS buffer for LoadModule */
801 memset( &params, '\0', sizeof(params) );
802 params.lpCmdLine = (LPSTR)lpCmdLine;
803 params.lpCmdShow = paramCmdShow;
804 params.lpCmdShow[0] = 2;
805 params.lpCmdShow[1] = nCmdShow;
807 /* Now load the executable file */
809 return LoadModule( NULL, &params );
812 /**********************************************************************
813 * LoadModule (KERNEL32.499)
815 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
817 LOADPARAMS *params = (LOADPARAMS *)paramBlock;
818 PROCESS_INFORMATION info;
819 STARTUPINFOA startup;
820 HINSTANCE hInstance;
821 PDB *pdb;
822 TDB *tdb;
824 memset( &startup, '\0', sizeof(startup) );
825 startup.cb = sizeof(startup);
826 startup.dwFlags = STARTF_USESHOWWINDOW;
827 startup.wShowWindow = params->lpCmdShow? params->lpCmdShow[1] : 0;
829 if ( !CreateProcessA( name, params->lpCmdLine,
830 NULL, NULL, FALSE, 0, params->lpEnvAddress,
831 NULL, &startup, &info ) )
833 hInstance = GetLastError();
834 if ( hInstance < 32 ) return hInstance;
836 FIXME("Strange error set by CreateProcess: %d\n", hInstance );
837 return 11;
840 /* Give 30 seconds to the app to come up */
841 if ( Callout.WaitForInputIdle ( info.hProcess, 30000 ) == 0xFFFFFFFF )
842 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
844 /* Get 16-bit hInstance/hTask from process */
845 pdb = PROCESS_IdToPDB( info.dwProcessId );
846 tdb = pdb? (TDB *)GlobalLock16( pdb->task ) : NULL;
847 hInstance = tdb && tdb->hInstance? tdb->hInstance : pdb? pdb->task : 0;
848 /* If there is no hInstance (32-bit process) return a dummy value
849 * that must be > 31
850 * FIXME: should do this in all cases and fix Win16 callers */
851 if (!hInstance) hInstance = 33;
853 /* Close off the handles */
854 CloseHandle( info.hThread );
855 CloseHandle( info.hProcess );
857 return hInstance;
860 /*************************************************************************
861 * get_makename_token
863 * Get next blank delimited token from input string. If quoted then
864 * process till matching quote and then till blank.
866 * Returns number of characters in token (not including \0). On
867 * end of string (EOS), returns a 0.
869 * from (IO) address of start of input string to scan, updated to
870 * next non-processed character.
871 * to (IO) address of start of output string (previous token \0
872 * char), updated to end of new output string (the \0
873 * char).
875 static int get_makename_token(LPCSTR *from, LPSTR *to )
877 int len = 0;
878 LPCSTR to_old = *to; /* only used for tracing */
880 while ( **from == ' ') {
881 /* Copy leading blanks (separators between previous */
882 /* token and this token). */
883 **to = **from;
884 (*from)++;
885 (*to)++;
886 len++;
888 do {
889 while ( (**from != 0) && (**from != ' ') && (**from != '"') ) {
890 **to = **from; (*from)++; (*to)++; len++;
892 if ( **from == '"' ) {
893 /* Handle quoted string. */
894 (*from)++;
895 if ( !strchr(*from, '"') ) {
896 /* fail - no closing quote. Return entire string */
897 while ( **from != 0 ) {
898 **to = **from; (*from)++; (*to)++; len++;
900 break;
902 while( **from != '"') {
903 **to = **from;
904 len++;
905 (*to)++;
906 (*from)++;
908 (*from)++;
909 continue;
912 /* either EOS or ' ' */
913 break;
915 } while (1);
917 **to = 0; /* terminate output string */
919 TRACE("returning token len=%d, string=%s\n", len, to_old);
921 return len;
924 /*************************************************************************
925 * make_lpCommandLine_name
927 * Try longer and longer strings from "line" to find an existing
928 * file name. Each attempt is delimited by a blank outside of quotes.
929 * Also will attempt to append ".exe" if requested and not already
930 * present. Returns the address of the remaining portion of the
931 * input line.
935 static BOOL make_lpCommandLine_name( LPCSTR line, LPSTR name, int namelen,
936 LPCSTR *after )
938 BOOL found = TRUE;
939 LPCSTR from;
940 char buffer[260];
941 DWORD retlen;
942 LPSTR to, lastpart;
944 from = line;
945 to = name;
947 /* scan over initial blanks if any */
948 while ( *from == ' ') from++;
950 /* get a token and append to previous data the check for existance */
951 do {
952 if ( !get_makename_token( &from, &to ) ) {
953 /* EOS has occured and not found - exit */
954 retlen = 0;
955 found = FALSE;
956 break;
958 TRACE("checking if file exists '%s'\n", name);
959 retlen = SearchPathA( NULL, name, ".exe", sizeof(buffer), buffer, &lastpart);
960 if ( retlen && (retlen < sizeof(buffer)) ) break;
961 } while (1);
963 /* if we have a non-null full path name in buffer then move to output */
964 if ( retlen ) {
965 if ( strlen(buffer) <= namelen ) {
966 strcpy( name, buffer );
967 } else {
968 /* not enough space to return full path string */
969 FIXME("internal string not long enough, need %d\n",
970 strlen(buffer) );
974 /* all done, indicate end of module name and then trace and exit */
975 if (after) *after = from;
976 TRACE("%i, selected file name '%s'\n and cmdline as %s\n",
977 found, name, debugstr_a(from));
978 return found;
981 /*************************************************************************
982 * make_lpApplicationName_name
984 * Scan input string (the lpApplicationName) and remove any quotes
985 * if they are balanced.
989 static BOOL make_lpApplicationName_name( LPCSTR line, LPSTR name, int namelen)
991 LPCSTR from;
992 LPSTR to, to_end, to_old;
993 char buffer[260];
995 to = buffer;
996 to_end = to + sizeof(buffer) - 1;
997 to_old = to;
999 while ( *line == ' ' ) line++; /* point to beginning of string */
1000 from = line;
1001 do {
1002 /* Copy all input till end, or quote */
1003 while((*from != 0) && (*from != '"') && (to < to_end))
1004 *to++ = *from++;
1005 if (to >= to_end) { *to = 0; break; }
1007 if (*from == '"')
1009 /* Handle quoted string. If there is a closing quote, copy all */
1010 /* that is inside. */
1011 from++;
1012 if (!strchr(from, '"'))
1014 /* fail - no closing quote */
1015 to = to_old; /* restore to previous attempt */
1016 *to = 0; /* end string */
1017 break; /* exit with previous attempt */
1019 while((*from != '"') && (to < to_end)) *to++ = *from++;
1020 if (to >= to_end) { *to = 0; break; }
1021 from++;
1022 continue; /* past quoted string, so restart from top */
1025 *to = 0; /* terminate output string */
1026 to_old = to; /* save for possible use in unmatched quote case */
1028 /* loop around keeping the blank as part of file name */
1029 if (!*from)
1030 break; /* exit if out of input string */
1031 } while (1);
1033 if (!SearchPathA( NULL, buffer, ".exe", namelen, name, NULL )) {
1034 TRACE("file not found '%s'\n", buffer );
1035 return FALSE;
1038 TRACE("selected as file name '%s'\n", name );
1039 return TRUE;
1042 /**********************************************************************
1043 * CreateProcessA (KERNEL32.171)
1045 BOOL WINAPI CreateProcessA( LPCSTR lpApplicationName, LPSTR lpCommandLine,
1046 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1047 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1048 BOOL bInheritHandles, DWORD dwCreationFlags,
1049 LPVOID lpEnvironment, LPCSTR lpCurrentDirectory,
1050 LPSTARTUPINFOA lpStartupInfo,
1051 LPPROCESS_INFORMATION lpProcessInfo )
1053 BOOL retv = FALSE;
1054 BOOL found_file = FALSE;
1055 HANDLE hFile;
1056 DWORD type;
1057 char name[256], dummy[256];
1058 LPCSTR cmdline = NULL;
1059 LPSTR tidy_cmdline;
1061 /* Get name and command line */
1063 if (!lpApplicationName && !lpCommandLine)
1065 SetLastError( ERROR_FILE_NOT_FOUND );
1066 return FALSE;
1069 /* Process the AppName and/or CmdLine to get module name and path */
1071 name[0] = '\0';
1073 if (lpApplicationName)
1075 found_file = make_lpApplicationName_name( lpApplicationName, name, sizeof(name) );
1076 if (lpCommandLine)
1077 make_lpCommandLine_name( lpCommandLine, dummy, sizeof ( dummy ), &cmdline );
1078 else
1079 cmdline = lpApplicationName;
1081 else
1083 if (lpCommandLine)
1084 found_file = make_lpCommandLine_name( lpCommandLine, name, sizeof ( name ), &cmdline );
1087 if ( !found_file ) {
1088 /* make an early exit if file not found - save second pass */
1089 SetLastError( ERROR_FILE_NOT_FOUND );
1090 return FALSE;
1093 if (!cmdline) cmdline = "";
1094 tidy_cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(name) + strlen(cmdline) + 3 );
1095 TRACE_(module)("tidy_cmdline: name '%s'[%d], cmdline '%s'[%d]\n",
1096 name, strlen(name), cmdline, strlen(cmdline));
1097 sprintf( tidy_cmdline, "\"%s\"%s", name, cmdline);
1099 /* Warn if unsupported features are used */
1101 if (dwCreationFlags & DETACHED_PROCESS)
1102 FIXME("(%s,...): DETACHED_PROCESS ignored\n", name);
1103 if (dwCreationFlags & CREATE_NEW_CONSOLE)
1104 FIXME("(%s,...): CREATE_NEW_CONSOLE ignored\n", name);
1105 if (dwCreationFlags & NORMAL_PRIORITY_CLASS)
1106 FIXME("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
1107 if (dwCreationFlags & IDLE_PRIORITY_CLASS)
1108 FIXME("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
1109 if (dwCreationFlags & HIGH_PRIORITY_CLASS)
1110 FIXME("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
1111 if (dwCreationFlags & REALTIME_PRIORITY_CLASS)
1112 FIXME("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
1113 if (dwCreationFlags & CREATE_NEW_PROCESS_GROUP)
1114 FIXME("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
1115 if (dwCreationFlags & CREATE_UNICODE_ENVIRONMENT)
1116 FIXME("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
1117 if (dwCreationFlags & CREATE_SEPARATE_WOW_VDM)
1118 FIXME("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
1119 if (dwCreationFlags & CREATE_SHARED_WOW_VDM)
1120 FIXME("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
1121 if (dwCreationFlags & CREATE_DEFAULT_ERROR_MODE)
1122 FIXME("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
1123 if (dwCreationFlags & CREATE_NO_WINDOW)
1124 FIXME("(%s,...): CREATE_NO_WINDOW ignored\n", name);
1125 if (dwCreationFlags & PROFILE_USER)
1126 FIXME("(%s,...): PROFILE_USER ignored\n", name);
1127 if (dwCreationFlags & PROFILE_KERNEL)
1128 FIXME("(%s,...): PROFILE_KERNEL ignored\n", name);
1129 if (dwCreationFlags & PROFILE_SERVER)
1130 FIXME("(%s,...): PROFILE_SERVER ignored\n", name);
1131 if (lpCurrentDirectory)
1132 FIXME("(%s,...): lpCurrentDirectory %s ignored\n",
1133 name, lpCurrentDirectory);
1134 if (lpStartupInfo->lpDesktop)
1135 FIXME("(%s,...): lpStartupInfo->lpDesktop %s ignored\n",
1136 name, lpStartupInfo->lpDesktop);
1137 if (lpStartupInfo->lpTitle)
1138 FIXME("(%s,...): lpStartupInfo->lpTitle %s ignored\n",
1139 name, lpStartupInfo->lpTitle);
1140 if (lpStartupInfo->dwFlags & STARTF_USECOUNTCHARS)
1141 FIXME("(%s,...): STARTF_USECOUNTCHARS (%ld,%ld) ignored\n",
1142 name, lpStartupInfo->dwXCountChars, lpStartupInfo->dwYCountChars);
1143 if (lpStartupInfo->dwFlags & STARTF_USEFILLATTRIBUTE)
1144 FIXME("(%s,...): STARTF_USEFILLATTRIBUTE %lx ignored\n",
1145 name, lpStartupInfo->dwFillAttribute);
1146 if (lpStartupInfo->dwFlags & STARTF_RUNFULLSCREEN)
1147 FIXME("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
1148 if (lpStartupInfo->dwFlags & STARTF_FORCEONFEEDBACK)
1149 FIXME("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
1150 if (lpStartupInfo->dwFlags & STARTF_FORCEOFFFEEDBACK)
1151 FIXME("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
1152 if (lpStartupInfo->dwFlags & STARTF_USEHOTKEY)
1153 FIXME("(%s,...): STARTF_USEHOTKEY ignored\n", name);
1156 /* Load file and create process */
1158 if ( !retv )
1160 /* Open file and determine executable type */
1162 hFile = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ,
1163 NULL, OPEN_EXISTING, 0, -1 );
1164 if ( hFile == INVALID_HANDLE_VALUE )
1166 SetLastError( ERROR_FILE_NOT_FOUND );
1167 HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1168 return FALSE;
1171 if ( !MODULE_GetBinaryType( hFile, name, &type ) )
1173 CloseHandle( hFile );
1175 /* FIXME: Try Unix executable only when appropriate! */
1176 if ( MODULE_CreateUnixProcess( name, tidy_cmdline,
1177 lpStartupInfo, lpProcessInfo, FALSE ) )
1179 HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1180 return TRUE;
1182 HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1183 SetLastError( ERROR_BAD_FORMAT );
1184 return FALSE;
1188 /* Create process */
1190 switch ( type )
1192 case SCS_32BIT_BINARY:
1193 retv = PE_CreateProcess( hFile, name, tidy_cmdline, lpEnvironment,
1194 lpProcessAttributes, lpThreadAttributes,
1195 bInheritHandles, dwCreationFlags,
1196 lpStartupInfo, lpProcessInfo );
1197 break;
1199 case SCS_DOS_BINARY:
1200 retv = MZ_CreateProcess( hFile, name, tidy_cmdline, lpEnvironment,
1201 lpProcessAttributes, lpThreadAttributes,
1202 bInheritHandles, dwCreationFlags,
1203 lpStartupInfo, lpProcessInfo );
1204 break;
1206 case SCS_WOW_BINARY:
1207 retv = NE_CreateProcess( hFile, name, tidy_cmdline, lpEnvironment,
1208 lpProcessAttributes, lpThreadAttributes,
1209 bInheritHandles, dwCreationFlags,
1210 lpStartupInfo, lpProcessInfo );
1211 break;
1213 case SCS_PIF_BINARY:
1214 case SCS_POSIX_BINARY:
1215 case SCS_OS216_BINARY:
1216 FIXME("Unsupported executable type: %ld\n", type );
1217 /* fall through */
1219 default:
1220 SetLastError( ERROR_BAD_FORMAT );
1221 retv = FALSE;
1222 break;
1225 CloseHandle( hFile );
1227 HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1228 return retv;
1231 /**********************************************************************
1232 * CreateProcessW (KERNEL32.172)
1233 * NOTES
1234 * lpReserved is not converted
1236 BOOL WINAPI CreateProcessW( LPCWSTR lpApplicationName, LPWSTR lpCommandLine,
1237 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1238 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1239 BOOL bInheritHandles, DWORD dwCreationFlags,
1240 LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory,
1241 LPSTARTUPINFOW lpStartupInfo,
1242 LPPROCESS_INFORMATION lpProcessInfo )
1243 { BOOL ret;
1244 STARTUPINFOA StartupInfoA;
1246 LPSTR lpApplicationNameA = HEAP_strdupWtoA (GetProcessHeap(),0,lpApplicationName);
1247 LPSTR lpCommandLineA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCommandLine);
1248 LPSTR lpCurrentDirectoryA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCurrentDirectory);
1250 memcpy (&StartupInfoA, lpStartupInfo, sizeof(STARTUPINFOA));
1251 StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpDesktop);
1252 StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpTitle);
1254 TRACE_(win32)("(%s,%s,...)\n", debugstr_w(lpApplicationName), debugstr_w(lpCommandLine));
1256 if (lpStartupInfo->lpReserved)
1257 FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n", debugstr_w(lpStartupInfo->lpReserved));
1259 ret = CreateProcessA( lpApplicationNameA, lpCommandLineA,
1260 lpProcessAttributes, lpThreadAttributes,
1261 bInheritHandles, dwCreationFlags,
1262 lpEnvironment, lpCurrentDirectoryA,
1263 &StartupInfoA, lpProcessInfo );
1265 HeapFree( GetProcessHeap(), 0, lpCurrentDirectoryA );
1266 HeapFree( GetProcessHeap(), 0, lpCommandLineA );
1267 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1268 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1270 return ret;
1273 /***********************************************************************
1274 * GetModuleHandle (KERNEL32.237)
1276 HMODULE WINAPI GetModuleHandleA(LPCSTR module)
1278 WINE_MODREF *wm;
1280 if ( module == NULL )
1281 wm = PROCESS_Current()->exe_modref;
1282 else
1283 wm = MODULE_FindModule( module );
1285 return wm? wm->module : 0;
1288 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
1290 HMODULE hModule;
1291 LPSTR modulea = HEAP_strdupWtoA( GetProcessHeap(), 0, module );
1292 hModule = GetModuleHandleA( modulea );
1293 HeapFree( GetProcessHeap(), 0, modulea );
1294 return hModule;
1298 /***********************************************************************
1299 * GetModuleFileNameA (KERNEL32.235)
1301 * GetModuleFileNameA seems to *always* return the long path;
1302 * it's only GetModuleFileName16 that decides between short/long path
1303 * by checking if exe version >= 4.0.
1304 * (SDK docu doesn't mention this)
1306 DWORD WINAPI GetModuleFileNameA(
1307 HMODULE hModule, /* [in] module handle (32bit) */
1308 LPSTR lpFileName, /* [out] filenamebuffer */
1309 DWORD size /* [in] size of filenamebuffer */
1310 ) {
1311 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1313 if (!wm) /* can happen on start up or the like */
1314 return 0;
1316 lstrcpynA( lpFileName, wm->filename, size );
1318 TRACE("%s\n", lpFileName );
1319 return strlen(lpFileName);
1323 /***********************************************************************
1324 * GetModuleFileName32W (KERNEL32.236)
1326 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName,
1327 DWORD size )
1329 LPSTR fnA = (char*)HeapAlloc( GetProcessHeap(), 0, size );
1330 DWORD res = GetModuleFileNameA( hModule, fnA, size );
1331 lstrcpynAtoW( lpFileName, fnA, size );
1332 HeapFree( GetProcessHeap(), 0, fnA );
1333 return res;
1337 /***********************************************************************
1338 * LoadLibraryExA (KERNEL32)
1340 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
1342 WINE_MODREF *wm;
1344 if(!libname)
1346 SetLastError(ERROR_INVALID_PARAMETER);
1347 return 0;
1350 EnterCriticalSection(&PROCESS_Current()->crit_section);
1352 wm = MODULE_LoadLibraryExA( libname, hfile, flags );
1353 if ( wm )
1355 MODULE_SendLoadDLLEvents();
1357 if ( !MODULE_DllProcessAttach( wm, NULL ) )
1359 WARN_(module)("Attach failed for module '%s', \n", libname);
1360 MODULE_FreeLibrary(wm);
1361 SetLastError(ERROR_DLL_INIT_FAILED);
1362 wm = NULL;
1366 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1368 return wm ? wm->module : 0;
1371 /***********************************************************************
1372 * MODULE_LoadLibraryExA (internal)
1374 * Load a PE style module according to the load order.
1376 * The HFILE parameter is not used and marked reserved in the SDK. I can
1377 * only guess that it should force a file to be mapped, but I rather
1378 * ignore the parameter because it would be extremely difficult to
1379 * integrate this with different types of module represenations.
1382 WINE_MODREF *MODULE_LoadLibraryExA( LPCSTR libname, HFILE hfile, DWORD flags )
1384 DWORD err;
1385 WINE_MODREF *pwm;
1386 int i;
1387 module_loadorder_t *plo;
1389 EnterCriticalSection(&PROCESS_Current()->crit_section);
1391 /* Check for already loaded module */
1392 if((pwm = MODULE_FindModule(libname)))
1394 if(!(pwm->flags & WINE_MODREF_MARKER))
1395 pwm->refCount++;
1396 TRACE("Already loaded module '%s' at 0x%08x, count=%d, \n", libname, pwm->module, pwm->refCount);
1397 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1398 return pwm;
1401 plo = MODULE_GetLoadOrder(libname);
1403 for(i = 0; i < MODULE_LOADORDER_NTYPES; i++)
1405 switch(plo->loadorder[i])
1407 case MODULE_LOADORDER_DLL:
1408 TRACE("Trying native dll '%s'\n", libname);
1409 pwm = PE_LoadLibraryExA(libname, flags, &err);
1410 break;
1412 case MODULE_LOADORDER_ELFDLL:
1413 TRACE("Trying elfdll '%s'\n", libname);
1414 pwm = ELFDLL_LoadLibraryExA(libname, flags, &err);
1415 break;
1417 case MODULE_LOADORDER_SO:
1418 TRACE("Trying so-library '%s'\n", libname);
1419 pwm = ELF_LoadLibraryExA(libname, flags, &err);
1420 break;
1422 case MODULE_LOADORDER_BI:
1423 TRACE("Trying built-in '%s'\n", libname);
1424 pwm = BUILTIN32_LoadLibraryExA(libname, flags, &err);
1425 break;
1427 default:
1428 ERR("Got invalid loadorder type %d (%s index %d)\n", plo->loadorder[i], plo->modulename, i);
1429 /* Fall through */
1431 case MODULE_LOADORDER_INVALID: /* We ignore this as it is an empty entry */
1432 pwm = NULL;
1433 break;
1436 if(pwm)
1438 /* Initialize DLL just loaded */
1439 TRACE("Loaded module '%s' at 0x%08x, \n", libname, pwm->module);
1441 /* Set the refCount here so that an attach failure will */
1442 /* decrement the dependencies through the MODULE_FreeLibrary call. */
1443 pwm->refCount++;
1445 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1447 return pwm;
1450 if(err != ERROR_FILE_NOT_FOUND)
1451 break;
1454 WARN("Failed to load module '%s'; error=0x%08lx, \n", libname, err);
1455 SetLastError(err);
1456 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1457 return NULL;
1460 /***********************************************************************
1461 * LoadLibraryA (KERNEL32)
1463 HMODULE WINAPI LoadLibraryA(LPCSTR libname) {
1464 return LoadLibraryExA(libname,0,0);
1467 /***********************************************************************
1468 * LoadLibraryW (KERNEL32)
1470 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
1472 return LoadLibraryExW(libnameW,0,0);
1475 /***********************************************************************
1476 * LoadLibrary32_16 (KERNEL.452)
1478 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
1480 HMODULE hModule;
1482 SYSLEVEL_ReleaseWin16Lock();
1483 hModule = LoadLibraryA( libname );
1484 SYSLEVEL_RestoreWin16Lock();
1486 return hModule;
1489 /***********************************************************************
1490 * LoadLibraryExW (KERNEL32)
1492 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW,HANDLE hfile,DWORD flags)
1494 LPSTR libnameA = HEAP_strdupWtoA( GetProcessHeap(), 0, libnameW );
1495 HMODULE ret = LoadLibraryExA( libnameA , hfile, flags );
1497 HeapFree( GetProcessHeap(), 0, libnameA );
1498 return ret;
1501 /***********************************************************************
1502 * MODULE_FlushModrefs
1504 * NOTE: Assumes that the process critical section is held!
1506 * Remove all unused modrefs and call the internal unloading routines
1507 * for the library type.
1509 static void MODULE_FlushModrefs(void)
1511 WINE_MODREF *wm, *next;
1513 for(wm = PROCESS_Current()->modref_list; wm; wm = next)
1515 next = wm->next;
1517 if(wm->refCount)
1518 continue;
1520 /* Unlink this modref from the chain */
1521 if(wm->next)
1522 wm->next->prev = wm->prev;
1523 if(wm->prev)
1524 wm->prev->next = wm->next;
1525 if(wm == PROCESS_Current()->modref_list)
1526 PROCESS_Current()->modref_list = wm->next;
1529 * The unloaders are also responsible for freeing the modref itself
1530 * because the loaders were responsible for allocating it.
1532 switch(wm->type)
1534 case MODULE32_PE: PE_UnloadLibrary(wm); break;
1535 case MODULE32_ELF: ELF_UnloadLibrary(wm); break;
1536 case MODULE32_ELFDLL: ELFDLL_UnloadLibrary(wm); break;
1537 case MODULE32_BI: BUILTIN32_UnloadLibrary(wm); break;
1539 default:
1540 ERR("Invalid or unhandled MODREF type %d encountered (wm=%p)\n", wm->type, wm);
1545 /***********************************************************************
1546 * FreeLibrary
1548 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
1550 BOOL retv = FALSE;
1551 WINE_MODREF *wm;
1553 EnterCriticalSection( &PROCESS_Current()->crit_section );
1554 PROCESS_Current()->free_lib_count++;
1556 wm = MODULE32_LookupHMODULE( hLibModule );
1557 if ( !wm || !hLibModule )
1558 SetLastError( ERROR_INVALID_HANDLE );
1559 else
1560 retv = MODULE_FreeLibrary( wm );
1562 PROCESS_Current()->free_lib_count--;
1563 LeaveCriticalSection( &PROCESS_Current()->crit_section );
1565 return retv;
1568 /***********************************************************************
1569 * MODULE_DecRefCount
1571 * NOTE: Assumes that the process critical section is held!
1573 static void MODULE_DecRefCount( WINE_MODREF *wm )
1575 int i;
1577 if ( wm->flags & WINE_MODREF_MARKER )
1578 return;
1580 if ( wm->refCount <= 0 )
1581 return;
1583 --wm->refCount;
1584 TRACE("(%s) refCount: %d\n", wm->modname, wm->refCount );
1586 if ( wm->refCount == 0 )
1588 wm->flags |= WINE_MODREF_MARKER;
1590 for ( i = 0; i < wm->nDeps; i++ )
1591 if ( wm->deps[i] )
1592 MODULE_DecRefCount( wm->deps[i] );
1594 wm->flags &= ~WINE_MODREF_MARKER;
1598 /***********************************************************************
1599 * MODULE_FreeLibrary
1601 * NOTE: Assumes that the process critical section is held!
1603 BOOL MODULE_FreeLibrary( WINE_MODREF *wm )
1605 TRACE("(%s) - START\n", wm->modname );
1607 /* Recursively decrement reference counts */
1608 MODULE_DecRefCount( wm );
1610 /* Call process detach notifications */
1611 if ( PROCESS_Current()->free_lib_count <= 1 )
1613 MODULE_DllProcessDetach( FALSE, NULL );
1614 DEBUG_SendUnloadDLLEvent( wm->module );
1617 TRACE("END\n");
1619 MODULE_FlushModrefs();
1621 return TRUE;
1625 /***********************************************************************
1626 * FreeLibraryAndExitThread
1628 VOID WINAPI FreeLibraryAndExitThread(HINSTANCE hLibModule, DWORD dwExitCode)
1630 FreeLibrary(hLibModule);
1631 ExitThread(dwExitCode);
1634 /***********************************************************************
1635 * PrivateLoadLibrary (KERNEL32)
1637 * FIXME: rough guesswork, don't know what "Private" means
1639 HINSTANCE WINAPI PrivateLoadLibrary(LPCSTR libname)
1641 return (HINSTANCE)LoadLibrary16(libname);
1646 /***********************************************************************
1647 * PrivateFreeLibrary (KERNEL32)
1649 * FIXME: rough guesswork, don't know what "Private" means
1651 void WINAPI PrivateFreeLibrary(HINSTANCE handle)
1653 FreeLibrary16((HINSTANCE16)handle);
1657 /***********************************************************************
1658 * WIN32_GetProcAddress16 (KERNEL32.36)
1659 * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
1661 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
1663 WORD ordinal;
1664 FARPROC16 ret;
1666 if (!hModule) {
1667 WARN("hModule may not be 0!\n");
1668 return (FARPROC16)0;
1670 if (HIWORD(hModule))
1672 WARN("hModule is Win32 handle (%08x)\n", hModule );
1673 return (FARPROC16)0;
1675 hModule = GetExePtr( hModule );
1676 if (HIWORD(name)) {
1677 ordinal = NE_GetOrdinal( hModule, name );
1678 TRACE("%04x '%s'\n", hModule, name );
1679 } else {
1680 ordinal = LOWORD(name);
1681 TRACE("%04x %04x\n", hModule, ordinal );
1683 if (!ordinal) return (FARPROC16)0;
1684 ret = NE_GetEntryPoint( hModule, ordinal );
1685 TRACE("returning %08x\n",(UINT)ret);
1686 return ret;
1689 /***********************************************************************
1690 * GetProcAddress16 (KERNEL.50)
1692 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, SEGPTR name )
1694 WORD ordinal;
1695 FARPROC16 ret;
1697 if (!hModule) hModule = GetCurrentTask();
1698 hModule = GetExePtr( hModule );
1700 if (HIWORD(name) != 0)
1702 ordinal = NE_GetOrdinal( hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1703 TRACE("%04x '%s'\n", hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1705 else
1707 ordinal = LOWORD(name);
1708 TRACE("%04x %04x\n", hModule, ordinal );
1710 if (!ordinal) return (FARPROC16)0;
1712 ret = NE_GetEntryPoint( hModule, ordinal );
1714 TRACE("returning %08x\n", (UINT)ret );
1715 return ret;
1719 /***********************************************************************
1720 * GetProcAddress32 (KERNEL32.257)
1722 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1724 return MODULE_GetProcAddress( hModule, function, TRUE );
1727 /***********************************************************************
1728 * WIN16_GetProcAddress32 (KERNEL.453)
1730 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
1732 return MODULE_GetProcAddress( hModule, function, FALSE );
1735 /***********************************************************************
1736 * MODULE_GetProcAddress32 (internal)
1738 FARPROC MODULE_GetProcAddress(
1739 HMODULE hModule, /* [in] current module handle */
1740 LPCSTR function, /* [in] function to be looked up */
1741 BOOL snoop )
1743 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1744 FARPROC retproc;
1746 if (HIWORD(function))
1747 TRACE_(win32)("(%08lx,%s)\n",(DWORD)hModule,function);
1748 else
1749 TRACE_(win32)("(%08lx,%p)\n",(DWORD)hModule,function);
1750 if (!wm) {
1751 SetLastError(ERROR_INVALID_HANDLE);
1752 return (FARPROC)0;
1754 switch (wm->type)
1756 case MODULE32_PE:
1757 retproc = PE_FindExportedFunction( wm, function, snoop );
1758 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1759 return retproc;
1760 case MODULE32_ELF:
1761 retproc = ELF_FindExportedFunction( wm, function);
1762 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1763 return retproc;
1764 default:
1765 ERR("wine_modref type %d not handled.\n",wm->type);
1766 SetLastError(ERROR_INVALID_HANDLE);
1767 return (FARPROC)0;
1772 /***********************************************************************
1773 * RtlImageNtHeaders (NTDLL)
1775 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
1777 /* basically:
1778 * return hModule+(((IMAGE_DOS_HEADER*)hModule)->e_lfanew);
1779 * but we could get HMODULE16 or the like (think builtin modules)
1782 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1783 if (!wm || (wm->type != MODULE32_PE)) return (PIMAGE_NT_HEADERS)0;
1784 return PE_HEADER(wm->module);
1788 /***************************************************************************
1789 * HasGPHandler (KERNEL.338)
1792 #include "pshpack1.h"
1793 typedef struct _GPHANDLERDEF
1795 WORD selector;
1796 WORD rangeStart;
1797 WORD rangeEnd;
1798 WORD handler;
1799 } GPHANDLERDEF;
1800 #include "poppack.h"
1802 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1804 HMODULE16 hModule;
1805 int gpOrdinal;
1806 SEGPTR gpPtr;
1807 GPHANDLERDEF *gpHandler;
1809 if ( (hModule = FarGetOwner16( SELECTOROF(address) )) != 0
1810 && (gpOrdinal = NE_GetOrdinal( hModule, "__GP" )) != 0
1811 && (gpPtr = (SEGPTR)NE_GetEntryPointEx( hModule, gpOrdinal, FALSE )) != 0
1812 && !IsBadReadPtr16( gpPtr, sizeof(GPHANDLERDEF) )
1813 && (gpHandler = PTR_SEG_TO_LIN( gpPtr )) != NULL )
1815 while (gpHandler->selector)
1817 if ( SELECTOROF(address) == gpHandler->selector
1818 && OFFSETOF(address) >= gpHandler->rangeStart
1819 && OFFSETOF(address) < gpHandler->rangeEnd )
1820 return PTR_SEG_OFF_TO_SEGPTR( gpHandler->selector,
1821 gpHandler->handler );
1822 gpHandler++;
1826 return 0;