Removed superfluous GlobalFindAtom calls.
[wine/multimedia.git] / loader / module.c
blob53ea615822b5ec001928ca9481b6d446ac6347fd
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 "thread.h"
29 #include "selectors.h"
30 #include "stackframe.h"
31 #include "task.h"
32 #include "debugtools.h"
33 #include "callback.h"
34 #include "loadorder.h"
35 #include "elfdll.h"
37 DEFAULT_DEBUG_CHANNEL(module)
38 DECLARE_DEBUG_CHANNEL(win32)
40 /*************************************************************************
41 * MODULE_WalkModref
42 * Walk MODREFs for input process ID
44 void MODULE_WalkModref( DWORD id )
46 int i;
47 WINE_MODREF *zwm, *prev = NULL;
48 PDB *pdb = PROCESS_IdToPDB( id );
50 if (!pdb) {
51 MESSAGE("Invalid process id (pid)\n");
52 return;
55 MESSAGE("Modref list for process pdb=%p\n", pdb);
56 MESSAGE("Modref next prev handle deps flags name\n");
57 for ( zwm = pdb->modref_list; zwm; zwm = zwm->next) {
58 MESSAGE("%p %p %p %04x %5d %04x %s\n", zwm, zwm->next, zwm->prev,
59 zwm->module, zwm->nDeps, zwm->flags, zwm->modname);
60 for ( i = 0; i < zwm->nDeps; i++ ) {
61 if ( zwm->deps[i] )
62 MESSAGE(" %d %p %s\n", i, zwm->deps[i], zwm->deps[i]->modname);
64 if (prev != zwm->prev)
65 MESSAGE(" --> modref corrupt, previous pointer wrong!!\n");
66 prev = zwm;
70 /*************************************************************************
71 * MODULE32_LookupHMODULE
72 * looks for the referenced HMODULE in the current process
74 WINE_MODREF *MODULE32_LookupHMODULE( HMODULE hmod )
76 WINE_MODREF *wm;
78 if (!hmod)
79 return PROCESS_Current()->exe_modref;
81 if (!HIWORD(hmod)) {
82 ERR("tried to lookup 0x%04x in win32 module handler!\n",hmod);
83 return NULL;
85 for ( wm = PROCESS_Current()->modref_list; wm; wm=wm->next )
86 if (wm->module == hmod)
87 return wm;
88 return NULL;
91 /*************************************************************************
92 * MODULE_InitDll
94 static BOOL MODULE_InitDll( WINE_MODREF *wm, DWORD type, LPVOID lpReserved )
96 BOOL retv = TRUE;
98 static LPCSTR typeName[] = { "PROCESS_DETACH", "PROCESS_ATTACH",
99 "THREAD_ATTACH", "THREAD_DETACH" };
100 assert( wm );
103 /* Skip calls for modules loaded with special load flags */
105 if ( ( wm->flags & WINE_MODREF_DONT_RESOLVE_REFS )
106 || ( wm->flags & WINE_MODREF_LOAD_AS_DATAFILE ) )
107 return TRUE;
110 TRACE("(%s,%s,%p) - CALL\n",
111 wm->modname, typeName[type], lpReserved );
113 /* Call the initialization routine */
114 switch ( wm->type )
116 case MODULE32_PE:
117 retv = PE_InitDLL( wm, type, lpReserved );
118 break;
120 case MODULE32_ELF:
121 /* no need to do that, dlopen() already does */
122 break;
124 default:
125 ERR("wine_modref type %d not handled.\n", wm->type );
126 retv = FALSE;
127 break;
130 TRACE("(%s,%s,%p) - RETURN %d\n",
131 wm->modname, typeName[type], lpReserved, retv );
133 return retv;
136 /*************************************************************************
137 * MODULE_DllProcessAttach
139 * Send the process attach notification to all DLLs the given module
140 * depends on (recursively). This is somewhat complicated due to the fact that
142 * - we have to respect the module dependencies, i.e. modules implicitly
143 * referenced by another module have to be initialized before the module
144 * itself can be initialized
146 * - the initialization routine of a DLL can itself call LoadLibrary,
147 * thereby introducing a whole new set of dependencies (even involving
148 * the 'old' modules) at any time during the whole process
150 * (Note that this routine can be recursively entered not only directly
151 * from itself, but also via LoadLibrary from one of the called initialization
152 * routines.)
154 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
155 * the process *detach* notifications to be sent in the correct order.
156 * This must not only take into account module dependencies, but also
157 * 'hidden' dependencies created by modules calling LoadLibrary in their
158 * attach notification routine.
160 * The strategy is rather simple: we move a WINE_MODREF to the head of the
161 * list after the attach notification has returned. This implies that the
162 * detach notifications are called in the reverse of the sequence the attach
163 * notifications *returned*.
165 * NOTE: Assumes that the process critical section is held!
168 BOOL MODULE_DllProcessAttach( WINE_MODREF *wm, LPVOID lpReserved )
170 BOOL retv = TRUE;
171 int i;
172 assert( wm );
174 /* prevent infinite recursion in case of cyclical dependencies */
175 if ( ( wm->flags & WINE_MODREF_MARKER )
176 || ( wm->flags & WINE_MODREF_PROCESS_ATTACHED ) )
177 return retv;
179 TRACE("(%s,%p) - START\n", wm->modname, lpReserved );
181 /* Tag current MODREF to prevent recursive loop */
182 wm->flags |= WINE_MODREF_MARKER;
184 /* Recursively attach all DLLs this one depends on */
185 for ( i = 0; retv && i < wm->nDeps; i++ )
186 if ( wm->deps[i] )
187 retv = MODULE_DllProcessAttach( wm->deps[i], lpReserved );
189 /* Call DLL entry point */
190 if ( retv )
192 retv = MODULE_InitDll( wm, DLL_PROCESS_ATTACH, lpReserved );
193 if ( retv )
194 wm->flags |= WINE_MODREF_PROCESS_ATTACHED;
197 /* Re-insert MODREF at head of list */
198 if ( retv && wm->prev )
200 wm->prev->next = wm->next;
201 if ( wm->next ) wm->next->prev = wm->prev;
203 wm->prev = NULL;
204 wm->next = PROCESS_Current()->modref_list;
205 PROCESS_Current()->modref_list = wm->next->prev = wm;
208 /* Remove recursion flag */
209 wm->flags &= ~WINE_MODREF_MARKER;
211 TRACE("(%s,%p) - END\n", wm->modname, lpReserved );
213 return retv;
216 /*************************************************************************
217 * MODULE_DllProcessDetach
219 * Send DLL process detach notifications. See the comment about calling
220 * sequence at MODULE_DllProcessAttach. Unless the bForceDetach flag
221 * is set, only DLLs with zero refcount are notified.
223 * NOTE: Assumes that the process critical section is held!
226 void MODULE_DllProcessDetach( BOOL bForceDetach, LPVOID lpReserved )
228 WINE_MODREF *wm;
232 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
234 /* Check whether to detach this DLL */
235 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
236 continue;
237 if ( wm->refCount > 0 && !bForceDetach )
238 continue;
240 /* Call detach notification */
241 wm->flags &= ~WINE_MODREF_PROCESS_ATTACHED;
242 MODULE_InitDll( wm, DLL_PROCESS_DETACH, lpReserved );
244 /* Restart at head of WINE_MODREF list, as entries might have
245 been added and/or removed while performing the call ... */
246 break;
248 } while ( wm );
251 /*************************************************************************
252 * MODULE_DllThreadAttach
254 * Send DLL thread attach notifications. These are sent in the
255 * reverse sequence of process detach notification.
258 void MODULE_DllThreadAttach( LPVOID lpReserved )
260 WINE_MODREF *wm;
262 EnterCriticalSection( &PROCESS_Current()->crit_section );
264 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
265 if ( !wm->next )
266 break;
268 for ( ; wm; wm = wm->prev )
270 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
271 continue;
272 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
273 continue;
275 MODULE_InitDll( wm, DLL_THREAD_ATTACH, lpReserved );
278 LeaveCriticalSection( &PROCESS_Current()->crit_section );
281 /*************************************************************************
282 * MODULE_DllThreadDetach
284 * Send DLL thread detach notifications. These are sent in the
285 * same sequence as process detach notification.
288 void MODULE_DllThreadDetach( LPVOID lpReserved )
290 WINE_MODREF *wm;
292 EnterCriticalSection( &PROCESS_Current()->crit_section );
294 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
296 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
297 continue;
298 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
299 continue;
301 MODULE_InitDll( wm, DLL_THREAD_DETACH, lpReserved );
304 LeaveCriticalSection( &PROCESS_Current()->crit_section );
307 /****************************************************************************
308 * DisableThreadLibraryCalls (KERNEL32.74)
310 * Don't call DllEntryPoint for DLL_THREAD_{ATTACH,DETACH} if set.
312 BOOL WINAPI DisableThreadLibraryCalls( HMODULE hModule )
314 WINE_MODREF *wm;
315 BOOL retval = TRUE;
317 EnterCriticalSection( &PROCESS_Current()->crit_section );
319 wm = MODULE32_LookupHMODULE( hModule );
320 if ( !wm )
321 retval = FALSE;
322 else
323 wm->flags |= WINE_MODREF_NO_DLL_CALLS;
325 LeaveCriticalSection( &PROCESS_Current()->crit_section );
327 return retval;
330 /*************************************************************************
331 * MODULE_SendLoadDLLEvents
333 * Sends DEBUG_DLL_LOAD events for all outstanding modules.
335 * NOTE: Assumes that the process critical section is held!
338 void MODULE_SendLoadDLLEvents( void )
340 WINE_MODREF *wm;
342 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
344 if ( wm->type != MODULE32_PE ) continue;
345 if ( wm == PROCESS_Current()->exe_modref ) continue;
346 if ( wm->flags & WINE_MODREF_DEBUG_EVENT_SENT ) continue;
348 DEBUG_SendLoadDLLEvent( -1 /*FIXME*/, wm->module, &wm->modname );
349 wm->flags |= WINE_MODREF_DEBUG_EVENT_SENT;
354 /***********************************************************************
355 * MODULE_CreateDummyModule
357 * Create a dummy NE module for Win32 or Winelib.
359 HMODULE MODULE_CreateDummyModule( LPCSTR filename, WORD version )
361 HMODULE hModule;
362 NE_MODULE *pModule;
363 SEGTABLEENTRY *pSegment;
364 char *pStr,*s;
365 unsigned int len;
366 const char* basename;
367 OFSTRUCT *ofs;
368 int of_size, size;
370 /* Extract base filename */
371 basename = strrchr(filename, '\\');
372 if (!basename) basename = filename;
373 else basename++;
374 len = strlen(basename);
375 if ((s = strchr(basename, '.'))) len = s - basename;
377 /* Allocate module */
378 of_size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName)
379 + strlen(filename) + 1;
380 size = sizeof(NE_MODULE) +
381 /* loaded file info */
382 of_size +
383 /* segment table: DS,CS */
384 2 * sizeof(SEGTABLEENTRY) +
385 /* name table */
386 len + 2 +
387 /* several empty tables */
390 hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
391 if (!hModule) return (HMODULE)11; /* invalid exe */
393 FarSetOwner16( hModule, hModule );
394 pModule = (NE_MODULE *)GlobalLock16( hModule );
396 /* Set all used entries */
397 pModule->magic = IMAGE_OS2_SIGNATURE;
398 pModule->count = 1;
399 pModule->next = 0;
400 pModule->flags = 0;
401 pModule->dgroup = 0;
402 pModule->ss = 1;
403 pModule->cs = 2;
404 pModule->heap_size = 0;
405 pModule->stack_size = 0;
406 pModule->seg_count = 2;
407 pModule->modref_count = 0;
408 pModule->nrname_size = 0;
409 pModule->fileinfo = sizeof(NE_MODULE);
410 pModule->os_flags = NE_OSFLAGS_WINDOWS;
411 pModule->expected_version = version;
412 pModule->self = hModule;
414 /* Set loaded file information */
415 ofs = (OFSTRUCT *)(pModule + 1);
416 memset( ofs, 0, of_size );
417 ofs->cBytes = of_size < 256 ? of_size : 255; /* FIXME */
418 strcpy( ofs->szPathName, filename );
420 pSegment = (SEGTABLEENTRY*)((char*)(pModule + 1) + of_size);
421 pModule->seg_table = (int)pSegment - (int)pModule;
422 /* Data segment */
423 pSegment->size = 0;
424 pSegment->flags = NE_SEGFLAGS_DATA;
425 pSegment->minsize = 0x1000;
426 pSegment++;
427 /* Code segment */
428 pSegment->flags = 0;
429 pSegment++;
431 /* Module name */
432 pStr = (char *)pSegment;
433 pModule->name_table = (int)pStr - (int)pModule;
434 assert(len<256);
435 *pStr = len;
436 lstrcpynA( pStr+1, basename, len+1 );
437 pStr += len+2;
439 /* All tables zero terminated */
440 pModule->res_table = pModule->import_table = pModule->entry_table =
441 (int)pStr - (int)pModule;
443 NE_RegisterModule( pModule );
444 return hModule;
448 /**********************************************************************
449 * MODULE_FindModule32
451 * Find a (loaded) win32 module depending on path
453 * RETURNS
454 * the module handle if found
455 * 0 if not
457 WINE_MODREF *MODULE_FindModule(
458 LPCSTR path /* [in] pathname of module/library to be found */
460 WINE_MODREF *wm;
461 char dllname[260], *p;
463 /* Append .DLL to name if no extension present */
464 strcpy( dllname, path );
465 if (!(p = strrchr( dllname, '.')) || strchr( p, '/' ) || strchr( p, '\\'))
466 strcat( dllname, ".DLL" );
468 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
470 if ( !strcasecmp( dllname, wm->modname ) )
471 break;
472 if ( !strcasecmp( dllname, wm->filename ) )
473 break;
474 if ( !strcasecmp( dllname, wm->short_modname ) )
475 break;
476 if ( !strcasecmp( dllname, wm->short_filename ) )
477 break;
480 return wm;
483 /***********************************************************************
484 * MODULE_GetBinaryType
486 * The GetBinaryType function determines whether a file is executable
487 * or not and if it is it returns what type of executable it is.
488 * The type of executable is a property that determines in which
489 * subsystem an executable file runs under.
491 * Binary types returned:
492 * SCS_32BIT_BINARY: A Win32 based application
493 * SCS_DOS_BINARY: An MS-Dos based application
494 * SCS_WOW_BINARY: A Win16 based application
495 * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
496 * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
497 * SCS_OS216_BINARY: A 16bit OS/2 based application
499 * Returns TRUE if the file is an executable in which case
500 * the value pointed by lpBinaryType is set.
501 * Returns FALSE if the file is not an executable or if the function fails.
503 * To do so it opens the file and reads in the header information
504 * if the extended header information is not present it will
505 * assume that the file is a DOS executable.
506 * If the extended header information is present it will
507 * determine if the file is a 16 or 32 bit Windows executable
508 * by check the flags in the header.
510 * Note that .COM and .PIF files are only recognized by their
511 * file name extension; but Windows does it the same way ...
513 static BOOL MODULE_GetBinaryType( HANDLE hfile, LPCSTR filename,
514 LPDWORD lpBinaryType )
516 IMAGE_DOS_HEADER mz_header;
517 char magic[4], *ptr;
518 DWORD len;
520 /* Seek to the start of the file and read the DOS header information.
522 if ( SetFilePointer( hfile, 0, NULL, SEEK_SET ) != -1
523 && ReadFile( hfile, &mz_header, sizeof(mz_header), &len, NULL )
524 && len == sizeof(mz_header) )
526 /* Now that we have the header check the e_magic field
527 * to see if this is a dos image.
529 if ( mz_header.e_magic == IMAGE_DOS_SIGNATURE )
531 BOOL lfanewValid = FALSE;
532 /* We do have a DOS image so we will now try to seek into
533 * the file by the amount indicated by the field
534 * "Offset to extended header" and read in the
535 * "magic" field information at that location.
536 * This will tell us if there is more header information
537 * to read or not.
539 /* But before we do we will make sure that header
540 * structure encompasses the "Offset to extended header"
541 * field.
543 if ( (mz_header.e_cparhdr<<4) >= sizeof(IMAGE_DOS_HEADER) )
544 if ( ( mz_header.e_crlc == 0 ) ||
545 ( mz_header.e_lfarlc >= sizeof(IMAGE_DOS_HEADER) ) )
546 if ( mz_header.e_lfanew >= sizeof(IMAGE_DOS_HEADER)
547 && SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET ) != -1
548 && ReadFile( hfile, magic, sizeof(magic), &len, NULL )
549 && len == sizeof(magic) )
550 lfanewValid = TRUE;
552 if ( !lfanewValid )
554 /* If we cannot read this "extended header" we will
555 * assume that we have a simple DOS executable.
557 *lpBinaryType = SCS_DOS_BINARY;
558 return TRUE;
560 else
562 /* Reading the magic field succeeded so
563 * we will try to determine what type it is.
565 if ( *(DWORD*)magic == IMAGE_NT_SIGNATURE )
567 /* This is an NT signature.
569 *lpBinaryType = SCS_32BIT_BINARY;
570 return TRUE;
572 else if ( *(WORD*)magic == IMAGE_OS2_SIGNATURE )
574 /* The IMAGE_OS2_SIGNATURE indicates that the
575 * "extended header is a Windows executable (NE)
576 * header." This can mean either a 16-bit OS/2
577 * or a 16-bit Windows or even a DOS program
578 * (running under a DOS extender). To decide
579 * which, we'll have to read the NE header.
582 IMAGE_OS2_HEADER ne;
583 if ( SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET ) != -1
584 && ReadFile( hfile, &ne, sizeof(ne), &len, NULL )
585 && len == sizeof(ne) )
587 switch ( ne.operating_system )
589 case 2: *lpBinaryType = SCS_WOW_BINARY; return TRUE;
590 case 5: *lpBinaryType = SCS_DOS_BINARY; return TRUE;
591 default: *lpBinaryType = SCS_OS216_BINARY; return TRUE;
594 /* Couldn't read header, so abort. */
595 return FALSE;
597 else
599 /* Unknown extended header, but this file is nonetheless
600 DOS-executable.
602 *lpBinaryType = SCS_DOS_BINARY;
603 return TRUE;
609 /* If we get here, we don't even have a correct MZ header.
610 * Try to check the file extension for known types ...
612 ptr = strrchr( filename, '.' );
613 if ( ptr && !strchr( ptr, '\\' ) && !strchr( ptr, '/' ) )
615 if ( !lstrcmpiA( ptr, ".COM" ) )
617 *lpBinaryType = SCS_DOS_BINARY;
618 return TRUE;
621 if ( !lstrcmpiA( ptr, ".PIF" ) )
623 *lpBinaryType = SCS_PIF_BINARY;
624 return TRUE;
628 return FALSE;
631 /***********************************************************************
632 * GetBinaryTypeA [KERNEL32.280]
634 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
636 BOOL ret = FALSE;
637 HANDLE hfile;
639 TRACE_(win32)("%s\n", lpApplicationName );
641 /* Sanity check.
643 if ( lpApplicationName == NULL || lpBinaryType == NULL )
644 return FALSE;
646 /* Open the file indicated by lpApplicationName for reading.
648 hfile = CreateFileA( lpApplicationName, GENERIC_READ, 0,
649 NULL, OPEN_EXISTING, 0, -1 );
650 if ( hfile == INVALID_HANDLE_VALUE )
651 return FALSE;
653 /* Check binary type
655 ret = MODULE_GetBinaryType( hfile, lpApplicationName, lpBinaryType );
657 /* Close the file.
659 CloseHandle( hfile );
661 return ret;
664 /***********************************************************************
665 * GetBinaryTypeW [KERNEL32.281]
667 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
669 BOOL ret = FALSE;
670 LPSTR strNew = NULL;
672 TRACE_(win32)("%s\n", debugstr_w(lpApplicationName) );
674 /* Sanity check.
676 if ( lpApplicationName == NULL || lpBinaryType == NULL )
677 return FALSE;
679 /* Convert the wide string to a ascii string.
681 strNew = HEAP_strdupWtoA( GetProcessHeap(), 0, lpApplicationName );
683 if ( strNew != NULL )
685 ret = GetBinaryTypeA( strNew, lpBinaryType );
687 /* Free the allocated string.
689 HeapFree( GetProcessHeap(), 0, strNew );
692 return ret;
695 /**********************************************************************
696 * MODULE_CreateUnixProcess
698 static BOOL MODULE_CreateUnixProcess( LPCSTR filename, LPCSTR lpCmdLine,
699 LPSTARTUPINFOA lpStartupInfo,
700 LPPROCESS_INFORMATION lpProcessInfo,
701 BOOL useWine )
703 DOS_FULL_NAME full_name;
704 const char *unixfilename = filename;
705 const char *argv[256], **argptr;
706 char *cmdline = NULL;
707 BOOL iconic = FALSE;
709 /* Get Unix file name and iconic flag */
711 if ( lpStartupInfo->dwFlags & STARTF_USESHOWWINDOW )
712 if ( lpStartupInfo->wShowWindow == SW_SHOWMINIMIZED
713 || lpStartupInfo->wShowWindow == SW_SHOWMINNOACTIVE )
714 iconic = TRUE;
716 /* Build argument list */
718 argptr = argv;
719 if ( !useWine )
721 char *p;
722 p = cmdline = strdup(lpCmdLine);
723 if (strchr(filename, '/') || strchr(filename, ':') || strchr(filename, '\\'))
725 if ( DOSFS_GetFullName( filename, TRUE, &full_name ) )
726 unixfilename = full_name.long_name;
728 *argptr++ = unixfilename;
729 if (iconic) *argptr++ = "-iconic";
730 while (1)
732 while (*p && (*p == ' ' || *p == '\t')) *p++ = '\0';
733 if (!*p) break;
734 *argptr++ = p;
735 while (*p && *p != ' ' && *p != '\t') p++;
738 else
740 *argptr++ = "wine";
741 if (iconic) *argptr++ = "-iconic";
742 *argptr++ = lpCmdLine;
744 *argptr++ = 0;
746 /* Fork and execute */
748 if ( !fork() )
750 /* Note: don't use Wine routines here, as this process
751 has not been correctly initialized! */
753 execvp( argv[0], (char**)argv );
755 /* Failed ! */
756 if ( useWine )
757 fprintf( stderr, "CreateProcess: can't exec 'wine %s'\n",
758 lpCmdLine );
759 exit( 1 );
762 /* Fake success return value */
764 memset( lpProcessInfo, '\0', sizeof( *lpProcessInfo ) );
765 lpProcessInfo->hProcess = INVALID_HANDLE_VALUE;
766 lpProcessInfo->hThread = INVALID_HANDLE_VALUE;
767 if (cmdline) free(cmdline);
769 SetLastError( ERROR_SUCCESS );
770 return TRUE;
773 /***********************************************************************
774 * WinExec16 (KERNEL.166)
776 HINSTANCE16 WINAPI WinExec16( LPCSTR lpCmdLine, UINT16 nCmdShow )
778 HINSTANCE16 hInst;
780 SYSLEVEL_ReleaseWin16Lock();
781 hInst = WinExec( lpCmdLine, nCmdShow );
782 SYSLEVEL_RestoreWin16Lock();
784 return hInst;
787 /***********************************************************************
788 * WinExec (KERNEL32.566)
790 HINSTANCE WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
792 LOADPARAMS params;
793 UINT16 paramCmdShow[2];
795 if (!lpCmdLine)
796 return 2; /* File not found */
798 /* Set up LOADPARAMS buffer for LoadModule */
800 memset( &params, '\0', sizeof(params) );
801 params.lpCmdLine = (LPSTR)lpCmdLine;
802 params.lpCmdShow = paramCmdShow;
803 params.lpCmdShow[0] = 2;
804 params.lpCmdShow[1] = nCmdShow;
806 /* Now load the executable file */
808 return LoadModule( NULL, &params );
811 /**********************************************************************
812 * LoadModule (KERNEL32.499)
814 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
816 LOADPARAMS *params = (LOADPARAMS *)paramBlock;
817 PROCESS_INFORMATION info;
818 STARTUPINFOA startup;
819 HINSTANCE hInstance;
820 PDB *pdb;
821 TDB *tdb;
823 memset( &startup, '\0', sizeof(startup) );
824 startup.cb = sizeof(startup);
825 startup.dwFlags = STARTF_USESHOWWINDOW;
826 startup.wShowWindow = params->lpCmdShow? params->lpCmdShow[1] : 0;
828 if ( !CreateProcessA( name, params->lpCmdLine,
829 NULL, NULL, FALSE, 0, params->lpEnvAddress,
830 NULL, &startup, &info ) )
832 hInstance = GetLastError();
833 if ( hInstance < 32 ) return hInstance;
835 FIXME("Strange error set by CreateProcess: %d\n", hInstance );
836 return 11;
839 /* Give 30 seconds to the app to come up */
840 if ( Callout.WaitForInputIdle ( info.hProcess, 30000 ) == 0xFFFFFFFF )
841 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
843 /* Get 16-bit hInstance/hTask from process */
844 pdb = PROCESS_IdToPDB( info.dwProcessId );
845 tdb = pdb? (TDB *)GlobalLock16( pdb->task ) : NULL;
846 hInstance = tdb && tdb->hInstance? tdb->hInstance : pdb? pdb->task : 0;
847 /* If there is no hInstance (32-bit process) return a dummy value
848 * that must be > 31
849 * FIXME: should do this in all cases and fix Win16 callers */
850 if (!hInstance) hInstance = 33;
852 /* Close off the handles */
853 CloseHandle( info.hThread );
854 CloseHandle( info.hProcess );
856 return hInstance;
859 /*************************************************************************
860 * get_makename_token
862 * Get next blank delimited token from input string. If quoted then
863 * process till matching quote and then till blank.
865 * Returns number of characters in token (not including \0). On
866 * end of string (EOS), returns a 0.
868 * from (IO) address of start of input string to scan, updated to
869 * next non-processed character.
870 * to (IO) address of start of output string (previous token \0
871 * char), updated to end of new output string (the \0
872 * char).
874 static int get_makename_token(LPCSTR *from, LPSTR *to )
876 int len = 0;
877 LPCSTR to_old = *to; /* only used for tracing */
879 while ( **from == ' ') {
880 /* Copy leading blanks (separators between previous */
881 /* token and this token). */
882 **to = **from;
883 (*from)++;
884 (*to)++;
885 len++;
887 do {
888 while ( (**from != 0) && (**from != ' ') && (**from != '"') ) {
889 **to = **from; (*from)++; (*to)++; len++;
891 if ( **from == '"' ) {
892 /* Handle quoted string. */
893 (*from)++;
894 if ( !strchr(*from, '"') ) {
895 /* fail - no closing quote. Return entire string */
896 while ( **from != 0 ) {
897 **to = **from; (*from)++; (*to)++; len++;
899 break;
901 while( **from != '"') {
902 **to = **from;
903 len++;
904 (*to)++;
905 (*from)++;
907 (*from)++;
908 continue;
911 /* either EOS or ' ' */
912 break;
914 } while (1);
916 **to = 0; /* terminate output string */
918 TRACE("returning token len=%d, string=%s\n", len, to_old);
920 return len;
923 /*************************************************************************
924 * make_lpCommandLine_name
926 * Try longer and longer strings from "line" to find an existing
927 * file name. Each attempt is delimited by a blank outside of quotes.
928 * Also will attempt to append ".exe" if requested and not already
929 * present. Returns the address of the remaining portion of the
930 * input line.
934 static BOOL make_lpCommandLine_name( LPCSTR line, LPSTR name, int namelen,
935 LPCSTR *after )
937 BOOL found = TRUE;
938 LPCSTR from;
939 char buffer[260];
940 DWORD retlen;
941 LPSTR to, lastpart;
943 from = line;
944 to = name;
946 /* scan over initial blanks if any */
947 while ( *from == ' ') from++;
949 /* get a token and append to previous data the check for existance */
950 do {
951 if ( !get_makename_token( &from, &to ) ) {
952 /* EOS has occured and not found - exit */
953 retlen = 0;
954 found = FALSE;
955 break;
957 TRACE("checking if file exists '%s'\n", name);
958 retlen = SearchPathA( NULL, name, ".exe", sizeof(buffer), buffer, &lastpart);
959 if ( retlen && (retlen < sizeof(buffer)) ) break;
960 } while (1);
962 /* if we have a non-null full path name in buffer then move to output */
963 if ( retlen ) {
964 if ( strlen(buffer) <= namelen ) {
965 strcpy( name, buffer );
966 } else {
967 /* not enough space to return full path string */
968 FIXME("internal string not long enough, need %d\n",
969 strlen(buffer) );
973 /* all done, indicate end of module name and then trace and exit */
974 if (after) *after = from;
975 TRACE("%i, selected file name '%s'\n and cmdline as %s\n",
976 found, name, debugstr_a(from));
977 return found;
980 /*************************************************************************
981 * make_lpApplicationName_name
983 * Scan input string (the lpApplicationName) and remove any quotes
984 * if they are balanced.
988 static BOOL make_lpApplicationName_name( LPCSTR line, LPSTR name, int namelen)
990 LPCSTR from;
991 LPSTR to, to_end, to_old;
992 char buffer[260];
994 to = buffer;
995 to_end = to + sizeof(buffer) - 1;
996 to_old = to;
998 while ( *line == ' ' ) line++; /* point to beginning of string */
999 from = line;
1000 do {
1001 /* Copy all input till end, or quote */
1002 while((*from != 0) && (*from != '"') && (to < to_end))
1003 *to++ = *from++;
1004 if (to >= to_end) { *to = 0; break; }
1006 if (*from == '"')
1008 /* Handle quoted string. If there is a closing quote, copy all */
1009 /* that is inside. */
1010 from++;
1011 if (!strchr(from, '"'))
1013 /* fail - no closing quote */
1014 to = to_old; /* restore to previous attempt */
1015 *to = 0; /* end string */
1016 break; /* exit with previous attempt */
1018 while((*from != '"') && (to < to_end)) *to++ = *from++;
1019 if (to >= to_end) { *to = 0; break; }
1020 from++;
1021 continue; /* past quoted string, so restart from top */
1024 *to = 0; /* terminate output string */
1025 to_old = to; /* save for possible use in unmatched quote case */
1027 /* loop around keeping the blank as part of file name */
1028 if (!*from)
1029 break; /* exit if out of input string */
1030 } while (1);
1032 if (!SearchPathA( NULL, buffer, ".exe", namelen, name, NULL )) {
1033 TRACE("file not found '%s'\n", buffer );
1034 return FALSE;
1037 TRACE("selected as file name '%s'\n", name );
1038 return TRUE;
1041 /**********************************************************************
1042 * CreateProcessA (KERNEL32.171)
1044 BOOL WINAPI CreateProcessA( LPCSTR lpApplicationName, LPSTR lpCommandLine,
1045 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1046 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1047 BOOL bInheritHandles, DWORD dwCreationFlags,
1048 LPVOID lpEnvironment, LPCSTR lpCurrentDirectory,
1049 LPSTARTUPINFOA lpStartupInfo,
1050 LPPROCESS_INFORMATION lpProcessInfo )
1052 BOOL retv = FALSE;
1053 BOOL found_file = FALSE;
1054 HANDLE hFile;
1055 DWORD type;
1056 char name[256], dummy[256];
1057 LPCSTR cmdline = NULL;
1058 LPSTR tidy_cmdline;
1060 /* Get name and command line */
1062 if (!lpApplicationName && !lpCommandLine)
1064 SetLastError( ERROR_FILE_NOT_FOUND );
1065 return FALSE;
1068 /* Process the AppName and/or CmdLine to get module name and path */
1070 name[0] = '\0';
1072 if (lpApplicationName)
1074 found_file = make_lpApplicationName_name( lpApplicationName, name, sizeof(name) );
1075 if (lpCommandLine)
1076 make_lpCommandLine_name( lpCommandLine, dummy, sizeof ( dummy ), &cmdline );
1077 else
1078 cmdline = lpApplicationName;
1080 else
1082 if (lpCommandLine)
1083 found_file = make_lpCommandLine_name( lpCommandLine, name, sizeof ( name ), &cmdline );
1086 if ( !found_file ) {
1087 /* make an early exit if file not found - save second pass */
1088 SetLastError( ERROR_FILE_NOT_FOUND );
1089 return FALSE;
1092 if (!cmdline) cmdline = "";
1093 tidy_cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(name) + strlen(cmdline) + 3 );
1094 TRACE_(module)("tidy_cmdline: name '%s'[%d], cmdline '%s'[%d]\n",
1095 name, strlen(name), cmdline, strlen(cmdline));
1096 sprintf( tidy_cmdline, "\"%s\"%s", name, cmdline);
1098 /* Warn if unsupported features are used */
1100 if (dwCreationFlags & DETACHED_PROCESS)
1101 FIXME("(%s,...): DETACHED_PROCESS ignored\n", name);
1102 if (dwCreationFlags & CREATE_NEW_CONSOLE)
1103 FIXME("(%s,...): CREATE_NEW_CONSOLE ignored\n", name);
1104 if (dwCreationFlags & NORMAL_PRIORITY_CLASS)
1105 FIXME("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
1106 if (dwCreationFlags & IDLE_PRIORITY_CLASS)
1107 FIXME("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
1108 if (dwCreationFlags & HIGH_PRIORITY_CLASS)
1109 FIXME("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
1110 if (dwCreationFlags & REALTIME_PRIORITY_CLASS)
1111 FIXME("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
1112 if (dwCreationFlags & CREATE_NEW_PROCESS_GROUP)
1113 FIXME("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
1114 if (dwCreationFlags & CREATE_UNICODE_ENVIRONMENT)
1115 FIXME("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
1116 if (dwCreationFlags & CREATE_SEPARATE_WOW_VDM)
1117 FIXME("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
1118 if (dwCreationFlags & CREATE_SHARED_WOW_VDM)
1119 FIXME("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
1120 if (dwCreationFlags & CREATE_DEFAULT_ERROR_MODE)
1121 FIXME("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
1122 if (dwCreationFlags & CREATE_NO_WINDOW)
1123 FIXME("(%s,...): CREATE_NO_WINDOW ignored\n", name);
1124 if (dwCreationFlags & PROFILE_USER)
1125 FIXME("(%s,...): PROFILE_USER ignored\n", name);
1126 if (dwCreationFlags & PROFILE_KERNEL)
1127 FIXME("(%s,...): PROFILE_KERNEL ignored\n", name);
1128 if (dwCreationFlags & PROFILE_SERVER)
1129 FIXME("(%s,...): PROFILE_SERVER ignored\n", name);
1130 if (lpCurrentDirectory)
1131 FIXME("(%s,...): lpCurrentDirectory %s ignored\n",
1132 name, lpCurrentDirectory);
1133 if (lpStartupInfo->lpDesktop)
1134 FIXME("(%s,...): lpStartupInfo->lpDesktop %s ignored\n",
1135 name, lpStartupInfo->lpDesktop);
1136 if (lpStartupInfo->lpTitle)
1137 FIXME("(%s,...): lpStartupInfo->lpTitle %s ignored\n",
1138 name, lpStartupInfo->lpTitle);
1139 if (lpStartupInfo->dwFlags & STARTF_USECOUNTCHARS)
1140 FIXME("(%s,...): STARTF_USECOUNTCHARS (%ld,%ld) ignored\n",
1141 name, lpStartupInfo->dwXCountChars, lpStartupInfo->dwYCountChars);
1142 if (lpStartupInfo->dwFlags & STARTF_USEFILLATTRIBUTE)
1143 FIXME("(%s,...): STARTF_USEFILLATTRIBUTE %lx ignored\n",
1144 name, lpStartupInfo->dwFillAttribute);
1145 if (lpStartupInfo->dwFlags & STARTF_RUNFULLSCREEN)
1146 FIXME("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
1147 if (lpStartupInfo->dwFlags & STARTF_FORCEONFEEDBACK)
1148 FIXME("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
1149 if (lpStartupInfo->dwFlags & STARTF_FORCEOFFFEEDBACK)
1150 FIXME("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
1151 if (lpStartupInfo->dwFlags & STARTF_USEHOTKEY)
1152 FIXME("(%s,...): STARTF_USEHOTKEY ignored\n", name);
1155 /* Load file and create process */
1157 if ( !retv )
1159 /* Open file and determine executable type */
1161 hFile = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ,
1162 NULL, OPEN_EXISTING, 0, -1 );
1163 if ( hFile == INVALID_HANDLE_VALUE )
1165 SetLastError( ERROR_FILE_NOT_FOUND );
1166 HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1167 return FALSE;
1170 if ( !MODULE_GetBinaryType( hFile, name, &type ) )
1172 CloseHandle( hFile );
1174 /* FIXME: Try Unix executable only when appropriate! */
1175 if ( MODULE_CreateUnixProcess( name, tidy_cmdline,
1176 lpStartupInfo, lpProcessInfo, FALSE ) )
1178 HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1179 return TRUE;
1181 HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1182 SetLastError( ERROR_BAD_FORMAT );
1183 return FALSE;
1187 /* Create process */
1189 switch ( type )
1191 case SCS_32BIT_BINARY:
1192 retv = PE_CreateProcess( hFile, name, tidy_cmdline, lpEnvironment,
1193 lpProcessAttributes, lpThreadAttributes,
1194 bInheritHandles, dwCreationFlags,
1195 lpStartupInfo, lpProcessInfo );
1196 break;
1198 case SCS_DOS_BINARY:
1199 retv = MZ_CreateProcess( hFile, name, tidy_cmdline, lpEnvironment,
1200 lpProcessAttributes, lpThreadAttributes,
1201 bInheritHandles, dwCreationFlags,
1202 lpStartupInfo, lpProcessInfo );
1203 break;
1205 case SCS_WOW_BINARY:
1206 retv = NE_CreateProcess( hFile, name, tidy_cmdline, lpEnvironment,
1207 lpProcessAttributes, lpThreadAttributes,
1208 bInheritHandles, dwCreationFlags,
1209 lpStartupInfo, lpProcessInfo );
1210 break;
1212 case SCS_PIF_BINARY:
1213 case SCS_POSIX_BINARY:
1214 case SCS_OS216_BINARY:
1215 FIXME("Unsupported executable type: %ld\n", type );
1216 /* fall through */
1218 default:
1219 SetLastError( ERROR_BAD_FORMAT );
1220 retv = FALSE;
1221 break;
1224 CloseHandle( hFile );
1226 HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1227 return retv;
1230 /**********************************************************************
1231 * CreateProcessW (KERNEL32.172)
1232 * NOTES
1233 * lpReserved is not converted
1235 BOOL WINAPI CreateProcessW( LPCWSTR lpApplicationName, LPWSTR lpCommandLine,
1236 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1237 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1238 BOOL bInheritHandles, DWORD dwCreationFlags,
1239 LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory,
1240 LPSTARTUPINFOW lpStartupInfo,
1241 LPPROCESS_INFORMATION lpProcessInfo )
1242 { BOOL ret;
1243 STARTUPINFOA StartupInfoA;
1245 LPSTR lpApplicationNameA = HEAP_strdupWtoA (GetProcessHeap(),0,lpApplicationName);
1246 LPSTR lpCommandLineA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCommandLine);
1247 LPSTR lpCurrentDirectoryA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCurrentDirectory);
1249 memcpy (&StartupInfoA, lpStartupInfo, sizeof(STARTUPINFOA));
1250 StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpDesktop);
1251 StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpTitle);
1253 TRACE_(win32)("(%s,%s,...)\n", debugstr_w(lpApplicationName), debugstr_w(lpCommandLine));
1255 if (lpStartupInfo->lpReserved)
1256 FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n", debugstr_w(lpStartupInfo->lpReserved));
1258 ret = CreateProcessA( lpApplicationNameA, lpCommandLineA,
1259 lpProcessAttributes, lpThreadAttributes,
1260 bInheritHandles, dwCreationFlags,
1261 lpEnvironment, lpCurrentDirectoryA,
1262 &StartupInfoA, lpProcessInfo );
1264 HeapFree( GetProcessHeap(), 0, lpCurrentDirectoryA );
1265 HeapFree( GetProcessHeap(), 0, lpCommandLineA );
1266 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1267 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1269 return ret;
1272 /***********************************************************************
1273 * GetModuleHandle (KERNEL32.237)
1275 HMODULE WINAPI GetModuleHandleA(LPCSTR module)
1277 WINE_MODREF *wm;
1279 if ( module == NULL )
1280 wm = PROCESS_Current()->exe_modref;
1281 else
1282 wm = MODULE_FindModule( module );
1284 return wm? wm->module : 0;
1287 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
1289 HMODULE hModule;
1290 LPSTR modulea = HEAP_strdupWtoA( GetProcessHeap(), 0, module );
1291 hModule = GetModuleHandleA( modulea );
1292 HeapFree( GetProcessHeap(), 0, modulea );
1293 return hModule;
1297 /***********************************************************************
1298 * GetModuleFileNameA (KERNEL32.235)
1300 DWORD WINAPI GetModuleFileNameA(
1301 HMODULE hModule, /* [in] module handle (32bit) */
1302 LPSTR lpFileName, /* [out] filenamebuffer */
1303 DWORD size /* [in] size of filenamebuffer */
1304 ) {
1305 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1307 if (!wm) /* can happen on start up or the like */
1308 return 0;
1310 if (PE_HEADER(wm->module)->OptionalHeader.MajorOperatingSystemVersion >= 4.0)
1311 lstrcpynA( lpFileName, wm->filename, size );
1312 else
1313 lstrcpynA( lpFileName, wm->short_filename, size );
1315 TRACE("%s\n", lpFileName );
1316 return strlen(lpFileName);
1320 /***********************************************************************
1321 * GetModuleFileName32W (KERNEL32.236)
1323 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName,
1324 DWORD size )
1326 LPSTR fnA = (char*)HeapAlloc( GetProcessHeap(), 0, size );
1327 DWORD res = GetModuleFileNameA( hModule, fnA, size );
1328 lstrcpynAtoW( lpFileName, fnA, size );
1329 HeapFree( GetProcessHeap(), 0, fnA );
1330 return res;
1334 /***********************************************************************
1335 * LoadLibraryExA (KERNEL32)
1337 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
1339 WINE_MODREF *wm;
1341 if(!libname)
1343 SetLastError(ERROR_INVALID_PARAMETER);
1344 return 0;
1347 EnterCriticalSection(&PROCESS_Current()->crit_section);
1349 wm = MODULE_LoadLibraryExA( libname, hfile, flags );
1350 if ( wm )
1352 if ( PROCESS_Current()->flags & PDB32_DEBUGGED )
1353 MODULE_SendLoadDLLEvents();
1355 if ( !MODULE_DllProcessAttach( wm, NULL ) )
1357 WARN_(module)("Attach failed for module '%s', \n", libname);
1358 MODULE_FreeLibrary(wm);
1359 SetLastError(ERROR_DLL_INIT_FAILED);
1360 wm = NULL;
1364 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1366 return wm ? wm->module : 0;
1369 /***********************************************************************
1370 * MODULE_LoadLibraryExA (internal)
1372 * Load a PE style module according to the load order.
1374 * The HFILE parameter is not used and marked reserved in the SDK. I can
1375 * only guess that it should force a file to be mapped, but I rather
1376 * ignore the parameter because it would be extremely difficult to
1377 * integrate this with different types of module represenations.
1380 WINE_MODREF *MODULE_LoadLibraryExA( LPCSTR libname, HFILE hfile, DWORD flags )
1382 DWORD err;
1383 WINE_MODREF *pwm;
1384 int i;
1385 module_loadorder_t *plo;
1387 EnterCriticalSection(&PROCESS_Current()->crit_section);
1389 /* Check for already loaded module */
1390 if((pwm = MODULE_FindModule(libname)))
1392 if(!(pwm->flags & WINE_MODREF_MARKER))
1393 pwm->refCount++;
1394 TRACE("Already loaded module '%s' at 0x%08x, count=%d, \n", libname, pwm->module, pwm->refCount);
1395 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1396 return pwm;
1399 plo = MODULE_GetLoadOrder(libname);
1401 for(i = 0; i < MODULE_LOADORDER_NTYPES; i++)
1403 switch(plo->loadorder[i])
1405 case MODULE_LOADORDER_DLL:
1406 TRACE("Trying native dll '%s'\n", libname);
1407 pwm = PE_LoadLibraryExA(libname, flags, &err);
1408 break;
1410 case MODULE_LOADORDER_ELFDLL:
1411 TRACE("Trying elfdll '%s'\n", libname);
1412 pwm = ELFDLL_LoadLibraryExA(libname, flags, &err);
1413 break;
1415 case MODULE_LOADORDER_SO:
1416 TRACE("Trying so-library '%s'\n", libname);
1417 pwm = ELF_LoadLibraryExA(libname, flags, &err);
1418 break;
1420 case MODULE_LOADORDER_BI:
1421 TRACE("Trying built-in '%s'\n", libname);
1422 pwm = BUILTIN32_LoadLibraryExA(libname, flags, &err);
1423 break;
1425 default:
1426 ERR("Got invalid loadorder type %d (%s index %d)\n", plo->loadorder[i], plo->modulename, i);
1427 /* Fall through */
1429 case MODULE_LOADORDER_INVALID: /* We ignore this as it is an empty entry */
1430 pwm = NULL;
1431 break;
1434 if(pwm)
1436 /* Initialize DLL just loaded */
1437 TRACE("Loaded module '%s' at 0x%08x, \n", libname, pwm->module);
1439 /* Set the refCount here so that an attach failure will */
1440 /* decrement the dependencies through the MODULE_FreeLibrary call. */
1441 pwm->refCount++;
1443 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1445 return pwm;
1448 if(err != ERROR_FILE_NOT_FOUND)
1449 break;
1452 WARN("Failed to load module '%s'; error=0x%08lx, \n", libname, err);
1453 SetLastError(err);
1454 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1455 return NULL;
1458 /***********************************************************************
1459 * LoadLibraryA (KERNEL32)
1461 HMODULE WINAPI LoadLibraryA(LPCSTR libname) {
1462 return LoadLibraryExA(libname,0,0);
1465 /***********************************************************************
1466 * LoadLibraryW (KERNEL32)
1468 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
1470 return LoadLibraryExW(libnameW,0,0);
1473 /***********************************************************************
1474 * LoadLibrary32_16 (KERNEL.452)
1476 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
1478 HMODULE hModule;
1480 SYSLEVEL_ReleaseWin16Lock();
1481 hModule = LoadLibraryA( libname );
1482 SYSLEVEL_RestoreWin16Lock();
1484 return hModule;
1487 /***********************************************************************
1488 * LoadLibraryExW (KERNEL32)
1490 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW,HANDLE hfile,DWORD flags)
1492 LPSTR libnameA = HEAP_strdupWtoA( GetProcessHeap(), 0, libnameW );
1493 HMODULE ret = LoadLibraryExA( libnameA , hfile, flags );
1495 HeapFree( GetProcessHeap(), 0, libnameA );
1496 return ret;
1499 /***********************************************************************
1500 * MODULE_FlushModrefs
1502 * NOTE: Assumes that the process critical section is held!
1504 * Remove all unused modrefs and call the internal unloading routines
1505 * for the library type.
1507 static void MODULE_FlushModrefs(void)
1509 WINE_MODREF *wm, *next;
1511 for(wm = PROCESS_Current()->modref_list; wm; wm = next)
1513 next = wm->next;
1515 if(wm->refCount)
1516 continue;
1518 /* Unlink this modref from the chain */
1519 if(wm->next)
1520 wm->next->prev = wm->prev;
1521 if(wm->prev)
1522 wm->prev->next = wm->next;
1523 if(wm == PROCESS_Current()->modref_list)
1524 PROCESS_Current()->modref_list = wm->next;
1527 * The unloaders are also responsible for freeing the modref itself
1528 * because the loaders were responsible for allocating it.
1530 switch(wm->type)
1532 case MODULE32_PE: PE_UnloadLibrary(wm); break;
1533 case MODULE32_ELF: ELF_UnloadLibrary(wm); break;
1534 case MODULE32_ELFDLL: ELFDLL_UnloadLibrary(wm); break;
1535 case MODULE32_BI: BUILTIN32_UnloadLibrary(wm); break;
1537 default:
1538 ERR("Invalid or unhandled MODREF type %d encountered (wm=%p)\n", wm->type, wm);
1543 /***********************************************************************
1544 * FreeLibrary
1546 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
1548 BOOL retv = FALSE;
1549 WINE_MODREF *wm;
1551 EnterCriticalSection( &PROCESS_Current()->crit_section );
1552 PROCESS_Current()->free_lib_count++;
1554 wm = MODULE32_LookupHMODULE( hLibModule );
1555 if ( !wm || !hLibModule )
1556 SetLastError( ERROR_INVALID_HANDLE );
1557 else
1558 retv = MODULE_FreeLibrary( wm );
1560 PROCESS_Current()->free_lib_count--;
1561 LeaveCriticalSection( &PROCESS_Current()->crit_section );
1563 return retv;
1566 /***********************************************************************
1567 * MODULE_DecRefCount
1569 * NOTE: Assumes that the process critical section is held!
1571 static void MODULE_DecRefCount( WINE_MODREF *wm )
1573 int i;
1575 if ( wm->flags & WINE_MODREF_MARKER )
1576 return;
1578 if ( wm->refCount <= 0 )
1579 return;
1581 --wm->refCount;
1582 TRACE("(%s) refCount: %d\n", wm->modname, wm->refCount );
1584 if ( wm->refCount == 0 )
1586 wm->flags |= WINE_MODREF_MARKER;
1588 for ( i = 0; i < wm->nDeps; i++ )
1589 if ( wm->deps[i] )
1590 MODULE_DecRefCount( wm->deps[i] );
1592 wm->flags &= ~WINE_MODREF_MARKER;
1596 /***********************************************************************
1597 * MODULE_FreeLibrary
1599 * NOTE: Assumes that the process critical section is held!
1601 BOOL MODULE_FreeLibrary( WINE_MODREF *wm )
1603 TRACE("(%s) - START\n", wm->modname );
1605 /* Recursively decrement reference counts */
1606 MODULE_DecRefCount( wm );
1608 /* Call process detach notifications */
1609 if ( PROCESS_Current()->free_lib_count <= 1 )
1611 MODULE_DllProcessDetach( FALSE, NULL );
1612 if (PROCESS_Current()->flags & PDB32_DEBUGGED)
1613 DEBUG_SendUnloadDLLEvent( wm->module );
1616 TRACE("(%s) - END\n", wm->modname );
1618 MODULE_FlushModrefs();
1620 return TRUE;
1624 /***********************************************************************
1625 * FreeLibraryAndExitThread
1627 VOID WINAPI FreeLibraryAndExitThread(HINSTANCE hLibModule, DWORD dwExitCode)
1629 FreeLibrary(hLibModule);
1630 ExitThread(dwExitCode);
1633 /***********************************************************************
1634 * PrivateLoadLibrary (KERNEL32)
1636 * FIXME: rough guesswork, don't know what "Private" means
1638 HINSTANCE WINAPI PrivateLoadLibrary(LPCSTR libname)
1640 return (HINSTANCE)LoadLibrary16(libname);
1645 /***********************************************************************
1646 * PrivateFreeLibrary (KERNEL32)
1648 * FIXME: rough guesswork, don't know what "Private" means
1650 void WINAPI PrivateFreeLibrary(HINSTANCE handle)
1652 FreeLibrary16((HINSTANCE16)handle);
1656 /***********************************************************************
1657 * WIN32_GetProcAddress16 (KERNEL32.36)
1658 * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
1660 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
1662 WORD ordinal;
1663 FARPROC16 ret;
1665 if (!hModule) {
1666 WARN("hModule may not be 0!\n");
1667 return (FARPROC16)0;
1669 if (HIWORD(hModule))
1671 WARN("hModule is Win32 handle (%08x)\n", hModule );
1672 return (FARPROC16)0;
1674 hModule = GetExePtr( hModule );
1675 if (HIWORD(name)) {
1676 ordinal = NE_GetOrdinal( hModule, name );
1677 TRACE("%04x '%s'\n", hModule, name );
1678 } else {
1679 ordinal = LOWORD(name);
1680 TRACE("%04x %04x\n", hModule, ordinal );
1682 if (!ordinal) return (FARPROC16)0;
1683 ret = NE_GetEntryPoint( hModule, ordinal );
1684 TRACE("returning %08x\n",(UINT)ret);
1685 return ret;
1688 /***********************************************************************
1689 * GetProcAddress16 (KERNEL.50)
1691 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, SEGPTR name )
1693 WORD ordinal;
1694 FARPROC16 ret;
1696 if (!hModule) hModule = GetCurrentTask();
1697 hModule = GetExePtr( hModule );
1699 if (HIWORD(name) != 0)
1701 ordinal = NE_GetOrdinal( hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1702 TRACE("%04x '%s'\n", hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1704 else
1706 ordinal = LOWORD(name);
1707 TRACE("%04x %04x\n", hModule, ordinal );
1709 if (!ordinal) return (FARPROC16)0;
1711 ret = NE_GetEntryPoint( hModule, ordinal );
1713 TRACE("returning %08x\n", (UINT)ret );
1714 return ret;
1718 /***********************************************************************
1719 * GetProcAddress32 (KERNEL32.257)
1721 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1723 return MODULE_GetProcAddress( hModule, function, TRUE );
1726 /***********************************************************************
1727 * WIN16_GetProcAddress32 (KERNEL.453)
1729 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
1731 return MODULE_GetProcAddress( hModule, function, FALSE );
1734 /***********************************************************************
1735 * MODULE_GetProcAddress32 (internal)
1737 FARPROC MODULE_GetProcAddress(
1738 HMODULE hModule, /* [in] current module handle */
1739 LPCSTR function, /* [in] function to be looked up */
1740 BOOL snoop )
1742 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1743 FARPROC retproc;
1745 if (HIWORD(function))
1746 TRACE_(win32)("(%08lx,%s)\n",(DWORD)hModule,function);
1747 else
1748 TRACE_(win32)("(%08lx,%p)\n",(DWORD)hModule,function);
1749 if (!wm) {
1750 SetLastError(ERROR_INVALID_HANDLE);
1751 return (FARPROC)0;
1753 switch (wm->type)
1755 case MODULE32_PE:
1756 retproc = PE_FindExportedFunction( wm, function, snoop );
1757 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1758 return retproc;
1759 case MODULE32_ELF:
1760 retproc = ELF_FindExportedFunction( wm, function);
1761 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1762 return retproc;
1763 default:
1764 ERR("wine_modref type %d not handled.\n",wm->type);
1765 SetLastError(ERROR_INVALID_HANDLE);
1766 return (FARPROC)0;
1771 /***********************************************************************
1772 * RtlImageNtHeaders (NTDLL)
1774 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
1776 /* basically:
1777 * return hModule+(((IMAGE_DOS_HEADER*)hModule)->e_lfanew);
1778 * but we could get HMODULE16 or the like (think builtin modules)
1781 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1782 if (!wm || (wm->type != MODULE32_PE)) return (PIMAGE_NT_HEADERS)0;
1783 return PE_HEADER(wm->module);
1787 /***************************************************************************
1788 * HasGPHandler (KERNEL.338)
1791 #include "pshpack1.h"
1792 typedef struct _GPHANDLERDEF
1794 WORD selector;
1795 WORD rangeStart;
1796 WORD rangeEnd;
1797 WORD handler;
1798 } GPHANDLERDEF;
1799 #include "poppack.h"
1801 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1803 HMODULE16 hModule;
1804 int gpOrdinal;
1805 SEGPTR gpPtr;
1806 GPHANDLERDEF *gpHandler;
1808 if ( (hModule = FarGetOwner16( SELECTOROF(address) )) != 0
1809 && (gpOrdinal = NE_GetOrdinal( hModule, "__GP" )) != 0
1810 && (gpPtr = (SEGPTR)NE_GetEntryPointEx( hModule, gpOrdinal, FALSE )) != 0
1811 && !IsBadReadPtr16( gpPtr, sizeof(GPHANDLERDEF) )
1812 && (gpHandler = PTR_SEG_TO_LIN( gpPtr )) != NULL )
1814 while (gpHandler->selector)
1816 if ( SELECTOROF(address) == gpHandler->selector
1817 && OFFSETOF(address) >= gpHandler->rangeStart
1818 && OFFSETOF(address) < gpHandler->rangeEnd )
1819 return PTR_SEG_OFF_TO_SEGPTR( gpHandler->selector,
1820 gpHandler->handler );
1821 gpHandler++;
1825 return 0;