Set refcounter to 1 on initial init or WSAStartup/WSAStartup with
[wine/testsucceed.git] / loader / module.c
blobeef1345e57a429885ae4ffbaec3cc630c6b1e42d
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;
344 OSVERSIONINFOA versionInfo;
346 INT of_size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName)
347 + strlen(ofs->szPathName) + 1;
348 INT size = sizeof(NE_MODULE) +
349 /* loaded file info */
350 of_size +
351 /* segment table: DS,CS */
352 2 * sizeof(SEGTABLEENTRY) +
353 /* name table */
355 /* several empty tables */
358 hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
359 if (!hModule) return (HMODULE)11; /* invalid exe */
361 FarSetOwner16( hModule, hModule );
362 pModule = (NE_MODULE *)GlobalLock16( hModule );
364 /* Set all used entries */
365 pModule->magic = IMAGE_OS2_SIGNATURE;
366 pModule->count = 1;
367 pModule->next = 0;
368 pModule->flags = 0;
369 pModule->dgroup = 0;
370 pModule->ss = 1;
371 pModule->cs = 2;
372 pModule->heap_size = 0;
373 pModule->stack_size = 0;
374 pModule->seg_count = 2;
375 pModule->modref_count = 0;
376 pModule->nrname_size = 0;
377 pModule->fileinfo = sizeof(NE_MODULE);
378 pModule->os_flags = NE_OSFLAGS_WINDOWS;
379 pModule->expected_version = 0x030a;
380 pModule->self = hModule;
382 /* Set expected_version according to the emulated Windows version */
383 versionInfo.dwOSVersionInfoSize = sizeof(versionInfo);
384 if ( GetVersionExA( &versionInfo ) )
385 pModule->expected_version = (versionInfo.dwMajorVersion & 0xff) << 8
386 | (versionInfo.dwMinorVersion & 0xff);
389 /* Set loaded file information */
390 memcpy( pModule + 1, ofs, of_size );
391 ((OFSTRUCT *)(pModule+1))->cBytes = of_size - 1;
393 pSegment = (SEGTABLEENTRY*)((char*)(pModule + 1) + of_size);
394 pModule->seg_table = (int)pSegment - (int)pModule;
395 /* Data segment */
396 pSegment->size = 0;
397 pSegment->flags = NE_SEGFLAGS_DATA;
398 pSegment->minsize = 0x1000;
399 pSegment++;
400 /* Code segment */
401 pSegment->flags = 0;
402 pSegment++;
404 /* Module name */
405 pStr = (char *)pSegment;
406 pModule->name_table = (int)pStr - (int)pModule;
407 if ( modName )
408 basename = modName;
409 else
411 basename = strrchr(ofs->szPathName,'\\');
412 if (!basename) basename = ofs->szPathName;
413 else basename++;
415 len = strlen(basename);
416 if ((s = strchr(basename,'.'))) len = s - basename;
417 if (len > 8) len = 8;
418 *pStr = len;
419 strncpy( pStr+1, basename, len );
420 if (len < 8) pStr[len+1] = 0;
421 pStr += 9;
423 /* All tables zero terminated */
424 pModule->res_table = pModule->import_table = pModule->entry_table =
425 (int)pStr - (int)pModule;
427 NE_RegisterModule( pModule );
428 return hModule;
432 /**********************************************************************
433 * MODULE_FindModule32
435 * Find a (loaded) win32 module depending on path
436 * The handling of '.' is a bit weird, but we need it that way,
437 * for sometimes the programs use '<name>.exe' and '<name>.dll' and
438 * this is the only way to differentiate. (mainly hypertrm.exe)
440 * RETURNS
441 * the module handle if found
442 * 0 if not
444 WINE_MODREF *MODULE_FindModule(
445 LPCSTR path /* [in] pathname of module/library to be found */
447 LPSTR filename;
448 LPSTR dotptr;
449 WINE_MODREF *wm;
451 if (!(filename = strrchr( path, '\\' )))
452 filename = HEAP_strdupA( GetProcessHeap(), 0, path );
453 else
454 filename = HEAP_strdupA( GetProcessHeap(), 0, filename+1 );
455 dotptr=strrchr(filename,'.');
457 for ( wm = PROCESS_Current()->modref_list; wm; wm=wm->next ) {
458 LPSTR xmodname,xdotptr;
460 assert (wm->modname);
461 xmodname = HEAP_strdupA( GetProcessHeap(), 0, wm->modname );
462 xdotptr=strrchr(xmodname,'.');
463 if ( (xdotptr && !dotptr) ||
464 (!xdotptr && dotptr)
466 if (dotptr) *dotptr = '\0';
467 if (xdotptr) *xdotptr = '\0';
469 if (!strcasecmp( filename, xmodname)) {
470 HeapFree( GetProcessHeap(), 0, filename );
471 HeapFree( GetProcessHeap(), 0, xmodname );
472 return wm;
474 if (dotptr) *dotptr='.';
475 /* FIXME: add paths, shortname */
476 HeapFree( GetProcessHeap(), 0, xmodname );
478 /* if that fails, try looking for the filename... */
479 for ( wm = PROCESS_Current()->modref_list; wm; wm=wm->next ) {
480 LPSTR xlname,xdotptr;
482 assert (wm->longname);
483 xlname = strrchr(wm->longname,'\\');
484 if (!xlname)
485 xlname = wm->longname;
486 else
487 xlname++;
488 xlname = HEAP_strdupA( GetProcessHeap(), 0, xlname );
489 xdotptr=strrchr(xlname,'.');
490 if ( (xdotptr && !dotptr) ||
491 (!xdotptr && dotptr)
493 if (dotptr) *dotptr = '\0';
494 if (xdotptr) *xdotptr = '\0';
496 if (!strcasecmp( filename, xlname)) {
497 HeapFree( GetProcessHeap(), 0, filename );
498 HeapFree( GetProcessHeap(), 0, xlname );
499 return wm;
501 if (dotptr) *dotptr='.';
502 /* FIXME: add paths, shortname */
503 HeapFree( GetProcessHeap(), 0, xlname );
505 HeapFree( GetProcessHeap(), 0, filename );
506 return NULL;
509 /***********************************************************************
510 * MODULE_GetBinaryType
512 * The GetBinaryType function determines whether a file is executable
513 * or not and if it is it returns what type of executable it is.
514 * The type of executable is a property that determines in which
515 * subsystem an executable file runs under.
517 * Binary types returned:
518 * SCS_32BIT_BINARY: A Win32 based application
519 * SCS_DOS_BINARY: An MS-Dos based application
520 * SCS_WOW_BINARY: A Win16 based application
521 * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
522 * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
523 * SCS_OS216_BINARY: A 16bit OS/2 based application
525 * Returns TRUE if the file is an executable in which case
526 * the value pointed by lpBinaryType is set.
527 * Returns FALSE if the file is not an executable or if the function fails.
529 * To do so it opens the file and reads in the header information
530 * if the extended header information is not presend it will
531 * assume that that the file is a DOS executable.
532 * If the extended header information is present it will
533 * determine if the file is an 16 or 32 bit Windows executable
534 * by check the flags in the header.
536 * Note that .COM and .PIF files are only recognized by their
537 * file name extension; but Windows does it the same way ...
539 static BOOL MODULE_GetBinaryType( HFILE hfile, OFSTRUCT *ofs,
540 LPDWORD lpBinaryType )
542 IMAGE_DOS_HEADER mz_header;
543 char magic[4], *ptr;
545 /* Seek to the start of the file and read the DOS header information.
547 if ( _llseek( hfile, 0, SEEK_SET ) >= 0 &&
548 _lread( hfile, &mz_header, sizeof(mz_header) ) == sizeof(mz_header) )
550 /* Now that we have the header check the e_magic field
551 * to see if this is a dos image.
553 if ( mz_header.e_magic == IMAGE_DOS_SIGNATURE )
555 BOOL lfanewValid = FALSE;
556 /* We do have a DOS image so we will now try to seek into
557 * the file by the amount indicated by the field
558 * "Offset to extended header" and read in the
559 * "magic" field information at that location.
560 * This will tell us if there is more header information
561 * to read or not.
563 /* But before we do we will make sure that header
564 * structure encompasses the "Offset to extended header"
565 * field.
567 if ( (mz_header.e_cparhdr<<4) >= sizeof(IMAGE_DOS_HEADER) )
568 if ( ( mz_header.e_crlc == 0 && mz_header.e_lfarlc == 0 ) ||
569 ( mz_header.e_lfarlc >= sizeof(IMAGE_DOS_HEADER) ) )
570 if ( mz_header.e_lfanew >= sizeof(IMAGE_DOS_HEADER) &&
571 _llseek( hfile, mz_header.e_lfanew, SEEK_SET ) >= 0 &&
572 _lread( hfile, magic, sizeof(magic) ) == sizeof(magic) )
573 lfanewValid = TRUE;
575 if ( !lfanewValid )
577 /* If we cannot read this "extended header" we will
578 * assume that we have a simple DOS executable.
580 *lpBinaryType = SCS_DOS_BINARY;
581 return TRUE;
583 else
585 /* Reading the magic field succeeded so
586 * we will try to determine what type it is.
588 if ( *(DWORD*)magic == IMAGE_NT_SIGNATURE )
590 /* This is an NT signature.
592 *lpBinaryType = SCS_32BIT_BINARY;
593 return TRUE;
595 else if ( *(WORD*)magic == IMAGE_OS2_SIGNATURE )
597 /* The IMAGE_OS2_SIGNATURE indicates that the
598 * "extended header is a Windows executable (NE)
599 * header." This can mean either a 16-bit OS/2
600 * or a 16-bit Windows or even a DOS program
601 * (running under a DOS extender). To decide
602 * which, we'll have to read the NE header.
605 IMAGE_OS2_HEADER ne;
606 if ( _llseek( hfile, mz_header.e_lfanew, SEEK_SET ) >= 0 &&
607 _lread( hfile, &ne, sizeof(ne) ) == sizeof(ne) )
609 switch ( ne.operating_system )
611 case 2: *lpBinaryType = SCS_WOW_BINARY; return TRUE;
612 case 5: *lpBinaryType = SCS_DOS_BINARY; return TRUE;
613 default: *lpBinaryType = SCS_OS216_BINARY; return TRUE;
616 /* Couldn't read header, so abort. */
617 return FALSE;
619 else
621 /* Unknown extended header, so abort.
623 return FALSE;
629 /* If we get here, we don't even have a correct MZ header.
630 * Try to check the file extension for known types ...
632 ptr = strrchr( ofs->szPathName, '.' );
633 if ( ptr && !strchr( ptr, '\\' ) && !strchr( ptr, '/' ) )
635 if ( !lstrcmpiA( ptr, ".COM" ) )
637 *lpBinaryType = SCS_DOS_BINARY;
638 return TRUE;
641 if ( !lstrcmpiA( ptr, ".PIF" ) )
643 *lpBinaryType = SCS_PIF_BINARY;
644 return TRUE;
648 return FALSE;
651 /***********************************************************************
652 * GetBinaryTypeA [KERNEL32.280]
654 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
656 BOOL ret = FALSE;
657 HFILE hfile;
658 OFSTRUCT ofs;
660 TRACE_(win32)("%s\n", lpApplicationName );
662 /* Sanity check.
664 if ( lpApplicationName == NULL || lpBinaryType == NULL )
665 return FALSE;
667 /* Open the file indicated by lpApplicationName for reading.
669 if ( (hfile = OpenFile( lpApplicationName, &ofs, OF_READ )) == HFILE_ERROR )
670 return FALSE;
672 /* Check binary type
674 ret = MODULE_GetBinaryType( hfile, &ofs, lpBinaryType );
676 /* Close the file.
678 CloseHandle( hfile );
680 return ret;
683 /***********************************************************************
684 * GetBinaryTypeW [KERNEL32.281]
686 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
688 BOOL ret = FALSE;
689 LPSTR strNew = NULL;
691 TRACE_(win32)("%s\n", debugstr_w(lpApplicationName) );
693 /* Sanity check.
695 if ( lpApplicationName == NULL || lpBinaryType == NULL )
696 return FALSE;
698 /* Convert the wide string to a ascii string.
700 strNew = HEAP_strdupWtoA( GetProcessHeap(), 0, lpApplicationName );
702 if ( strNew != NULL )
704 ret = GetBinaryTypeA( strNew, lpBinaryType );
706 /* Free the allocated string.
708 HeapFree( GetProcessHeap(), 0, strNew );
711 return ret;
714 /**********************************************************************
715 * MODULE_CreateUnixProcess
717 static BOOL MODULE_CreateUnixProcess( LPCSTR filename, LPCSTR lpCmdLine,
718 LPSTARTUPINFOA lpStartupInfo,
719 LPPROCESS_INFORMATION lpProcessInfo,
720 BOOL useWine )
722 DOS_FULL_NAME full_name;
723 const char *unixfilename = filename;
724 const char *argv[256], **argptr;
725 char *cmdline = NULL;
726 BOOL iconic = FALSE;
728 /* Get Unix file name and iconic flag */
730 if ( lpStartupInfo->dwFlags & STARTF_USESHOWWINDOW )
731 if ( lpStartupInfo->wShowWindow == SW_SHOWMINIMIZED
732 || lpStartupInfo->wShowWindow == SW_SHOWMINNOACTIVE )
733 iconic = TRUE;
735 /* Build argument list */
737 argptr = argv;
738 if ( !useWine )
740 char *p;
741 p = cmdline = strdup(lpCmdLine);
742 if (strchr(filename, '/') || strchr(filename, ':') || strchr(filename, '\\'))
744 if ( DOSFS_GetFullName( filename, TRUE, &full_name ) )
745 unixfilename = full_name.long_name;
747 *argptr++ = unixfilename;
748 if (iconic) *argptr++ = "-iconic";
749 while (1)
751 while (*p && (*p == ' ' || *p == '\t')) *p++ = '\0';
752 if (!*p) break;
753 *argptr++ = p;
754 while (*p && *p != ' ' && *p != '\t') p++;
757 else
759 *argptr++ = "wine";
760 if (iconic) *argptr++ = "-iconic";
761 *argptr++ = lpCmdLine;
763 *argptr++ = 0;
765 /* Fork and execute */
767 if ( !fork() )
769 /* Note: don't use Wine routines here, as this process
770 has not been correctly initialized! */
772 execvp( argv[0], (char**)argv );
774 /* Failed ! */
775 if ( useWine )
776 fprintf( stderr, "CreateProcess: can't exec 'wine %s'\n",
777 lpCmdLine );
778 exit( 1 );
781 /* Fake success return value */
783 memset( lpProcessInfo, '\0', sizeof( *lpProcessInfo ) );
784 lpProcessInfo->hProcess = INVALID_HANDLE_VALUE;
785 lpProcessInfo->hThread = INVALID_HANDLE_VALUE;
786 if (cmdline) free(cmdline);
788 SetLastError( ERROR_SUCCESS );
789 return TRUE;
792 /***********************************************************************
793 * WinExec16 (KERNEL.166)
795 HINSTANCE16 WINAPI WinExec16( LPCSTR lpCmdLine, UINT16 nCmdShow )
797 HINSTANCE16 hInst;
799 SYSLEVEL_ReleaseWin16Lock();
800 hInst = WinExec( lpCmdLine, nCmdShow );
801 SYSLEVEL_RestoreWin16Lock();
803 return hInst;
806 /***********************************************************************
807 * WinExec (KERNEL32.566)
809 HINSTANCE WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
811 LOADPARAMS params;
812 UINT16 paramCmdShow[2];
814 if (!lpCmdLine)
815 return 2; /* File not found */
817 /* Set up LOADPARAMS buffer for LoadModule */
819 memset( &params, '\0', sizeof(params) );
820 params.lpCmdLine = (LPSTR)lpCmdLine;
821 params.lpCmdShow = paramCmdShow;
822 params.lpCmdShow[0] = 2;
823 params.lpCmdShow[1] = nCmdShow;
825 /* Now load the executable file */
827 return LoadModule( NULL, &params );
830 /**********************************************************************
831 * LoadModule (KERNEL32.499)
833 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
835 LOADPARAMS *params = (LOADPARAMS *)paramBlock;
836 PROCESS_INFORMATION info;
837 STARTUPINFOA startup;
838 HINSTANCE hInstance;
839 PDB *pdb;
840 TDB *tdb;
842 memset( &startup, '\0', sizeof(startup) );
843 startup.cb = sizeof(startup);
844 startup.dwFlags = STARTF_USESHOWWINDOW;
845 startup.wShowWindow = params->lpCmdShow? params->lpCmdShow[1] : 0;
847 if ( !CreateProcessA( name, params->lpCmdLine,
848 NULL, NULL, FALSE, 0, params->lpEnvAddress,
849 NULL, &startup, &info ) )
851 hInstance = GetLastError();
852 if ( hInstance < 32 ) return hInstance;
854 FIXME_(module)("Strange error set by CreateProcess: %d\n", hInstance );
855 return 11;
858 /* Get 16-bit hInstance/hTask from process */
859 pdb = PROCESS_IdToPDB( info.dwProcessId );
860 tdb = pdb? (TDB *)GlobalLock16( pdb->task ) : NULL;
861 hInstance = tdb && tdb->hInstance? tdb->hInstance : pdb? pdb->task : 0;
862 /* If there is no hInstance (32-bit process) return a dummy value
863 * that must be > 31
864 * FIXME: should do this in all cases and fix Win16 callers */
865 if (!hInstance) hInstance = 33;
867 /* Close off the handles */
868 CloseHandle( info.hThread );
869 CloseHandle( info.hProcess );
871 return hInstance;
874 /*************************************************************************
875 * get_makename_token
877 * Get next blank delimited token from input string. If quoted then
878 * process till matching quote and then till blank.
880 * Returns number of characters in token (not including \0). On
881 * end of string (EOS), returns a 0.
883 * from (IO) address of start of input string to scan, updated to
884 * next non-processed character.
885 * to (IO) address of start of output string (previous token \0
886 * char), updated to end of new output string (the \0
887 * char).
889 static int get_makename_token(LPCSTR *from, LPSTR *to )
891 int len = 0;
892 LPCSTR to_old = *to; /* only used for tracing */
894 while ( **from == ' ') {
895 /* Copy leading blanks (separators between previous */
896 /* token and this token). */
897 **to = **from;
898 (*from)++;
899 (*to)++;
900 len++;
902 do {
903 while ( (**from != 0) && (**from != ' ') && (**from != '"') ) {
904 **to = **from; (*from)++; (*to)++; len++;
906 if ( **from == '"' ) {
907 /* Handle quoted string. */
908 (*from)++;
909 if ( !strchr(*from, '"') ) {
910 /* fail - no closing quote. Return entire string */
911 while ( **from != 0 ) {
912 **to = **from; (*from)++; (*to)++; len++;
914 break;
916 while( **from != '"') {
917 **to = **from;
918 len++;
919 (*to)++;
920 (*from)++;
922 (*from)++;
923 continue;
926 /* either EOS or ' ' */
927 break;
929 } while (1);
931 **to = 0; /* terminate output string */
933 TRACE_(module)("returning token len=%d, string=%s\n",
934 len, to_old);
936 return len;
939 /*************************************************************************
940 * make_lpCommandLine_name
942 * Try longer and longer strings from "line" to find an existing
943 * file name. Each attempt is delimited by a blank outside of quotes.
944 * Also will attempt to append ".exe" if requested and not already
945 * present. Returns the address of the remaining portion of the
946 * input line.
950 static BOOL make_lpCommandLine_name( LPCSTR line, LPSTR name, int namelen,
951 LPCSTR *after )
953 BOOL found = TRUE;
954 LPCSTR from;
955 char buffer[260];
956 DWORD retlen;
957 LPSTR to, lastpart;
959 from = line;
960 to = name;
962 /* scan over initial blanks if any */
963 while ( *from == ' ') from++;
965 /* get a token and append to previous data the check for existance */
966 do {
967 if ( !get_makename_token( &from, &to ) ) {
968 /* EOS has occured and not found - exit */
969 retlen = 0;
970 found = FALSE;
971 break;
973 TRACE_(module)("checking if file exists '%s'\n", name);
974 retlen = SearchPathA( NULL, name, ".exe", sizeof(buffer), buffer, &lastpart);
975 if ( retlen && (retlen < sizeof(buffer)) ) break;
976 } while (1);
978 /* if we have a non-null full path name in buffer then move to output */
979 if ( retlen ) {
980 if ( strlen(buffer) <= namelen ) {
981 strcpy( name, buffer );
982 } else {
983 /* not enough space to return full path string */
984 FIXME_(module)("internal string not long enough, need %d\n",
985 strlen(buffer) );
989 /* all done, indicate end of module name and then trace and exit */
990 if (after) *after = from;
991 TRACE_(module)("%i, selected file name '%s'\n and cmdline as %s\n",
992 found, name, debugstr_a(from));
993 return found;
996 /*************************************************************************
997 * make_lpApplicationName_name
999 * Scan input string (the lpApplicationName) and remove any quotes
1000 * if they are balanced.
1004 static BOOL make_lpApplicationName_name( LPCSTR line, LPSTR name, int namelen)
1006 LPCSTR from;
1007 LPSTR to, to_end, to_old;
1008 DOS_FULL_NAME full_name;
1010 to = name;
1011 to_end = to + namelen - 1;
1012 to_old = to;
1014 while ( *line == ' ' ) line++; /* point to beginning of string */
1015 from = line;
1016 do {
1017 /* Copy all input till end, or quote */
1018 while((*from != 0) && (*from != '"') && (to < to_end))
1019 *to++ = *from++;
1020 if (to >= to_end) { *to = 0; break; }
1022 if (*from == '"')
1024 /* Handle quoted string. If there is a closing quote, copy all */
1025 /* that is inside. */
1026 from++;
1027 if (!strchr(from, '"'))
1029 /* fail - no closing quote */
1030 to = to_old; /* restore to previous attempt */
1031 *to = 0; /* end string */
1032 break; /* exit with previous attempt */
1034 while((*from != '"') && (to < to_end)) *to++ = *from++;
1035 if (to >= to_end) { *to = 0; break; }
1036 from++;
1037 continue; /* past quoted string, so restart from top */
1040 *to = 0; /* terminate output string */
1041 to_old = to; /* save for possible use in unmatched quote case */
1043 /* loop around keeping the blank as part of file name */
1044 if (!*from)
1045 break; /* exit if out of input string */
1046 } while (1);
1048 if (!DOSFS_GetFullName(name, TRUE, &full_name)) {
1049 TRACE_(module)("file not found '%s'\n", name );
1050 return FALSE;
1053 if (strlen(full_name.long_name) >= namelen ) {
1054 FIXME_(module)("name longer than buffer (len=%d), file=%s\n",
1055 namelen, full_name.long_name);
1056 return FALSE;
1058 strcpy(name, full_name.long_name);
1060 TRACE_(module)("selected as file name '%s'\n", name );
1061 return TRUE;
1064 /**********************************************************************
1065 * CreateProcessA (KERNEL32.171)
1067 BOOL WINAPI CreateProcessA( LPCSTR lpApplicationName, LPSTR lpCommandLine,
1068 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1069 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1070 BOOL bInheritHandles, DWORD dwCreationFlags,
1071 LPVOID lpEnvironment, LPCSTR lpCurrentDirectory,
1072 LPSTARTUPINFOA lpStartupInfo,
1073 LPPROCESS_INFORMATION lpProcessInfo )
1075 BOOL retv = FALSE;
1076 BOOL found_file = FALSE;
1077 HFILE hFile;
1078 OFSTRUCT ofs;
1079 DWORD type;
1080 char name[256], dummy[256];
1081 LPCSTR cmdline = NULL;
1082 LPSTR tidy_cmdline;
1083 int len = 0;
1085 /* Get name and command line */
1087 if (!lpApplicationName && !lpCommandLine)
1089 SetLastError( ERROR_FILE_NOT_FOUND );
1090 return FALSE;
1093 /* Process the AppName and/or CmdLine to get module name and path */
1095 name[0] = '\0';
1097 if (lpApplicationName) {
1098 found_file = make_lpApplicationName_name( lpApplicationName, name, sizeof(name) );
1099 if (lpCommandLine) {
1100 make_lpCommandLine_name( lpCommandLine, dummy, sizeof ( dummy ), &cmdline );
1102 else {
1103 cmdline = lpApplicationName;
1105 len += strlen(lpApplicationName);
1107 else {
1108 found_file = make_lpCommandLine_name( lpCommandLine, name, sizeof ( name ), &cmdline );
1109 if (lpCommandLine) len = strlen(lpCommandLine);
1112 if ( !found_file ) {
1113 /* make an early exit if file not found - save second pass */
1114 SetLastError( ERROR_FILE_NOT_FOUND );
1115 return FALSE;
1118 len += strlen(name) + 2;
1119 tidy_cmdline = HeapAlloc( GetProcessHeap(), 0, len );
1120 sprintf( tidy_cmdline, "\"%s\"%s", name, cmdline);
1122 /* Warn if unsupported features are used */
1124 if (dwCreationFlags & CREATE_SUSPENDED)
1125 FIXME_(module)("(%s,...): CREATE_SUSPENDED ignored\n", name);
1126 if (dwCreationFlags & DETACHED_PROCESS)
1127 FIXME_(module)("(%s,...): DETACHED_PROCESS ignored\n", name);
1128 if (dwCreationFlags & CREATE_NEW_CONSOLE)
1129 FIXME_(module)("(%s,...): CREATE_NEW_CONSOLE ignored\n", name);
1130 if (dwCreationFlags & NORMAL_PRIORITY_CLASS)
1131 FIXME_(module)("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
1132 if (dwCreationFlags & IDLE_PRIORITY_CLASS)
1133 FIXME_(module)("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
1134 if (dwCreationFlags & HIGH_PRIORITY_CLASS)
1135 FIXME_(module)("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
1136 if (dwCreationFlags & REALTIME_PRIORITY_CLASS)
1137 FIXME_(module)("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
1138 if (dwCreationFlags & CREATE_NEW_PROCESS_GROUP)
1139 FIXME_(module)("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
1140 if (dwCreationFlags & CREATE_UNICODE_ENVIRONMENT)
1141 FIXME_(module)("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
1142 if (dwCreationFlags & CREATE_SEPARATE_WOW_VDM)
1143 FIXME_(module)("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
1144 if (dwCreationFlags & CREATE_SHARED_WOW_VDM)
1145 FIXME_(module)("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
1146 if (dwCreationFlags & CREATE_DEFAULT_ERROR_MODE)
1147 FIXME_(module)("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
1148 if (dwCreationFlags & CREATE_NO_WINDOW)
1149 FIXME_(module)("(%s,...): CREATE_NO_WINDOW ignored\n", name);
1150 if (dwCreationFlags & PROFILE_USER)
1151 FIXME_(module)("(%s,...): PROFILE_USER ignored\n", name);
1152 if (dwCreationFlags & PROFILE_KERNEL)
1153 FIXME_(module)("(%s,...): PROFILE_KERNEL ignored\n", name);
1154 if (dwCreationFlags & PROFILE_SERVER)
1155 FIXME_(module)("(%s,...): PROFILE_SERVER ignored\n", name);
1156 if (lpCurrentDirectory)
1157 FIXME_(module)("(%s,...): lpCurrentDirectory %s ignored\n",
1158 name, lpCurrentDirectory);
1159 if (lpStartupInfo->lpDesktop)
1160 FIXME_(module)("(%s,...): lpStartupInfo->lpDesktop %s ignored\n",
1161 name, lpStartupInfo->lpDesktop);
1162 if (lpStartupInfo->lpTitle)
1163 FIXME_(module)("(%s,...): lpStartupInfo->lpTitle %s ignored\n",
1164 name, lpStartupInfo->lpTitle);
1165 if (lpStartupInfo->dwFlags & STARTF_USECOUNTCHARS)
1166 FIXME_(module)("(%s,...): STARTF_USECOUNTCHARS (%ld,%ld) ignored\n",
1167 name, lpStartupInfo->dwXCountChars, lpStartupInfo->dwYCountChars);
1168 if (lpStartupInfo->dwFlags & STARTF_USEFILLATTRIBUTE)
1169 FIXME_(module)("(%s,...): STARTF_USEFILLATTRIBUTE %lx ignored\n",
1170 name, lpStartupInfo->dwFillAttribute);
1171 if (lpStartupInfo->dwFlags & STARTF_RUNFULLSCREEN)
1172 FIXME_(module)("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
1173 if (lpStartupInfo->dwFlags & STARTF_FORCEONFEEDBACK)
1174 FIXME_(module)("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
1175 if (lpStartupInfo->dwFlags & STARTF_FORCEOFFFEEDBACK)
1176 FIXME_(module)("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
1177 if (lpStartupInfo->dwFlags & STARTF_USEHOTKEY)
1178 FIXME_(module)("(%s,...): STARTF_USEHOTKEY ignored\n", name);
1180 /* Check for special case: second instance of NE module */
1182 lstrcpynA( ofs.szPathName, name, sizeof( ofs.szPathName ) );
1183 retv = NE_CreateProcess( HFILE_ERROR, &ofs, tidy_cmdline, lpEnvironment,
1184 lpProcessAttributes, lpThreadAttributes,
1185 bInheritHandles, dwCreationFlags,
1186 lpStartupInfo, lpProcessInfo );
1188 /* Load file and create process */
1190 if ( !retv )
1192 /* Open file and determine executable type */
1194 if ( (hFile = OpenFile( name, &ofs, OF_READ )) == HFILE_ERROR )
1196 SetLastError( ERROR_FILE_NOT_FOUND );
1197 HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1198 return FALSE;
1201 if ( !MODULE_GetBinaryType( hFile, &ofs, &type ) )
1203 CloseHandle( hFile );
1205 /* FIXME: Try Unix executable only when appropriate! */
1206 if ( MODULE_CreateUnixProcess( name, tidy_cmdline,
1207 lpStartupInfo, lpProcessInfo, FALSE ) )
1209 HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1210 return TRUE;
1212 HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1213 SetLastError( ERROR_BAD_FORMAT );
1214 return FALSE;
1218 /* Create process */
1220 switch ( type )
1222 case SCS_32BIT_BINARY:
1223 retv = PE_CreateProcess( hFile, &ofs, tidy_cmdline, lpEnvironment,
1224 lpProcessAttributes, lpThreadAttributes,
1225 bInheritHandles, dwCreationFlags,
1226 lpStartupInfo, lpProcessInfo );
1227 break;
1229 case SCS_DOS_BINARY:
1230 retv = MZ_CreateProcess( hFile, &ofs, tidy_cmdline, lpEnvironment,
1231 lpProcessAttributes, lpThreadAttributes,
1232 bInheritHandles, dwCreationFlags,
1233 lpStartupInfo, lpProcessInfo );
1234 break;
1236 case SCS_WOW_BINARY:
1237 retv = NE_CreateProcess( hFile, &ofs, tidy_cmdline, lpEnvironment,
1238 lpProcessAttributes, lpThreadAttributes,
1239 bInheritHandles, dwCreationFlags,
1240 lpStartupInfo, lpProcessInfo );
1241 break;
1243 case SCS_PIF_BINARY:
1244 case SCS_POSIX_BINARY:
1245 case SCS_OS216_BINARY:
1246 FIXME_(module)("Unsupported executable type: %ld\n", type );
1247 /* fall through */
1249 default:
1250 SetLastError( ERROR_BAD_FORMAT );
1251 retv = FALSE;
1252 break;
1255 CloseHandle( hFile );
1257 HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1258 return retv;
1261 /**********************************************************************
1262 * CreateProcessW (KERNEL32.172)
1263 * NOTES
1264 * lpReserved is not converted
1266 BOOL WINAPI CreateProcessW( LPCWSTR lpApplicationName, LPWSTR lpCommandLine,
1267 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1268 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1269 BOOL bInheritHandles, DWORD dwCreationFlags,
1270 LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory,
1271 LPSTARTUPINFOW lpStartupInfo,
1272 LPPROCESS_INFORMATION lpProcessInfo )
1273 { BOOL ret;
1274 STARTUPINFOA StartupInfoA;
1276 LPSTR lpApplicationNameA = HEAP_strdupWtoA (GetProcessHeap(),0,lpApplicationName);
1277 LPSTR lpCommandLineA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCommandLine);
1278 LPSTR lpCurrentDirectoryA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCurrentDirectory);
1280 memcpy (&StartupInfoA, lpStartupInfo, sizeof(STARTUPINFOA));
1281 StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpDesktop);
1282 StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpTitle);
1284 TRACE_(win32)("(%s,%s,...)\n", debugstr_w(lpApplicationName), debugstr_w(lpCommandLine));
1286 if (lpStartupInfo->lpReserved)
1287 FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n", debugstr_w(lpStartupInfo->lpReserved));
1289 ret = CreateProcessA( lpApplicationNameA, lpCommandLineA,
1290 lpProcessAttributes, lpThreadAttributes,
1291 bInheritHandles, dwCreationFlags,
1292 lpEnvironment, lpCurrentDirectoryA,
1293 &StartupInfoA, lpProcessInfo );
1295 HeapFree( GetProcessHeap(), 0, lpCurrentDirectoryA );
1296 HeapFree( GetProcessHeap(), 0, lpCommandLineA );
1297 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1298 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1300 return ret;
1303 /***********************************************************************
1304 * GetModuleHandle (KERNEL32.237)
1306 HMODULE WINAPI GetModuleHandleA(LPCSTR module)
1308 WINE_MODREF *wm;
1310 if ( module == NULL )
1311 wm = PROCESS_Current()->exe_modref;
1312 else
1313 wm = MODULE_FindModule( module );
1315 return wm? wm->module : 0;
1318 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
1320 HMODULE hModule;
1321 LPSTR modulea = HEAP_strdupWtoA( GetProcessHeap(), 0, module );
1322 hModule = GetModuleHandleA( modulea );
1323 HeapFree( GetProcessHeap(), 0, modulea );
1324 return hModule;
1328 /***********************************************************************
1329 * GetModuleFileName32A (KERNEL32.235)
1331 DWORD WINAPI GetModuleFileNameA(
1332 HMODULE hModule, /* [in] module handle (32bit) */
1333 LPSTR lpFileName, /* [out] filenamebuffer */
1334 DWORD size /* [in] size of filenamebuffer */
1335 ) {
1336 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1338 if (!wm) /* can happen on start up or the like */
1339 return 0;
1341 if (PE_HEADER(wm->module)->OptionalHeader.MajorOperatingSystemVersion >= 4.0)
1342 lstrcpynA( lpFileName, wm->longname, size );
1343 else
1344 lstrcpynA( lpFileName, wm->shortname, size );
1346 TRACE_(module)("%s\n", lpFileName );
1347 return strlen(lpFileName);
1351 /***********************************************************************
1352 * GetModuleFileName32W (KERNEL32.236)
1354 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName,
1355 DWORD size )
1357 LPSTR fnA = (char*)HeapAlloc( GetProcessHeap(), 0, size );
1358 DWORD res = GetModuleFileNameA( hModule, fnA, size );
1359 lstrcpynAtoW( lpFileName, fnA, size );
1360 HeapFree( GetProcessHeap(), 0, fnA );
1361 return res;
1365 /***********************************************************************
1366 * LoadLibraryExA (KERNEL32)
1368 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HFILE hfile, DWORD flags)
1370 WINE_MODREF *wm;
1372 if(!libname)
1374 SetLastError(ERROR_INVALID_PARAMETER);
1375 return 0;
1378 EnterCriticalSection(&PROCESS_Current()->crit_section);
1380 wm = MODULE_LoadLibraryExA( libname, hfile, flags );
1382 if(wm && !MODULE_DllProcessAttach(wm, NULL))
1384 WARN_(module)("Attach failed for module '%s', \n", libname);
1385 MODULE_FreeLibrary(wm);
1386 SetLastError(ERROR_DLL_INIT_FAILED);
1387 wm = NULL;
1390 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1392 return wm ? wm->module : 0;
1395 /***********************************************************************
1396 * MODULE_LoadLibraryExA (internal)
1398 * Load a PE style module according to the load order.
1400 * The HFILE parameter is not used and marked reserved in the SDK. I can
1401 * only guess that it should force a file to be mapped, but I rather
1402 * ignore the parameter because it would be extremely difficult to
1403 * integrate this with different types of module represenations.
1406 WINE_MODREF *MODULE_LoadLibraryExA( LPCSTR libname, HFILE hfile, DWORD flags )
1408 DWORD err;
1409 WINE_MODREF *pwm;
1410 int i;
1411 module_loadorder_t *plo;
1413 EnterCriticalSection(&PROCESS_Current()->crit_section);
1415 /* Check for already loaded module */
1416 if((pwm = MODULE_FindModule(libname)))
1418 if(!(pwm->flags & WINE_MODREF_MARKER))
1419 pwm->refCount++;
1420 TRACE_(module)("Already loaded module '%s' at 0x%08x, count=%d, \n", libname, pwm->module, pwm->refCount);
1421 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1422 return pwm;
1425 plo = MODULE_GetLoadOrder(libname);
1427 for(i = 0; i < MODULE_LOADORDER_NTYPES; i++)
1429 switch(plo->loadorder[i])
1431 case MODULE_LOADORDER_DLL:
1432 TRACE_(module)("Trying native dll '%s'\n", libname);
1433 pwm = PE_LoadLibraryExA(libname, flags, &err);
1434 break;
1436 case MODULE_LOADORDER_ELFDLL:
1437 TRACE_(module)("Trying elfdll '%s'\n", libname);
1438 pwm = ELFDLL_LoadLibraryExA(libname, flags, &err);
1439 break;
1441 case MODULE_LOADORDER_SO:
1442 TRACE_(module)("Trying so-library '%s'\n", libname);
1443 pwm = ELF_LoadLibraryExA(libname, flags, &err);
1444 break;
1446 case MODULE_LOADORDER_BI:
1447 TRACE_(module)("Trying built-in '%s'\n", libname);
1448 pwm = BUILTIN32_LoadLibraryExA(libname, flags, &err);
1449 break;
1451 default:
1452 ERR_(module)("Got invalid loadorder type %d (%s index %d)\n", plo->loadorder[i], plo->modulename, i);
1453 /* Fall through */
1455 case MODULE_LOADORDER_INVALID: /* We ignore this as it is an empty entry */
1456 pwm = NULL;
1457 break;
1460 if(pwm)
1462 /* Initialize DLL just loaded */
1463 TRACE_(module)("Loaded module '%s' at 0x%08x, \n", libname, pwm->module);
1465 /* Set the refCount here so that an attach failure will */
1466 /* decrement the dependencies through the MODULE_FreeLibrary call. */
1467 pwm->refCount++;
1469 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1471 if (PROCESS_Current()->flags & PDB32_DEBUGGED)
1472 DEBUG_SendLoadDLLEvent( -1 /*FIXME*/, pwm->module, pwm->modname );
1474 return pwm;
1477 if(err != ERROR_FILE_NOT_FOUND)
1478 break;
1481 ERR_(module)("Failed to load module '%s'; error=0x%08lx, \n", libname, err);
1482 SetLastError(err);
1483 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1484 return NULL;
1487 /***********************************************************************
1488 * LoadLibraryA (KERNEL32)
1490 HMODULE WINAPI LoadLibraryA(LPCSTR libname) {
1491 return LoadLibraryExA(libname,0,0);
1494 /***********************************************************************
1495 * LoadLibraryW (KERNEL32)
1497 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
1499 return LoadLibraryExW(libnameW,0,0);
1502 /***********************************************************************
1503 * LoadLibrary32_16 (KERNEL.452)
1505 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
1507 HMODULE hModule;
1509 SYSLEVEL_ReleaseWin16Lock();
1510 hModule = LoadLibraryA( libname );
1511 SYSLEVEL_RestoreWin16Lock();
1513 return hModule;
1516 /***********************************************************************
1517 * LoadLibraryExW (KERNEL32)
1519 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW,HFILE hfile,DWORD flags)
1521 LPSTR libnameA = HEAP_strdupWtoA( GetProcessHeap(), 0, libnameW );
1522 HMODULE ret = LoadLibraryExA( libnameA , hfile, flags );
1524 HeapFree( GetProcessHeap(), 0, libnameA );
1525 return ret;
1528 /***********************************************************************
1529 * MODULE_FlushModrefs
1531 * NOTE: Assumes that the process critical section is held!
1533 * Remove all unused modrefs and call the internal unloading routines
1534 * for the library type.
1536 static void MODULE_FlushModrefs(void)
1538 WINE_MODREF *wm, *next;
1540 for(wm = PROCESS_Current()->modref_list; wm; wm = next)
1542 next = wm->next;
1544 if(wm->refCount)
1545 continue;
1547 /* Unlink this modref from the chain */
1548 if(wm->next)
1549 wm->next->prev = wm->prev;
1550 if(wm->prev)
1551 wm->prev->next = wm->next;
1552 if(wm == PROCESS_Current()->modref_list)
1553 PROCESS_Current()->modref_list = wm->next;
1556 * The unloaders are also responsible for freeing the modref itself
1557 * because the loaders were responsible for allocating it.
1559 switch(wm->type)
1561 case MODULE32_PE: PE_UnloadLibrary(wm); break;
1562 case MODULE32_ELF: ELF_UnloadLibrary(wm); break;
1563 case MODULE32_ELFDLL: ELFDLL_UnloadLibrary(wm); break;
1564 case MODULE32_BI: BUILTIN32_UnloadLibrary(wm); break;
1566 default:
1567 ERR_(module)("Invalid or unhandled MODREF type %d encountered (wm=%p)\n", wm->type, wm);
1572 /***********************************************************************
1573 * FreeLibrary
1575 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
1577 BOOL retv = FALSE;
1578 WINE_MODREF *wm;
1580 EnterCriticalSection( &PROCESS_Current()->crit_section );
1581 PROCESS_Current()->free_lib_count++;
1583 wm = MODULE32_LookupHMODULE( hLibModule );
1584 if ( !wm || !hLibModule )
1585 SetLastError( ERROR_INVALID_HANDLE );
1586 else
1587 retv = MODULE_FreeLibrary( wm );
1589 PROCESS_Current()->free_lib_count--;
1590 LeaveCriticalSection( &PROCESS_Current()->crit_section );
1592 return retv;
1595 /***********************************************************************
1596 * MODULE_DecRefCount
1598 * NOTE: Assumes that the process critical section is held!
1600 static void MODULE_DecRefCount( WINE_MODREF *wm )
1602 int i;
1604 if ( wm->flags & WINE_MODREF_MARKER )
1605 return;
1607 if ( wm->refCount <= 0 )
1608 return;
1610 --wm->refCount;
1611 TRACE_(module)("(%s) refCount: %d\n", wm->modname, wm->refCount );
1613 if ( wm->refCount == 0 )
1615 wm->flags |= WINE_MODREF_MARKER;
1617 for ( i = 0; i < wm->nDeps; i++ )
1618 if ( wm->deps[i] )
1619 MODULE_DecRefCount( wm->deps[i] );
1621 wm->flags &= ~WINE_MODREF_MARKER;
1625 /***********************************************************************
1626 * MODULE_FreeLibrary
1628 * NOTE: Assumes that the process critical section is held!
1630 BOOL MODULE_FreeLibrary( WINE_MODREF *wm )
1632 TRACE_(module)("(%s) - START\n", wm->modname );
1634 /* Recursively decrement reference counts */
1635 MODULE_DecRefCount( wm );
1637 /* Call process detach notifications */
1638 if ( PROCESS_Current()->free_lib_count <= 1 )
1640 MODULE_DllProcessDetach( FALSE, NULL );
1641 if (PROCESS_Current()->flags & PDB32_DEBUGGED)
1642 DEBUG_SendUnloadDLLEvent( wm->module );
1645 MODULE_FlushModrefs();
1647 TRACE_(module)("(%s) - END\n", wm->modname );
1649 return TRUE;
1653 /***********************************************************************
1654 * FreeLibraryAndExitThread
1656 VOID WINAPI FreeLibraryAndExitThread(HINSTANCE hLibModule, DWORD dwExitCode)
1658 FreeLibrary(hLibModule);
1659 ExitThread(dwExitCode);
1662 /***********************************************************************
1663 * PrivateLoadLibrary (KERNEL32)
1665 * FIXME: rough guesswork, don't know what "Private" means
1667 HINSTANCE WINAPI PrivateLoadLibrary(LPCSTR libname)
1669 return (HINSTANCE)LoadLibrary16(libname);
1674 /***********************************************************************
1675 * PrivateFreeLibrary (KERNEL32)
1677 * FIXME: rough guesswork, don't know what "Private" means
1679 void WINAPI PrivateFreeLibrary(HINSTANCE handle)
1681 FreeLibrary16((HINSTANCE16)handle);
1685 /***********************************************************************
1686 * WIN32_GetProcAddress16 (KERNEL32.36)
1687 * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
1689 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
1691 WORD ordinal;
1692 FARPROC16 ret;
1694 if (!hModule) {
1695 WARN_(module)("hModule may not be 0!\n");
1696 return (FARPROC16)0;
1698 if (HIWORD(hModule))
1700 WARN_(module)("hModule is Win32 handle (%08x)\n", hModule );
1701 return (FARPROC16)0;
1703 hModule = GetExePtr( hModule );
1704 if (HIWORD(name)) {
1705 ordinal = NE_GetOrdinal( hModule, name );
1706 TRACE_(module)("%04x '%s'\n",
1707 hModule, name );
1708 } else {
1709 ordinal = LOWORD(name);
1710 TRACE_(module)("%04x %04x\n",
1711 hModule, ordinal );
1713 if (!ordinal) return (FARPROC16)0;
1714 ret = NE_GetEntryPoint( hModule, ordinal );
1715 TRACE_(module)("returning %08x\n",(UINT)ret);
1716 return ret;
1719 /***********************************************************************
1720 * GetProcAddress16 (KERNEL.50)
1722 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, SEGPTR name )
1724 WORD ordinal;
1725 FARPROC16 ret;
1727 if (!hModule) hModule = GetCurrentTask();
1728 hModule = GetExePtr( hModule );
1730 if (HIWORD(name) != 0)
1732 ordinal = NE_GetOrdinal( hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1733 TRACE_(module)("%04x '%s'\n",
1734 hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1736 else
1738 ordinal = LOWORD(name);
1739 TRACE_(module)("%04x %04x\n",
1740 hModule, ordinal );
1742 if (!ordinal) return (FARPROC16)0;
1744 ret = NE_GetEntryPoint( hModule, ordinal );
1746 TRACE_(module)("returning %08x\n", (UINT)ret );
1747 return ret;
1751 /***********************************************************************
1752 * GetProcAddress32 (KERNEL32.257)
1754 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1756 return MODULE_GetProcAddress( hModule, function, TRUE );
1759 /***********************************************************************
1760 * WIN16_GetProcAddress32 (KERNEL.453)
1762 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
1764 return MODULE_GetProcAddress( hModule, function, FALSE );
1767 /***********************************************************************
1768 * MODULE_GetProcAddress32 (internal)
1770 FARPROC MODULE_GetProcAddress(
1771 HMODULE hModule, /* [in] current module handle */
1772 LPCSTR function, /* [in] function to be looked up */
1773 BOOL snoop )
1775 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1776 FARPROC retproc;
1778 if (HIWORD(function))
1779 TRACE_(win32)("(%08lx,%s)\n",(DWORD)hModule,function);
1780 else
1781 TRACE_(win32)("(%08lx,%p)\n",(DWORD)hModule,function);
1782 if (!wm) {
1783 SetLastError(ERROR_INVALID_HANDLE);
1784 return (FARPROC)0;
1786 switch (wm->type)
1788 case MODULE32_PE:
1789 retproc = PE_FindExportedFunction( wm, function, snoop );
1790 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1791 return retproc;
1792 case MODULE32_ELF:
1793 retproc = ELF_FindExportedFunction( wm, function);
1794 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1795 return retproc;
1796 default:
1797 ERR_(module)("wine_modref type %d not handled.\n",wm->type);
1798 SetLastError(ERROR_INVALID_HANDLE);
1799 return (FARPROC)0;
1804 /***********************************************************************
1805 * RtlImageNtHeaders (NTDLL)
1807 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
1809 /* basically:
1810 * return hModule+(((IMAGE_DOS_HEADER*)hModule)->e_lfanew);
1811 * but we could get HMODULE16 or the like (think builtin modules)
1814 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1815 if (!wm || (wm->type != MODULE32_PE)) return (PIMAGE_NT_HEADERS)0;
1816 return PE_HEADER(wm->module);
1820 /***************************************************************************
1821 * HasGPHandler (KERNEL.338)
1824 #include "pshpack1.h"
1825 typedef struct _GPHANDLERDEF
1827 WORD selector;
1828 WORD rangeStart;
1829 WORD rangeEnd;
1830 WORD handler;
1831 } GPHANDLERDEF;
1832 #include "poppack.h"
1834 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1836 HMODULE16 hModule;
1837 int gpOrdinal;
1838 SEGPTR gpPtr;
1839 GPHANDLERDEF *gpHandler;
1841 if ( (hModule = FarGetOwner16( SELECTOROF(address) )) != 0
1842 && (gpOrdinal = NE_GetOrdinal( hModule, "__GP" )) != 0
1843 && (gpPtr = (SEGPTR)NE_GetEntryPointEx( hModule, gpOrdinal, FALSE )) != 0
1844 && !IsBadReadPtr16( gpPtr, sizeof(GPHANDLERDEF) )
1845 && (gpHandler = PTR_SEG_TO_LIN( gpPtr )) != NULL )
1847 while (gpHandler->selector)
1849 if ( SELECTOROF(address) == gpHandler->selector
1850 && OFFSETOF(address) >= gpHandler->rangeStart
1851 && OFFSETOF(address) < gpHandler->rangeEnd )
1852 return PTR_SEG_OFF_TO_SEGPTR( gpHandler->selector,
1853 gpHandler->handler );
1854 gpHandler++;
1858 return 0;