Added missing (and now required) filename directive.
[wine.git] / loader / module.c
blob5508615369c3915bfff1ab3ca8c2b5bef8082162
1 /*
2 * Modules
4 * Copyright 1995 Alexandre Julliard
5 */
7 #include <assert.h>
8 #include <fcntl.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <sys/types.h>
12 #include <unistd.h>
13 #include "wine/winuser16.h"
14 #include "wine/winbase16.h"
15 #include "windef.h"
16 #include "winerror.h"
17 #include "file.h"
18 #include "global.h"
19 #include "heap.h"
20 #include "module.h"
21 #include "snoop.h"
22 #include "neexe.h"
23 #include "pe_image.h"
24 #include "dosexe.h"
25 #include "process.h"
26 #include "thread.h"
27 #include "selectors.h"
28 #include "stackframe.h"
29 #include "task.h"
30 #include "debugtools.h"
31 #include "callback.h"
32 #include "loadorder.h"
33 #include "elfdll.h"
35 DECLARE_DEBUG_CHANNEL(module)
36 DECLARE_DEBUG_CHANNEL(win32)
38 /*************************************************************************
39 * MODULE_WalkModref
40 * Walk MODREFs for input process ID
42 void MODULE_WalkModref( DWORD id )
44 int i;
45 WINE_MODREF *zwm, *prev = NULL;
46 PDB *pdb = PROCESS_IdToPDB( id );
48 if (!pdb) {
49 MESSAGE("Invalid process id (pid)\n");
50 return;
53 MESSAGE("Modref list for process pdb=%p\n", pdb);
54 MESSAGE("Modref next prev handle deps flags name\n");
55 for ( zwm = pdb->modref_list; zwm; zwm = zwm->next) {
56 MESSAGE("%p %p %p %04x %5d %04x %s\n", zwm, zwm->next, zwm->prev,
57 zwm->module, zwm->nDeps, zwm->flags, zwm->modname);
58 for ( i = 0; i < zwm->nDeps; i++ ) {
59 if ( zwm->deps[i] )
60 MESSAGE(" %d %p %s\n", i, zwm->deps[i], zwm->deps[i]->modname);
62 if (prev != zwm->prev)
63 MESSAGE(" --> modref corrupt, previous pointer wrong!!\n");
64 prev = zwm;
68 /*************************************************************************
69 * MODULE32_LookupHMODULE
70 * looks for the referenced HMODULE in the current process
72 WINE_MODREF *MODULE32_LookupHMODULE( HMODULE hmod )
74 WINE_MODREF *wm;
76 if (!hmod)
77 return PROCESS_Current()->exe_modref;
79 if (!HIWORD(hmod)) {
80 ERR_(module)("tried to lookup 0x%04x in win32 module handler!\n",hmod);
81 return NULL;
83 for ( wm = PROCESS_Current()->modref_list; wm; wm=wm->next )
84 if (wm->module == hmod)
85 return wm;
86 return NULL;
89 /*************************************************************************
90 * MODULE_InitDll
92 static BOOL MODULE_InitDll( WINE_MODREF *wm, DWORD type, LPVOID lpReserved )
94 BOOL retv = TRUE;
96 static LPCSTR typeName[] = { "PROCESS_DETACH", "PROCESS_ATTACH",
97 "THREAD_ATTACH", "THREAD_DETACH" };
98 assert( wm );
101 /* Skip calls for modules loaded with special load flags */
103 if ( ( wm->flags & WINE_MODREF_DONT_RESOLVE_REFS )
104 || ( wm->flags & WINE_MODREF_LOAD_AS_DATAFILE ) )
105 return TRUE;
108 TRACE_(module)("(%s,%s,%p) - CALL\n",
109 wm->modname, typeName[type], lpReserved );
111 /* Call the initialization routine */
112 switch ( wm->type )
114 case MODULE32_PE:
115 retv = PE_InitDLL( wm, type, lpReserved );
116 break;
118 case MODULE32_ELF:
119 /* no need to do that, dlopen() already does */
120 break;
122 default:
123 ERR_(module)("wine_modref type %d not handled.\n", wm->type );
124 retv = FALSE;
125 break;
128 TRACE_(module)("(%s,%s,%p) - RETURN %d\n",
129 wm->modname, typeName[type], lpReserved, retv );
131 return retv;
134 /*************************************************************************
135 * MODULE_DllProcessAttach
137 * Send the process attach notification to all DLLs the given module
138 * depends on (recursively). This is somewhat complicated due to the fact that
140 * - we have to respect the module dependencies, i.e. modules implicitly
141 * referenced by another module have to be initialized before the module
142 * itself can be initialized
144 * - the initialization routine of a DLL can itself call LoadLibrary,
145 * thereby introducing a whole new set of dependencies (even involving
146 * the 'old' modules) at any time during the whole process
148 * (Note that this routine can be recursively entered not only directly
149 * from itself, but also via LoadLibrary from one of the called initialization
150 * routines.)
152 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
153 * the process *detach* notifications to be sent in the correct order.
154 * This must not only take into account module dependencies, but also
155 * 'hidden' dependencies created by modules calling LoadLibrary in their
156 * attach notification routine.
158 * The strategy is rather simple: we move a WINE_MODREF to the head of the
159 * list after the attach notification has returned. This implies that the
160 * detach notifications are called in the reverse of the sequence the attach
161 * notifications *returned*.
163 * NOTE: Assumes that the process critical section is held!
166 BOOL MODULE_DllProcessAttach( WINE_MODREF *wm, LPVOID lpReserved )
168 BOOL retv = TRUE;
169 int i;
170 assert( wm );
172 /* prevent infinite recursion in case of cyclical dependencies */
173 if ( ( wm->flags & WINE_MODREF_MARKER )
174 || ( wm->flags & WINE_MODREF_PROCESS_ATTACHED ) )
175 return retv;
177 TRACE_(module)("(%s,%p) - START\n",
178 wm->modname, lpReserved );
180 /* Tag current MODREF to prevent recursive loop */
181 wm->flags |= WINE_MODREF_MARKER;
183 /* Recursively attach all DLLs this one depends on */
184 for ( i = 0; retv && i < wm->nDeps; i++ )
185 if ( wm->deps[i] )
186 retv = MODULE_DllProcessAttach( wm->deps[i], lpReserved );
188 /* Call DLL entry point */
189 if ( retv )
191 retv = MODULE_InitDll( wm, DLL_PROCESS_ATTACH, lpReserved );
192 if ( retv )
193 wm->flags |= WINE_MODREF_PROCESS_ATTACHED;
196 /* Re-insert MODREF at head of list */
197 if ( retv && wm->prev )
199 wm->prev->next = wm->next;
200 if ( wm->next ) wm->next->prev = wm->prev;
202 wm->prev = NULL;
203 wm->next = PROCESS_Current()->modref_list;
204 PROCESS_Current()->modref_list = wm->next->prev = wm;
207 /* Remove recursion flag */
208 wm->flags &= ~WINE_MODREF_MARKER;
210 TRACE_(module)("(%s,%p) - END\n",
211 wm->modname, lpReserved );
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;
331 /***********************************************************************
332 * MODULE_CreateDummyModule
334 * Create a dummy NE module for Win32 or Winelib.
336 HMODULE MODULE_CreateDummyModule( const OFSTRUCT *ofs, LPCSTR modName )
338 HMODULE hModule;
339 NE_MODULE *pModule;
340 SEGTABLEENTRY *pSegment;
341 char *pStr,*s;
342 int len;
343 const char* basename;
345 INT of_size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName)
346 + strlen(ofs->szPathName) + 1;
347 INT size = sizeof(NE_MODULE) +
348 /* loaded file info */
349 of_size +
350 /* segment table: DS,CS */
351 2 * sizeof(SEGTABLEENTRY) +
352 /* name table */
354 /* several empty tables */
357 hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
358 if (!hModule) return (HMODULE)11; /* invalid exe */
360 FarSetOwner16( hModule, hModule );
361 pModule = (NE_MODULE *)GlobalLock16( hModule );
363 /* Set all used entries */
364 pModule->magic = IMAGE_OS2_SIGNATURE;
365 pModule->count = 1;
366 pModule->next = 0;
367 pModule->flags = 0;
368 pModule->dgroup = 0;
369 pModule->ss = 1;
370 pModule->cs = 2;
371 pModule->heap_size = 0;
372 pModule->stack_size = 0;
373 pModule->seg_count = 2;
374 pModule->modref_count = 0;
375 pModule->nrname_size = 0;
376 pModule->fileinfo = sizeof(NE_MODULE);
377 pModule->os_flags = NE_OSFLAGS_WINDOWS;
378 pModule->expected_version = 0x030a;
379 pModule->self = hModule;
381 /* Set loaded file information */
382 memcpy( pModule + 1, ofs, of_size );
383 ((OFSTRUCT *)(pModule+1))->cBytes = of_size - 1;
385 pSegment = (SEGTABLEENTRY*)((char*)(pModule + 1) + of_size);
386 pModule->seg_table = (int)pSegment - (int)pModule;
387 /* Data segment */
388 pSegment->size = 0;
389 pSegment->flags = NE_SEGFLAGS_DATA;
390 pSegment->minsize = 0x1000;
391 pSegment++;
392 /* Code segment */
393 pSegment->flags = 0;
394 pSegment++;
396 /* Module name */
397 pStr = (char *)pSegment;
398 pModule->name_table = (int)pStr - (int)pModule;
399 if ( modName )
400 basename = modName;
401 else
403 basename = strrchr(ofs->szPathName,'\\');
404 if (!basename) basename = ofs->szPathName;
405 else basename++;
407 len = strlen(basename);
408 if ((s = strchr(basename,'.'))) len = s - basename;
409 if (len > 8) len = 8;
410 *pStr = len;
411 strncpy( pStr+1, basename, len );
412 if (len < 8) pStr[len+1] = 0;
413 pStr += 9;
415 /* All tables zero terminated */
416 pModule->res_table = pModule->import_table = pModule->entry_table =
417 (int)pStr - (int)pModule;
419 NE_RegisterModule( pModule );
420 return hModule;
424 /**********************************************************************
425 * MODULE_FindModule32
427 * Find a (loaded) win32 module depending on path
428 * The handling of '.' is a bit weird, but we need it that way,
429 * for sometimes the programs use '<name>.exe' and '<name>.dll' and
430 * this is the only way to differentiate. (mainly hypertrm.exe)
432 * RETURNS
433 * the module handle if found
434 * 0 if not
436 WINE_MODREF *MODULE_FindModule(
437 LPCSTR path /* [in] pathname of module/library to be found */
439 LPSTR filename;
440 LPSTR dotptr;
441 WINE_MODREF *wm;
443 if (!(filename = strrchr( path, '\\' )))
444 filename = HEAP_strdupA( GetProcessHeap(), 0, path );
445 else
446 filename = HEAP_strdupA( GetProcessHeap(), 0, filename+1 );
447 dotptr=strrchr(filename,'.');
449 for ( wm = PROCESS_Current()->modref_list; wm; wm=wm->next ) {
450 LPSTR xmodname,xdotptr;
452 assert (wm->modname);
453 xmodname = HEAP_strdupA( GetProcessHeap(), 0, wm->modname );
454 xdotptr=strrchr(xmodname,'.');
455 if ( (xdotptr && !dotptr) ||
456 (!xdotptr && dotptr)
458 if (dotptr) *dotptr = '\0';
459 if (xdotptr) *xdotptr = '\0';
461 if (!strcasecmp( filename, xmodname)) {
462 HeapFree( GetProcessHeap(), 0, filename );
463 HeapFree( GetProcessHeap(), 0, xmodname );
464 return wm;
466 if (dotptr) *dotptr='.';
467 /* FIXME: add paths, shortname */
468 HeapFree( GetProcessHeap(), 0, xmodname );
470 /* if that fails, try looking for the filename... */
471 for ( wm = PROCESS_Current()->modref_list; wm; wm=wm->next ) {
472 LPSTR xlname,xdotptr;
474 assert (wm->longname);
475 xlname = strrchr(wm->longname,'\\');
476 if (!xlname)
477 xlname = wm->longname;
478 else
479 xlname++;
480 xlname = HEAP_strdupA( GetProcessHeap(), 0, xlname );
481 xdotptr=strrchr(xlname,'.');
482 if ( (xdotptr && !dotptr) ||
483 (!xdotptr && dotptr)
485 if (dotptr) *dotptr = '\0';
486 if (xdotptr) *xdotptr = '\0';
488 if (!strcasecmp( filename, xlname)) {
489 HeapFree( GetProcessHeap(), 0, filename );
490 HeapFree( GetProcessHeap(), 0, xlname );
491 return wm;
493 if (dotptr) *dotptr='.';
494 /* FIXME: add paths, shortname */
495 HeapFree( GetProcessHeap(), 0, xlname );
497 HeapFree( GetProcessHeap(), 0, filename );
498 return NULL;
501 /***********************************************************************
502 * MODULE_GetBinaryType
504 * The GetBinaryType function determines whether a file is executable
505 * or not and if it is it returns what type of executable it is.
506 * The type of executable is a property that determines in which
507 * subsystem an executable file runs under.
509 * Binary types returned:
510 * SCS_32BIT_BINARY: A Win32 based application
511 * SCS_DOS_BINARY: An MS-Dos based application
512 * SCS_WOW_BINARY: A Win16 based application
513 * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
514 * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
515 * SCS_OS216_BINARY: A 16bit OS/2 based application
517 * Returns TRUE if the file is an executable in which case
518 * the value pointed by lpBinaryType is set.
519 * Returns FALSE if the file is not an executable or if the function fails.
521 * To do so it opens the file and reads in the header information
522 * if the extended header information is not presend it will
523 * assume that that the file is a DOS executable.
524 * If the extended header information is present it will
525 * determine if the file is an 16 or 32 bit Windows executable
526 * by check the flags in the header.
528 * Note that .COM and .PIF files are only recognized by their
529 * file name extension; but Windows does it the same way ...
531 static BOOL MODULE_GetBinaryType( HFILE hfile, OFSTRUCT *ofs,
532 LPDWORD lpBinaryType )
534 IMAGE_DOS_HEADER mz_header;
535 char magic[4], *ptr;
537 /* Seek to the start of the file and read the DOS header information.
539 if ( _llseek( hfile, 0, SEEK_SET ) >= 0 &&
540 _lread( hfile, &mz_header, sizeof(mz_header) ) == sizeof(mz_header) )
542 /* Now that we have the header check the e_magic field
543 * to see if this is a dos image.
545 if ( mz_header.e_magic == IMAGE_DOS_SIGNATURE )
547 BOOL lfanewValid = FALSE;
548 /* We do have a DOS image so we will now try to seek into
549 * the file by the amount indicated by the field
550 * "Offset to extended header" and read in the
551 * "magic" field information at that location.
552 * This will tell us if there is more header information
553 * to read or not.
555 /* But before we do we will make sure that header
556 * structure encompasses the "Offset to extended header"
557 * field.
559 if ( (mz_header.e_cparhdr<<4) >= sizeof(IMAGE_DOS_HEADER) )
560 if ( ( mz_header.e_crlc == 0 ) ||
561 ( mz_header.e_lfarlc >= sizeof(IMAGE_DOS_HEADER) ) )
562 if ( mz_header.e_lfanew >= sizeof(IMAGE_DOS_HEADER) &&
563 _llseek( hfile, mz_header.e_lfanew, SEEK_SET ) >= 0 &&
564 _lread( hfile, magic, sizeof(magic) ) == sizeof(magic) )
565 lfanewValid = TRUE;
567 if ( !lfanewValid )
569 /* If we cannot read this "extended header" we will
570 * assume that we have a simple DOS executable.
572 *lpBinaryType = SCS_DOS_BINARY;
573 return TRUE;
575 else
577 /* Reading the magic field succeeded so
578 * we will try to determine what type it is.
580 if ( *(DWORD*)magic == IMAGE_NT_SIGNATURE )
582 /* This is an NT signature.
584 *lpBinaryType = SCS_32BIT_BINARY;
585 return TRUE;
587 else if ( *(WORD*)magic == IMAGE_OS2_SIGNATURE )
589 /* The IMAGE_OS2_SIGNATURE indicates that the
590 * "extended header is a Windows executable (NE)
591 * header." This can mean either a 16-bit OS/2
592 * or a 16-bit Windows or even a DOS program
593 * (running under a DOS extender). To decide
594 * which, we'll have to read the NE header.
597 IMAGE_OS2_HEADER ne;
598 if ( _llseek( hfile, mz_header.e_lfanew, SEEK_SET ) >= 0 &&
599 _lread( hfile, &ne, sizeof(ne) ) == sizeof(ne) )
601 switch ( ne.operating_system )
603 case 2: *lpBinaryType = SCS_WOW_BINARY; return TRUE;
604 case 5: *lpBinaryType = SCS_DOS_BINARY; return TRUE;
605 default: *lpBinaryType = SCS_OS216_BINARY; return TRUE;
608 /* Couldn't read header, so abort. */
609 return FALSE;
611 else
613 /* Unknown extended header, so abort.
615 return FALSE;
621 /* If we get here, we don't even have a correct MZ header.
622 * Try to check the file extension for known types ...
624 ptr = strrchr( ofs->szPathName, '.' );
625 if ( ptr && !strchr( ptr, '\\' ) && !strchr( ptr, '/' ) )
627 if ( !lstrcmpiA( ptr, ".COM" ) )
629 *lpBinaryType = SCS_DOS_BINARY;
630 return TRUE;
633 if ( !lstrcmpiA( ptr, ".PIF" ) )
635 *lpBinaryType = SCS_PIF_BINARY;
636 return TRUE;
640 return FALSE;
643 /***********************************************************************
644 * GetBinaryTypeA [KERNEL32.280]
646 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
648 BOOL ret = FALSE;
649 HFILE hfile;
650 OFSTRUCT ofs;
652 TRACE_(win32)("%s\n", lpApplicationName );
654 /* Sanity check.
656 if ( lpApplicationName == NULL || lpBinaryType == NULL )
657 return FALSE;
659 /* Open the file indicated by lpApplicationName for reading.
661 if ( (hfile = OpenFile( lpApplicationName, &ofs, OF_READ )) == HFILE_ERROR )
662 return FALSE;
664 /* Check binary type
666 ret = MODULE_GetBinaryType( hfile, &ofs, lpBinaryType );
668 /* Close the file.
670 CloseHandle( hfile );
672 return ret;
675 /***********************************************************************
676 * GetBinaryTypeW [KERNEL32.281]
678 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
680 BOOL ret = FALSE;
681 LPSTR strNew = NULL;
683 TRACE_(win32)("%s\n", debugstr_w(lpApplicationName) );
685 /* Sanity check.
687 if ( lpApplicationName == NULL || lpBinaryType == NULL )
688 return FALSE;
690 /* Convert the wide string to a ascii string.
692 strNew = HEAP_strdupWtoA( GetProcessHeap(), 0, lpApplicationName );
694 if ( strNew != NULL )
696 ret = GetBinaryTypeA( strNew, lpBinaryType );
698 /* Free the allocated string.
700 HeapFree( GetProcessHeap(), 0, strNew );
703 return ret;
706 /**********************************************************************
707 * MODULE_CreateUnixProcess
709 static BOOL MODULE_CreateUnixProcess( LPCSTR filename, LPCSTR lpCmdLine,
710 LPSTARTUPINFOA lpStartupInfo,
711 LPPROCESS_INFORMATION lpProcessInfo,
712 BOOL useWine )
714 DOS_FULL_NAME full_name;
715 const char *unixfilename = filename;
716 const char *argv[256], **argptr;
717 char *cmdline = NULL;
718 BOOL iconic = FALSE;
720 /* Get Unix file name and iconic flag */
722 if ( lpStartupInfo->dwFlags & STARTF_USESHOWWINDOW )
723 if ( lpStartupInfo->wShowWindow == SW_SHOWMINIMIZED
724 || lpStartupInfo->wShowWindow == SW_SHOWMINNOACTIVE )
725 iconic = TRUE;
727 /* Build argument list */
729 argptr = argv;
730 if ( !useWine )
732 char *p;
733 p = cmdline = strdup(lpCmdLine);
734 if (strchr(filename, '/') || strchr(filename, ':') || strchr(filename, '\\'))
736 if ( DOSFS_GetFullName( filename, TRUE, &full_name ) )
737 unixfilename = full_name.long_name;
739 *argptr++ = unixfilename;
740 if (iconic) *argptr++ = "-iconic";
741 while (1)
743 while (*p && (*p == ' ' || *p == '\t')) *p++ = '\0';
744 if (!*p) break;
745 *argptr++ = p;
746 while (*p && *p != ' ' && *p != '\t') p++;
749 else
751 *argptr++ = "wine";
752 if (iconic) *argptr++ = "-iconic";
753 *argptr++ = lpCmdLine;
755 *argptr++ = 0;
757 /* Fork and execute */
759 if ( !fork() )
761 /* Note: don't use Wine routines here, as this process
762 has not been correctly initialized! */
764 execvp( argv[0], (char**)argv );
766 /* Failed ! */
767 if ( useWine )
768 fprintf( stderr, "CreateProcess: can't exec 'wine %s'\n",
769 lpCmdLine );
770 exit( 1 );
773 /* Fake success return value */
775 memset( lpProcessInfo, '\0', sizeof( *lpProcessInfo ) );
776 lpProcessInfo->hProcess = INVALID_HANDLE_VALUE;
777 lpProcessInfo->hThread = INVALID_HANDLE_VALUE;
778 if (cmdline) free(cmdline);
780 SetLastError( ERROR_SUCCESS );
781 return TRUE;
784 /***********************************************************************
785 * WinExec16 (KERNEL.166)
787 HINSTANCE16 WINAPI WinExec16( LPCSTR lpCmdLine, UINT16 nCmdShow )
789 HINSTANCE16 hInst;
791 SYSLEVEL_ReleaseWin16Lock();
792 hInst = WinExec( lpCmdLine, nCmdShow );
793 SYSLEVEL_RestoreWin16Lock();
795 return hInst;
798 /***********************************************************************
799 * WinExec (KERNEL32.566)
801 HINSTANCE WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
803 LOADPARAMS params;
804 UINT16 paramCmdShow[2];
806 if (!lpCmdLine)
807 return 2; /* File not found */
809 /* Set up LOADPARAMS buffer for LoadModule */
811 memset( &params, '\0', sizeof(params) );
812 params.lpCmdLine = (LPSTR)lpCmdLine;
813 params.lpCmdShow = paramCmdShow;
814 params.lpCmdShow[0] = 2;
815 params.lpCmdShow[1] = nCmdShow;
817 /* Now load the executable file */
819 return LoadModule( NULL, &params );
822 /**********************************************************************
823 * LoadModule (KERNEL32.499)
825 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
827 LOADPARAMS *params = (LOADPARAMS *)paramBlock;
828 PROCESS_INFORMATION info;
829 STARTUPINFOA startup;
830 HINSTANCE hInstance;
831 PDB *pdb;
832 TDB *tdb;
834 memset( &startup, '\0', sizeof(startup) );
835 startup.cb = sizeof(startup);
836 startup.dwFlags = STARTF_USESHOWWINDOW;
837 startup.wShowWindow = params->lpCmdShow? params->lpCmdShow[1] : 0;
839 if ( !CreateProcessA( name, params->lpCmdLine,
840 NULL, NULL, FALSE, 0, params->lpEnvAddress,
841 NULL, &startup, &info ) )
843 hInstance = GetLastError();
844 if ( hInstance < 32 ) return hInstance;
846 FIXME_(module)("Strange error set by CreateProcess: %d\n", hInstance );
847 return 11;
850 /* Get 16-bit hInstance/hTask from process */
851 pdb = PROCESS_IdToPDB( info.dwProcessId );
852 tdb = pdb? (TDB *)GlobalLock16( pdb->task ) : NULL;
853 hInstance = tdb && tdb->hInstance? tdb->hInstance : pdb? pdb->task : 0;
854 /* If there is no hInstance (32-bit process) return a dummy value
855 * that must be > 31
856 * FIXME: should do this in all cases and fix Win16 callers */
857 if (!hInstance) hInstance = 33;
859 /* Close off the handles */
860 CloseHandle( info.hThread );
861 CloseHandle( info.hProcess );
863 return hInstance;
866 /*************************************************************************
867 * get_makename_token
869 * Get next blank delimited token from input string. If quoted then
870 * process till matching quote and then till blank.
872 * Returns number of characters in token (not including \0). On
873 * end of string (EOS), returns a 0.
875 * from (IO) address of start of input string to scan, updated to
876 * next non-processed character.
877 * to (IO) address of start of output string (previous token \0
878 * char), updated to end of new output string (the \0
879 * char).
881 static int get_makename_token(LPCSTR *from, LPSTR *to )
883 int len = 0;
884 LPCSTR to_old = *to; /* only used for tracing */
886 while ( **from == ' ') {
887 /* Copy leading blanks (separators between previous */
888 /* token and this token). */
889 **to = **from;
890 (*from)++;
891 (*to)++;
892 len++;
894 do {
895 while ( (**from != 0) && (**from != ' ') && (**from != '"') ) {
896 **to = **from; (*from)++; (*to)++; len++;
898 if ( **from == '"' ) {
899 /* Handle quoted string. */
900 (*from)++;
901 if ( !strchr(*from, '"') ) {
902 /* fail - no closing quote. Return entire string */
903 while ( **from != 0 ) {
904 **to = **from; (*from)++; (*to)++; len++;
906 break;
908 while( **from != '"') {
909 **to = **from;
910 len++;
911 (*to)++;
912 (*from)++;
914 (*from)++;
915 continue;
918 /* either EOS or ' ' */
919 break;
921 } while (1);
923 **to = 0; /* terminate output string */
925 TRACE_(module)("returning token len=%d, string=%s\n",
926 len, to_old);
928 return len;
931 /*************************************************************************
932 * make_lpCommandLine_name
934 * Try longer and longer strings from "line" to find an existing
935 * file name. Each attempt is delimited by a blank outside of quotes.
936 * Also will attempt to append ".exe" if requested and not already
937 * present. Returns the address of the remaining portion of the
938 * input line.
942 static BOOL make_lpCommandLine_name( LPCSTR line, LPSTR name, int namelen,
943 LPCSTR *after )
945 BOOL found = TRUE;
946 LPCSTR from;
947 char buffer[260];
948 DWORD retlen;
949 LPSTR to, lastpart;
951 from = line;
952 to = name;
954 /* scan over initial blanks if any */
955 while ( *from == ' ') from++;
957 /* get a token and append to previous data the check for existance */
958 do {
959 if ( !get_makename_token( &from, &to ) ) {
960 /* EOS has occured and not found - exit */
961 retlen = 0;
962 found = FALSE;
963 break;
965 TRACE_(module)("checking if file exists '%s'\n", name);
966 retlen = SearchPathA( NULL, name, ".exe", sizeof(buffer), buffer, &lastpart);
967 if ( retlen && (retlen < sizeof(buffer)) ) break;
968 } while (1);
970 /* if we have a non-null full path name in buffer then move to output */
971 if ( retlen ) {
972 if ( strlen(buffer) <= namelen ) {
973 strcpy( name, buffer );
974 } else {
975 /* not enough space to return full path string */
976 FIXME_(module)("internal string not long enough, need %d\n",
977 strlen(buffer) );
981 /* all done, indicate end of module name and then trace and exit */
982 if (after) *after = from;
983 TRACE_(module)("%i, selected file name '%s'\n and cmdline as %s\n",
984 found, name, debugstr_a(from));
985 return found;
988 /*************************************************************************
989 * make_lpApplicationName_name
991 * Scan input string (the lpApplicationName) and remove any quotes
992 * if they are balanced.
996 static BOOL make_lpApplicationName_name( LPCSTR line, LPSTR name, int namelen)
998 LPCSTR from;
999 LPSTR to, to_end, to_old;
1000 DOS_FULL_NAME full_name;
1002 to = name;
1003 to_end = to + namelen - 1;
1004 to_old = to;
1006 while ( *line == ' ' ) line++; /* point to beginning of string */
1007 from = line;
1008 do {
1009 /* Copy all input till end, or quote */
1010 while((*from != 0) && (*from != '"') && (to < to_end))
1011 *to++ = *from++;
1012 if (to >= to_end) { *to = 0; break; }
1014 if (*from == '"')
1016 /* Handle quoted string. If there is a closing quote, copy all */
1017 /* that is inside. */
1018 from++;
1019 if (!strchr(from, '"'))
1021 /* fail - no closing quote */
1022 to = to_old; /* restore to previous attempt */
1023 *to = 0; /* end string */
1024 break; /* exit with previous attempt */
1026 while((*from != '"') && (to < to_end)) *to++ = *from++;
1027 if (to >= to_end) { *to = 0; break; }
1028 from++;
1029 continue; /* past quoted string, so restart from top */
1032 *to = 0; /* terminate output string */
1033 to_old = to; /* save for possible use in unmatched quote case */
1035 /* loop around keeping the blank as part of file name */
1036 if (!*from)
1037 break; /* exit if out of input string */
1038 } while (1);
1040 if (!DOSFS_GetFullName(name, TRUE, &full_name)) {
1041 TRACE_(module)("file not found '%s'\n", name );
1042 return FALSE;
1045 if (strlen(full_name.long_name) >= namelen ) {
1046 FIXME_(module)("name longer than buffer (len=%d), file=%s\n",
1047 namelen, full_name.long_name);
1048 return FALSE;
1050 strcpy(name, full_name.long_name);
1052 TRACE_(module)("selected as file name '%s'\n", name );
1053 return TRUE;
1056 /**********************************************************************
1057 * CreateProcessA (KERNEL32.171)
1059 BOOL WINAPI CreateProcessA( LPCSTR lpApplicationName, LPSTR lpCommandLine,
1060 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1061 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1062 BOOL bInheritHandles, DWORD dwCreationFlags,
1063 LPVOID lpEnvironment, LPCSTR lpCurrentDirectory,
1064 LPSTARTUPINFOA lpStartupInfo,
1065 LPPROCESS_INFORMATION lpProcessInfo )
1067 BOOL retv = FALSE;
1068 BOOL found_file = FALSE;
1069 HFILE hFile;
1070 OFSTRUCT ofs;
1071 DWORD type;
1072 char name[256], dummy[256];
1073 LPCSTR cmdline = NULL;
1074 LPSTR tidy_cmdline;
1075 int len = 0;
1077 /* Get name and command line */
1079 if (!lpApplicationName && !lpCommandLine)
1081 SetLastError( ERROR_FILE_NOT_FOUND );
1082 return FALSE;
1085 /* Process the AppName and/or CmdLine to get module name and path */
1087 name[0] = '\0';
1089 if (lpApplicationName) {
1090 found_file = make_lpApplicationName_name( lpApplicationName, name, sizeof(name) );
1091 if (lpCommandLine) {
1092 make_lpCommandLine_name( lpCommandLine, dummy, sizeof ( dummy ), &cmdline );
1094 else {
1095 cmdline = lpApplicationName;
1097 len += strlen(lpApplicationName);
1099 else {
1100 found_file = make_lpCommandLine_name( lpCommandLine, name, sizeof ( name ), &cmdline );
1101 if (lpCommandLine) len = strlen(lpCommandLine);
1104 if ( !found_file ) {
1105 /* make an early exit if file not found - save second pass */
1106 SetLastError( ERROR_FILE_NOT_FOUND );
1107 return FALSE;
1110 len += strlen(name) + 2;
1111 tidy_cmdline = HeapAlloc( GetProcessHeap(), 0, len );
1112 sprintf( tidy_cmdline, "\"%s\"%s", name, cmdline);
1114 /* Warn if unsupported features are used */
1116 if (dwCreationFlags & CREATE_SUSPENDED)
1117 FIXME_(module)("(%s,...): CREATE_SUSPENDED ignored\n", name);
1118 if (dwCreationFlags & DETACHED_PROCESS)
1119 FIXME_(module)("(%s,...): DETACHED_PROCESS ignored\n", name);
1120 if (dwCreationFlags & CREATE_NEW_CONSOLE)
1121 FIXME_(module)("(%s,...): CREATE_NEW_CONSOLE ignored\n", name);
1122 if (dwCreationFlags & NORMAL_PRIORITY_CLASS)
1123 FIXME_(module)("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
1124 if (dwCreationFlags & IDLE_PRIORITY_CLASS)
1125 FIXME_(module)("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
1126 if (dwCreationFlags & HIGH_PRIORITY_CLASS)
1127 FIXME_(module)("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
1128 if (dwCreationFlags & REALTIME_PRIORITY_CLASS)
1129 FIXME_(module)("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
1130 if (dwCreationFlags & CREATE_NEW_PROCESS_GROUP)
1131 FIXME_(module)("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
1132 if (dwCreationFlags & CREATE_UNICODE_ENVIRONMENT)
1133 FIXME_(module)("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
1134 if (dwCreationFlags & CREATE_SEPARATE_WOW_VDM)
1135 FIXME_(module)("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
1136 if (dwCreationFlags & CREATE_SHARED_WOW_VDM)
1137 FIXME_(module)("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
1138 if (dwCreationFlags & CREATE_DEFAULT_ERROR_MODE)
1139 FIXME_(module)("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
1140 if (dwCreationFlags & CREATE_NO_WINDOW)
1141 FIXME_(module)("(%s,...): CREATE_NO_WINDOW ignored\n", name);
1142 if (dwCreationFlags & PROFILE_USER)
1143 FIXME_(module)("(%s,...): PROFILE_USER ignored\n", name);
1144 if (dwCreationFlags & PROFILE_KERNEL)
1145 FIXME_(module)("(%s,...): PROFILE_KERNEL ignored\n", name);
1146 if (dwCreationFlags & PROFILE_SERVER)
1147 FIXME_(module)("(%s,...): PROFILE_SERVER ignored\n", name);
1148 if (lpCurrentDirectory)
1149 FIXME_(module)("(%s,...): lpCurrentDirectory %s ignored\n",
1150 name, lpCurrentDirectory);
1151 if (lpStartupInfo->lpDesktop)
1152 FIXME_(module)("(%s,...): lpStartupInfo->lpDesktop %s ignored\n",
1153 name, lpStartupInfo->lpDesktop);
1154 if (lpStartupInfo->lpTitle)
1155 FIXME_(module)("(%s,...): lpStartupInfo->lpTitle %s ignored\n",
1156 name, lpStartupInfo->lpTitle);
1157 if (lpStartupInfo->dwFlags & STARTF_USECOUNTCHARS)
1158 FIXME_(module)("(%s,...): STARTF_USECOUNTCHARS (%ld,%ld) ignored\n",
1159 name, lpStartupInfo->dwXCountChars, lpStartupInfo->dwYCountChars);
1160 if (lpStartupInfo->dwFlags & STARTF_USEFILLATTRIBUTE)
1161 FIXME_(module)("(%s,...): STARTF_USEFILLATTRIBUTE %lx ignored\n",
1162 name, lpStartupInfo->dwFillAttribute);
1163 if (lpStartupInfo->dwFlags & STARTF_RUNFULLSCREEN)
1164 FIXME_(module)("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
1165 if (lpStartupInfo->dwFlags & STARTF_FORCEONFEEDBACK)
1166 FIXME_(module)("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
1167 if (lpStartupInfo->dwFlags & STARTF_FORCEOFFFEEDBACK)
1168 FIXME_(module)("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
1169 if (lpStartupInfo->dwFlags & STARTF_USEHOTKEY)
1170 FIXME_(module)("(%s,...): STARTF_USEHOTKEY ignored\n", name);
1172 /* Check for special case: second instance of NE module */
1174 lstrcpynA( ofs.szPathName, name, sizeof( ofs.szPathName ) );
1175 retv = NE_CreateProcess( HFILE_ERROR, &ofs, tidy_cmdline, lpEnvironment,
1176 lpProcessAttributes, lpThreadAttributes,
1177 bInheritHandles, dwCreationFlags,
1178 lpStartupInfo, lpProcessInfo );
1180 /* Load file and create process */
1182 if ( !retv )
1184 /* Open file and determine executable type */
1186 if ( (hFile = OpenFile( name, &ofs, OF_READ )) == HFILE_ERROR )
1188 SetLastError( ERROR_FILE_NOT_FOUND );
1189 HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1190 return FALSE;
1193 if ( !MODULE_GetBinaryType( hFile, &ofs, &type ) )
1195 CloseHandle( hFile );
1197 /* FIXME: Try Unix executable only when appropriate! */
1198 if ( MODULE_CreateUnixProcess( name, tidy_cmdline,
1199 lpStartupInfo, lpProcessInfo, FALSE ) )
1201 HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1202 return TRUE;
1204 HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1205 SetLastError( ERROR_BAD_FORMAT );
1206 return FALSE;
1210 /* Create process */
1212 switch ( type )
1214 case SCS_32BIT_BINARY:
1215 retv = PE_CreateProcess( hFile, &ofs, tidy_cmdline, lpEnvironment,
1216 lpProcessAttributes, lpThreadAttributes,
1217 bInheritHandles, dwCreationFlags,
1218 lpStartupInfo, lpProcessInfo );
1219 break;
1221 case SCS_DOS_BINARY:
1222 retv = MZ_CreateProcess( hFile, &ofs, tidy_cmdline, lpEnvironment,
1223 lpProcessAttributes, lpThreadAttributes,
1224 bInheritHandles, dwCreationFlags,
1225 lpStartupInfo, lpProcessInfo );
1226 break;
1228 case SCS_WOW_BINARY:
1229 retv = NE_CreateProcess( hFile, &ofs, tidy_cmdline, lpEnvironment,
1230 lpProcessAttributes, lpThreadAttributes,
1231 bInheritHandles, dwCreationFlags,
1232 lpStartupInfo, lpProcessInfo );
1233 break;
1235 case SCS_PIF_BINARY:
1236 case SCS_POSIX_BINARY:
1237 case SCS_OS216_BINARY:
1238 FIXME_(module)("Unsupported executable type: %ld\n", type );
1239 /* fall through */
1241 default:
1242 SetLastError( ERROR_BAD_FORMAT );
1243 retv = FALSE;
1244 break;
1247 CloseHandle( hFile );
1249 HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1250 return retv;
1253 /**********************************************************************
1254 * CreateProcessW (KERNEL32.172)
1255 * NOTES
1256 * lpReserved is not converted
1258 BOOL WINAPI CreateProcessW( LPCWSTR lpApplicationName, LPWSTR lpCommandLine,
1259 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1260 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1261 BOOL bInheritHandles, DWORD dwCreationFlags,
1262 LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory,
1263 LPSTARTUPINFOW lpStartupInfo,
1264 LPPROCESS_INFORMATION lpProcessInfo )
1265 { BOOL ret;
1266 STARTUPINFOA StartupInfoA;
1268 LPSTR lpApplicationNameA = HEAP_strdupWtoA (GetProcessHeap(),0,lpApplicationName);
1269 LPSTR lpCommandLineA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCommandLine);
1270 LPSTR lpCurrentDirectoryA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCurrentDirectory);
1272 memcpy (&StartupInfoA, lpStartupInfo, sizeof(STARTUPINFOA));
1273 StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpDesktop);
1274 StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpTitle);
1276 TRACE_(win32)("(%s,%s,...)\n", debugstr_w(lpApplicationName), debugstr_w(lpCommandLine));
1278 if (lpStartupInfo->lpReserved)
1279 FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n", debugstr_w(lpStartupInfo->lpReserved));
1281 ret = CreateProcessA( lpApplicationNameA, lpCommandLineA,
1282 lpProcessAttributes, lpThreadAttributes,
1283 bInheritHandles, dwCreationFlags,
1284 lpEnvironment, lpCurrentDirectoryA,
1285 &StartupInfoA, lpProcessInfo );
1287 HeapFree( GetProcessHeap(), 0, lpCurrentDirectoryA );
1288 HeapFree( GetProcessHeap(), 0, lpCommandLineA );
1289 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1290 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1292 return ret;
1295 /***********************************************************************
1296 * GetModuleHandle (KERNEL32.237)
1298 HMODULE WINAPI GetModuleHandleA(LPCSTR module)
1300 WINE_MODREF *wm;
1302 if ( module == NULL )
1303 wm = PROCESS_Current()->exe_modref;
1304 else
1305 wm = MODULE_FindModule( module );
1307 return wm? wm->module : 0;
1310 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
1312 HMODULE hModule;
1313 LPSTR modulea = HEAP_strdupWtoA( GetProcessHeap(), 0, module );
1314 hModule = GetModuleHandleA( modulea );
1315 HeapFree( GetProcessHeap(), 0, modulea );
1316 return hModule;
1320 /***********************************************************************
1321 * GetModuleFileName32A (KERNEL32.235)
1323 DWORD WINAPI GetModuleFileNameA(
1324 HMODULE hModule, /* [in] module handle (32bit) */
1325 LPSTR lpFileName, /* [out] filenamebuffer */
1326 DWORD size /* [in] size of filenamebuffer */
1327 ) {
1328 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1330 if (!wm) /* can happen on start up or the like */
1331 return 0;
1333 if (PE_HEADER(wm->module)->OptionalHeader.MajorOperatingSystemVersion >= 4.0)
1334 lstrcpynA( lpFileName, wm->longname, size );
1335 else
1336 lstrcpynA( lpFileName, wm->shortname, size );
1338 TRACE_(module)("%s\n", lpFileName );
1339 return strlen(lpFileName);
1343 /***********************************************************************
1344 * GetModuleFileName32W (KERNEL32.236)
1346 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName,
1347 DWORD size )
1349 LPSTR fnA = (char*)HeapAlloc( GetProcessHeap(), 0, size );
1350 DWORD res = GetModuleFileNameA( hModule, fnA, size );
1351 lstrcpynAtoW( lpFileName, fnA, size );
1352 HeapFree( GetProcessHeap(), 0, fnA );
1353 return res;
1357 /***********************************************************************
1358 * LoadLibraryExA (KERNEL32)
1360 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HFILE hfile, DWORD flags)
1362 WINE_MODREF *wm;
1364 if(!libname)
1366 SetLastError(ERROR_INVALID_PARAMETER);
1367 return 0;
1370 EnterCriticalSection(&PROCESS_Current()->crit_section);
1372 wm = MODULE_LoadLibraryExA( libname, hfile, flags );
1374 if(wm && !MODULE_DllProcessAttach(wm, NULL))
1376 WARN_(module)("Attach failed for module '%s', \n", libname);
1377 MODULE_FreeLibrary(wm);
1378 SetLastError(ERROR_DLL_INIT_FAILED);
1379 wm = NULL;
1382 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1384 return wm ? wm->module : 0;
1387 /***********************************************************************
1388 * MODULE_LoadLibraryExA (internal)
1390 * Load a PE style module according to the load order.
1392 * The HFILE parameter is not used and marked reserved in the SDK. I can
1393 * only guess that it should force a file to be mapped, but I rather
1394 * ignore the parameter because it would be extremely difficult to
1395 * integrate this with different types of module represenations.
1398 WINE_MODREF *MODULE_LoadLibraryExA( LPCSTR libname, HFILE hfile, DWORD flags )
1400 DWORD err;
1401 WINE_MODREF *pwm;
1402 int i;
1403 module_loadorder_t *plo;
1405 EnterCriticalSection(&PROCESS_Current()->crit_section);
1407 /* Check for already loaded module */
1408 if((pwm = MODULE_FindModule(libname)))
1410 if(!(pwm->flags & WINE_MODREF_MARKER))
1411 pwm->refCount++;
1412 TRACE_(module)("Already loaded module '%s' at 0x%08x, count=%d, \n", libname, pwm->module, pwm->refCount);
1413 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1414 return pwm;
1417 plo = MODULE_GetLoadOrder(libname);
1419 for(i = 0; i < MODULE_LOADORDER_NTYPES; i++)
1421 switch(plo->loadorder[i])
1423 case MODULE_LOADORDER_DLL:
1424 TRACE_(module)("Trying native dll '%s'\n", libname);
1425 pwm = PE_LoadLibraryExA(libname, flags, &err);
1426 break;
1428 case MODULE_LOADORDER_ELFDLL:
1429 TRACE_(module)("Trying elfdll '%s'\n", libname);
1430 pwm = ELFDLL_LoadLibraryExA(libname, flags, &err);
1431 break;
1433 case MODULE_LOADORDER_SO:
1434 TRACE_(module)("Trying so-library '%s'\n", libname);
1435 pwm = ELF_LoadLibraryExA(libname, flags, &err);
1436 break;
1438 case MODULE_LOADORDER_BI:
1439 TRACE_(module)("Trying built-in '%s'\n", libname);
1440 pwm = BUILTIN32_LoadLibraryExA(libname, flags, &err);
1441 break;
1443 default:
1444 ERR_(module)("Got invalid loadorder type %d (%s index %d)\n", plo->loadorder[i], plo->modulename, i);
1445 /* Fall through */
1447 case MODULE_LOADORDER_INVALID: /* We ignore this as it is an empty entry */
1448 pwm = NULL;
1449 break;
1452 if(pwm)
1454 /* Initialize DLL just loaded */
1455 TRACE_(module)("Loaded module '%s' at 0x%08x, \n", libname, pwm->module);
1457 /* Set the refCount here so that an attach failure will */
1458 /* decrement the dependencies through the MODULE_FreeLibrary call. */
1459 pwm->refCount++;
1461 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1463 if (PROCESS_Current()->flags & PDB32_DEBUGGED)
1464 DEBUG_SendLoadDLLEvent( -1 /*FIXME*/, pwm->module, pwm->modname );
1466 return pwm;
1469 if(err != ERROR_FILE_NOT_FOUND)
1470 break;
1473 ERR_(module)("Failed to load module '%s'; error=0x%08lx, \n", libname, err);
1474 SetLastError(err);
1475 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1476 return NULL;
1479 /***********************************************************************
1480 * LoadLibraryA (KERNEL32)
1482 HMODULE WINAPI LoadLibraryA(LPCSTR libname) {
1483 return LoadLibraryExA(libname,0,0);
1486 /***********************************************************************
1487 * LoadLibraryW (KERNEL32)
1489 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
1491 return LoadLibraryExW(libnameW,0,0);
1494 /***********************************************************************
1495 * LoadLibrary32_16 (KERNEL.452)
1497 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
1499 HMODULE hModule;
1501 SYSLEVEL_ReleaseWin16Lock();
1502 hModule = LoadLibraryA( libname );
1503 SYSLEVEL_RestoreWin16Lock();
1505 return hModule;
1508 /***********************************************************************
1509 * LoadLibraryExW (KERNEL32)
1511 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW,HFILE hfile,DWORD flags)
1513 LPSTR libnameA = HEAP_strdupWtoA( GetProcessHeap(), 0, libnameW );
1514 HMODULE ret = LoadLibraryExA( libnameA , hfile, flags );
1516 HeapFree( GetProcessHeap(), 0, libnameA );
1517 return ret;
1520 /***********************************************************************
1521 * MODULE_FlushModrefs
1523 * NOTE: Assumes that the process critical section is held!
1525 * Remove all unused modrefs and call the internal unloading routines
1526 * for the library type.
1528 static void MODULE_FlushModrefs(void)
1530 WINE_MODREF *wm, *next;
1532 for(wm = PROCESS_Current()->modref_list; wm; wm = next)
1534 next = wm->next;
1536 if(wm->refCount)
1537 continue;
1539 /* Unlink this modref from the chain */
1540 if(wm->next)
1541 wm->next->prev = wm->prev;
1542 if(wm->prev)
1543 wm->prev->next = wm->next;
1544 if(wm == PROCESS_Current()->modref_list)
1545 PROCESS_Current()->modref_list = wm->next;
1548 * The unloaders are also responsible for freeing the modref itself
1549 * because the loaders were responsible for allocating it.
1551 switch(wm->type)
1553 case MODULE32_PE: PE_UnloadLibrary(wm); break;
1554 case MODULE32_ELF: ELF_UnloadLibrary(wm); break;
1555 case MODULE32_ELFDLL: ELFDLL_UnloadLibrary(wm); break;
1556 case MODULE32_BI: BUILTIN32_UnloadLibrary(wm); break;
1558 default:
1559 ERR_(module)("Invalid or unhandled MODREF type %d encountered (wm=%p)\n", wm->type, wm);
1564 /***********************************************************************
1565 * FreeLibrary
1567 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
1569 BOOL retv = FALSE;
1570 WINE_MODREF *wm;
1572 EnterCriticalSection( &PROCESS_Current()->crit_section );
1573 PROCESS_Current()->free_lib_count++;
1575 wm = MODULE32_LookupHMODULE( hLibModule );
1576 if ( !wm || !hLibModule )
1577 SetLastError( ERROR_INVALID_HANDLE );
1578 else
1579 retv = MODULE_FreeLibrary( wm );
1581 PROCESS_Current()->free_lib_count--;
1582 LeaveCriticalSection( &PROCESS_Current()->crit_section );
1584 return retv;
1587 /***********************************************************************
1588 * MODULE_DecRefCount
1590 * NOTE: Assumes that the process critical section is held!
1592 static void MODULE_DecRefCount( WINE_MODREF *wm )
1594 int i;
1596 if ( wm->flags & WINE_MODREF_MARKER )
1597 return;
1599 if ( wm->refCount <= 0 )
1600 return;
1602 --wm->refCount;
1603 TRACE_(module)("(%s) refCount: %d\n", wm->modname, wm->refCount );
1605 if ( wm->refCount == 0 )
1607 wm->flags |= WINE_MODREF_MARKER;
1609 for ( i = 0; i < wm->nDeps; i++ )
1610 if ( wm->deps[i] )
1611 MODULE_DecRefCount( wm->deps[i] );
1613 wm->flags &= ~WINE_MODREF_MARKER;
1617 /***********************************************************************
1618 * MODULE_FreeLibrary
1620 * NOTE: Assumes that the process critical section is held!
1622 BOOL MODULE_FreeLibrary( WINE_MODREF *wm )
1624 TRACE_(module)("(%s) - START\n", wm->modname );
1626 /* Recursively decrement reference counts */
1627 MODULE_DecRefCount( wm );
1629 /* Call process detach notifications */
1630 if ( PROCESS_Current()->free_lib_count <= 1 )
1632 MODULE_DllProcessDetach( FALSE, NULL );
1633 if (PROCESS_Current()->flags & PDB32_DEBUGGED)
1634 DEBUG_SendUnloadDLLEvent( wm->module );
1637 MODULE_FlushModrefs();
1639 TRACE_(module)("(%s) - END\n", wm->modname );
1641 return TRUE;
1645 /***********************************************************************
1646 * FreeLibraryAndExitThread
1648 VOID WINAPI FreeLibraryAndExitThread(HINSTANCE hLibModule, DWORD dwExitCode)
1650 FreeLibrary(hLibModule);
1651 ExitThread(dwExitCode);
1654 /***********************************************************************
1655 * PrivateLoadLibrary (KERNEL32)
1657 * FIXME: rough guesswork, don't know what "Private" means
1659 HINSTANCE WINAPI PrivateLoadLibrary(LPCSTR libname)
1661 return (HINSTANCE)LoadLibrary16(libname);
1666 /***********************************************************************
1667 * PrivateFreeLibrary (KERNEL32)
1669 * FIXME: rough guesswork, don't know what "Private" means
1671 void WINAPI PrivateFreeLibrary(HINSTANCE handle)
1673 FreeLibrary16((HINSTANCE16)handle);
1677 /***********************************************************************
1678 * WIN32_GetProcAddress16 (KERNEL32.36)
1679 * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
1681 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
1683 WORD ordinal;
1684 FARPROC16 ret;
1686 if (!hModule) {
1687 WARN_(module)("hModule may not be 0!\n");
1688 return (FARPROC16)0;
1690 if (HIWORD(hModule))
1692 WARN_(module)("hModule is Win32 handle (%08x)\n", hModule );
1693 return (FARPROC16)0;
1695 hModule = GetExePtr( hModule );
1696 if (HIWORD(name)) {
1697 ordinal = NE_GetOrdinal( hModule, name );
1698 TRACE_(module)("%04x '%s'\n",
1699 hModule, name );
1700 } else {
1701 ordinal = LOWORD(name);
1702 TRACE_(module)("%04x %04x\n",
1703 hModule, ordinal );
1705 if (!ordinal) return (FARPROC16)0;
1706 ret = NE_GetEntryPoint( hModule, ordinal );
1707 TRACE_(module)("returning %08x\n",(UINT)ret);
1708 return ret;
1711 /***********************************************************************
1712 * GetProcAddress16 (KERNEL.50)
1714 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, SEGPTR name )
1716 WORD ordinal;
1717 FARPROC16 ret;
1719 if (!hModule) hModule = GetCurrentTask();
1720 hModule = GetExePtr( hModule );
1722 if (HIWORD(name) != 0)
1724 ordinal = NE_GetOrdinal( hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1725 TRACE_(module)("%04x '%s'\n",
1726 hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1728 else
1730 ordinal = LOWORD(name);
1731 TRACE_(module)("%04x %04x\n",
1732 hModule, ordinal );
1734 if (!ordinal) return (FARPROC16)0;
1736 ret = NE_GetEntryPoint( hModule, ordinal );
1738 TRACE_(module)("returning %08x\n", (UINT)ret );
1739 return ret;
1743 /***********************************************************************
1744 * GetProcAddress32 (KERNEL32.257)
1746 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1748 return MODULE_GetProcAddress( hModule, function, TRUE );
1751 /***********************************************************************
1752 * WIN16_GetProcAddress32 (KERNEL.453)
1754 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
1756 return MODULE_GetProcAddress( hModule, function, FALSE );
1759 /***********************************************************************
1760 * MODULE_GetProcAddress32 (internal)
1762 FARPROC MODULE_GetProcAddress(
1763 HMODULE hModule, /* [in] current module handle */
1764 LPCSTR function, /* [in] function to be looked up */
1765 BOOL snoop )
1767 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1768 FARPROC retproc;
1770 if (HIWORD(function))
1771 TRACE_(win32)("(%08lx,%s)\n",(DWORD)hModule,function);
1772 else
1773 TRACE_(win32)("(%08lx,%p)\n",(DWORD)hModule,function);
1774 if (!wm) {
1775 SetLastError(ERROR_INVALID_HANDLE);
1776 return (FARPROC)0;
1778 switch (wm->type)
1780 case MODULE32_PE:
1781 retproc = PE_FindExportedFunction( wm, function, snoop );
1782 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1783 return retproc;
1784 case MODULE32_ELF:
1785 retproc = ELF_FindExportedFunction( wm, function);
1786 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1787 return retproc;
1788 default:
1789 ERR_(module)("wine_modref type %d not handled.\n",wm->type);
1790 SetLastError(ERROR_INVALID_HANDLE);
1791 return (FARPROC)0;
1796 /***********************************************************************
1797 * RtlImageNtHeaders (NTDLL)
1799 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
1801 /* basically:
1802 * return hModule+(((IMAGE_DOS_HEADER*)hModule)->e_lfanew);
1803 * but we could get HMODULE16 or the like (think builtin modules)
1806 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1807 if (!wm || (wm->type != MODULE32_PE)) return (PIMAGE_NT_HEADERS)0;
1808 return PE_HEADER(wm->module);
1812 /***************************************************************************
1813 * HasGPHandler (KERNEL.338)
1816 #include "pshpack1.h"
1817 typedef struct _GPHANDLERDEF
1819 WORD selector;
1820 WORD rangeStart;
1821 WORD rangeEnd;
1822 WORD handler;
1823 } GPHANDLERDEF;
1824 #include "poppack.h"
1826 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1828 HMODULE16 hModule;
1829 int gpOrdinal;
1830 SEGPTR gpPtr;
1831 GPHANDLERDEF *gpHandler;
1833 if ( (hModule = FarGetOwner16( SELECTOROF(address) )) != 0
1834 && (gpOrdinal = NE_GetOrdinal( hModule, "__GP" )) != 0
1835 && (gpPtr = (SEGPTR)NE_GetEntryPointEx( hModule, gpOrdinal, FALSE )) != 0
1836 && !IsBadReadPtr16( gpPtr, sizeof(GPHANDLERDEF) )
1837 && (gpHandler = PTR_SEG_TO_LIN( gpPtr )) != NULL )
1839 while (gpHandler->selector)
1841 if ( SELECTOROF(address) == gpHandler->selector
1842 && OFFSETOF(address) >= gpHandler->rangeStart
1843 && OFFSETOF(address) < gpHandler->rangeEnd )
1844 return PTR_SEG_OFF_TO_SEGPTR( gpHandler->selector,
1845 gpHandler->handler );
1846 gpHandler++;
1850 return 0;