Removed MODULE_GetWndProcEntry16().
[wine/wine64.git] / loader / module.c
blob8cd2fbcd5cd2a464fd8587aefb86898fe432cec0
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 "neexe.h"
22 #include "pe_image.h"
23 #include "dosexe.h"
24 #include "process.h"
25 #include "thread.h"
26 #include "selectors.h"
27 #include "stackframe.h"
28 #include "task.h"
29 #include "debugtools.h"
30 #include "callback.h"
31 #include "loadorder.h"
32 #include "elfdll.h"
34 DECLARE_DEBUG_CHANNEL(module)
35 DECLARE_DEBUG_CHANNEL(win32)
37 /*************************************************************************
38 * MODULE_WalkModref
39 * Walk MODREFs for input process ID
41 void MODULE_WalkModref( DWORD id )
43 int i;
44 WINE_MODREF *zwm, *prev = NULL;
45 PDB *pdb = PROCESS_IdToPDB( id );
47 if (!pdb) {
48 MESSAGE("Invalid process id (pid)\n");
49 return;
52 MESSAGE("Modref list for process pdb=%p\n", pdb);
53 MESSAGE("Modref next prev handle deps flags name\n");
54 for ( zwm = pdb->modref_list; zwm; zwm = zwm->next) {
55 MESSAGE("%p %p %p %04x %5d %04x %s\n", zwm, zwm->next, zwm->prev,
56 zwm->module, zwm->nDeps, zwm->flags, zwm->modname);
57 for ( i = 0; i < zwm->nDeps; i++ ) {
58 if ( zwm->deps[i] )
59 MESSAGE(" %d %p %s\n", i, zwm->deps[i], zwm->deps[i]->modname);
61 if (prev != zwm->prev)
62 MESSAGE(" --> modref corrupt, previous pointer wrong!!\n");
63 prev = zwm;
67 /*************************************************************************
68 * MODULE32_LookupHMODULE
69 * looks for the referenced HMODULE in the current process
71 WINE_MODREF *MODULE32_LookupHMODULE( HMODULE hmod )
73 WINE_MODREF *wm;
75 if (!hmod)
76 return PROCESS_Current()->exe_modref;
78 if (!HIWORD(hmod)) {
79 ERR_(module)("tried to lookup 0x%04x in win32 module handler!\n",hmod);
80 return NULL;
82 for ( wm = PROCESS_Current()->modref_list; wm; wm=wm->next )
83 if (wm->module == hmod)
84 return wm;
85 return NULL;
88 /*************************************************************************
89 * MODULE_InitDll
91 static BOOL MODULE_InitDll( WINE_MODREF *wm, DWORD type, LPVOID lpReserved )
93 BOOL retv = TRUE;
95 static LPCSTR typeName[] = { "PROCESS_DETACH", "PROCESS_ATTACH",
96 "THREAD_ATTACH", "THREAD_DETACH" };
97 assert( wm );
100 /* Skip calls for modules loaded with special load flags */
102 if ( ( wm->flags & WINE_MODREF_DONT_RESOLVE_REFS )
103 || ( wm->flags & WINE_MODREF_LOAD_AS_DATAFILE ) )
104 return TRUE;
107 TRACE_(module)("(%s,%s,%p) - CALL\n",
108 wm->modname, typeName[type], lpReserved );
110 /* Call the initialization routine */
111 switch ( wm->type )
113 case MODULE32_PE:
114 retv = PE_InitDLL( wm, type, lpReserved );
115 break;
117 case MODULE32_ELF:
118 /* no need to do that, dlopen() already does */
119 break;
121 default:
122 ERR_(module)("wine_modref type %d not handled.\n", wm->type );
123 retv = FALSE;
124 break;
127 TRACE_(module)("(%s,%s,%p) - RETURN %d\n",
128 wm->modname, typeName[type], lpReserved, retv );
130 return retv;
133 /*************************************************************************
134 * MODULE_DllProcessAttach
136 * Send the process attach notification to all DLLs the given module
137 * depends on (recursively). This is somewhat complicated due to the fact that
139 * - we have to respect the module dependencies, i.e. modules implicitly
140 * referenced by another module have to be initialized before the module
141 * itself can be initialized
143 * - the initialization routine of a DLL can itself call LoadLibrary,
144 * thereby introducing a whole new set of dependencies (even involving
145 * the 'old' modules) at any time during the whole process
147 * (Note that this routine can be recursively entered not only directly
148 * from itself, but also via LoadLibrary from one of the called initialization
149 * routines.)
151 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
152 * the process *detach* notifications to be sent in the correct order.
153 * This must not only take into account module dependencies, but also
154 * 'hidden' dependencies created by modules calling LoadLibrary in their
155 * attach notification routine.
157 * The strategy is rather simple: we move a WINE_MODREF to the head of the
158 * list after the attach notification has returned. This implies that the
159 * detach notifications are called in the reverse of the sequence the attach
160 * notifications *returned*.
162 * NOTE: Assumes that the process critical section is held!
165 BOOL MODULE_DllProcessAttach( WINE_MODREF *wm, LPVOID lpReserved )
167 BOOL retv = TRUE;
168 int i;
169 assert( wm );
171 /* prevent infinite recursion in case of cyclical dependencies */
172 if ( ( wm->flags & WINE_MODREF_MARKER )
173 || ( wm->flags & WINE_MODREF_PROCESS_ATTACHED ) )
174 return retv;
176 TRACE_(module)("(%s,%p) - START\n",
177 wm->modname, lpReserved );
179 /* Tag current MODREF to prevent recursive loop */
180 wm->flags |= WINE_MODREF_MARKER;
182 /* Recursively attach all DLLs this one depends on */
183 for ( i = 0; retv && i < wm->nDeps; i++ )
184 if ( wm->deps[i] )
185 retv = MODULE_DllProcessAttach( wm->deps[i], lpReserved );
187 /* Call DLL entry point */
188 if ( retv )
190 retv = MODULE_InitDll( wm, DLL_PROCESS_ATTACH, lpReserved );
191 if ( retv )
192 wm->flags |= WINE_MODREF_PROCESS_ATTACHED;
195 /* Re-insert MODREF at head of list */
196 if ( retv && wm->prev )
198 wm->prev->next = wm->next;
199 if ( wm->next ) wm->next->prev = wm->prev;
201 wm->prev = NULL;
202 wm->next = PROCESS_Current()->modref_list;
203 PROCESS_Current()->modref_list = wm->next->prev = wm;
206 /* Remove recursion flag */
207 wm->flags &= ~WINE_MODREF_MARKER;
209 TRACE_(module)("(%s,%p) - END\n",
210 wm->modname, lpReserved );
212 return retv;
215 /*************************************************************************
216 * MODULE_DllProcessDetach
218 * Send DLL process detach notifications. See the comment about calling
219 * sequence at MODULE_DllProcessAttach. Unless the bForceDetach flag
220 * is set, only DLLs with zero refcount are notified.
222 * NOTE: Assumes that the process critical section is held!
225 void MODULE_DllProcessDetach( BOOL bForceDetach, LPVOID lpReserved )
227 WINE_MODREF *wm;
231 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
233 /* Check whether to detach this DLL */
234 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
235 continue;
236 if ( wm->refCount > 0 && !bForceDetach )
237 continue;
239 /* Call detach notification */
240 wm->flags &= ~WINE_MODREF_PROCESS_ATTACHED;
241 MODULE_InitDll( wm, DLL_PROCESS_DETACH, lpReserved );
243 /* Restart at head of WINE_MODREF list, as entries might have
244 been added and/or removed while performing the call ... */
245 break;
247 } while ( wm );
250 /*************************************************************************
251 * MODULE_DllThreadAttach
253 * Send DLL thread attach notifications. These are sent in the
254 * reverse sequence of process detach notification.
257 void MODULE_DllThreadAttach( LPVOID lpReserved )
259 WINE_MODREF *wm;
261 EnterCriticalSection( &PROCESS_Current()->crit_section );
263 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
264 if ( !wm->next )
265 break;
267 for ( ; wm; wm = wm->prev )
269 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
270 continue;
271 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
272 continue;
274 MODULE_InitDll( wm, DLL_THREAD_ATTACH, lpReserved );
277 LeaveCriticalSection( &PROCESS_Current()->crit_section );
280 /*************************************************************************
281 * MODULE_DllThreadDetach
283 * Send DLL thread detach notifications. These are sent in the
284 * same sequence as process detach notification.
287 void MODULE_DllThreadDetach( LPVOID lpReserved )
289 WINE_MODREF *wm;
291 EnterCriticalSection( &PROCESS_Current()->crit_section );
293 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
295 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
296 continue;
297 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
298 continue;
300 MODULE_InitDll( wm, DLL_THREAD_DETACH, lpReserved );
303 LeaveCriticalSection( &PROCESS_Current()->crit_section );
306 /****************************************************************************
307 * DisableThreadLibraryCalls (KERNEL32.74)
309 * Don't call DllEntryPoint for DLL_THREAD_{ATTACH,DETACH} if set.
311 BOOL WINAPI DisableThreadLibraryCalls( HMODULE hModule )
313 WINE_MODREF *wm;
314 BOOL retval = TRUE;
316 EnterCriticalSection( &PROCESS_Current()->crit_section );
318 wm = MODULE32_LookupHMODULE( hModule );
319 if ( !wm )
320 retval = FALSE;
321 else
322 wm->flags |= WINE_MODREF_NO_DLL_CALLS;
324 LeaveCriticalSection( &PROCESS_Current()->crit_section );
326 return retval;
330 /***********************************************************************
331 * MODULE_CreateDummyModule
333 * Create a dummy NE module for Win32 or Winelib.
335 HMODULE MODULE_CreateDummyModule( const OFSTRUCT *ofs, LPCSTR modName )
337 HMODULE hModule;
338 NE_MODULE *pModule;
339 SEGTABLEENTRY *pSegment;
340 char *pStr,*s;
341 int len;
342 const char* basename;
344 INT of_size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName)
345 + strlen(ofs->szPathName) + 1;
346 INT size = sizeof(NE_MODULE) +
347 /* loaded file info */
348 of_size +
349 /* segment table: DS,CS */
350 2 * sizeof(SEGTABLEENTRY) +
351 /* name table */
353 /* several empty tables */
356 hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
357 if (!hModule) return (HMODULE)11; /* invalid exe */
359 FarSetOwner16( hModule, hModule );
360 pModule = (NE_MODULE *)GlobalLock16( hModule );
362 /* Set all used entries */
363 pModule->magic = IMAGE_OS2_SIGNATURE;
364 pModule->count = 1;
365 pModule->next = 0;
366 pModule->flags = 0;
367 pModule->dgroup = 0;
368 pModule->ss = 1;
369 pModule->cs = 2;
370 pModule->heap_size = 0;
371 pModule->stack_size = 0;
372 pModule->seg_count = 2;
373 pModule->modref_count = 0;
374 pModule->nrname_size = 0;
375 pModule->fileinfo = sizeof(NE_MODULE);
376 pModule->os_flags = NE_OSFLAGS_WINDOWS;
377 pModule->expected_version = 0x030a;
378 pModule->self = hModule;
380 /* Set loaded file information */
381 memcpy( pModule + 1, ofs, of_size );
382 ((OFSTRUCT *)(pModule+1))->cBytes = of_size - 1;
384 pSegment = (SEGTABLEENTRY*)((char*)(pModule + 1) + of_size);
385 pModule->seg_table = (int)pSegment - (int)pModule;
386 /* Data segment */
387 pSegment->size = 0;
388 pSegment->flags = NE_SEGFLAGS_DATA;
389 pSegment->minsize = 0x1000;
390 pSegment++;
391 /* Code segment */
392 pSegment->flags = 0;
393 pSegment++;
395 /* Module name */
396 pStr = (char *)pSegment;
397 pModule->name_table = (int)pStr - (int)pModule;
398 if ( modName )
399 basename = modName;
400 else
402 basename = strrchr(ofs->szPathName,'\\');
403 if (!basename) basename = ofs->szPathName;
404 else basename++;
406 len = strlen(basename);
407 if ((s = strchr(basename,'.'))) len = s - basename;
408 if (len > 8) len = 8;
409 *pStr = len;
410 strncpy( pStr+1, basename, len );
411 if (len < 8) pStr[len+1] = 0;
412 pStr += 9;
414 /* All tables zero terminated */
415 pModule->res_table = pModule->import_table = pModule->entry_table =
416 (int)pStr - (int)pModule;
418 NE_RegisterModule( pModule );
419 return hModule;
423 /**********************************************************************
424 * MODULE_FindModule32
426 * Find a (loaded) win32 module depending on path
427 * The handling of '.' is a bit weird, but we need it that way,
428 * for sometimes the programs use '<name>.exe' and '<name>.dll' and
429 * this is the only way to differentiate. (mainly hypertrm.exe)
431 * RETURNS
432 * the module handle if found
433 * 0 if not
435 WINE_MODREF *MODULE_FindModule(
436 LPCSTR path /* [in] pathname of module/library to be found */
438 LPSTR filename;
439 LPSTR dotptr;
440 WINE_MODREF *wm;
442 if (!(filename = strrchr( path, '\\' )))
443 filename = HEAP_strdupA( GetProcessHeap(), 0, path );
444 else
445 filename = HEAP_strdupA( GetProcessHeap(), 0, filename+1 );
446 dotptr=strrchr(filename,'.');
448 for ( wm = PROCESS_Current()->modref_list; wm; wm=wm->next ) {
449 LPSTR xmodname,xdotptr;
451 assert (wm->modname);
452 xmodname = HEAP_strdupA( GetProcessHeap(), 0, wm->modname );
453 xdotptr=strrchr(xmodname,'.');
454 if ( (xdotptr && !dotptr) ||
455 (!xdotptr && dotptr)
457 if (dotptr) *dotptr = '\0';
458 if (xdotptr) *xdotptr = '\0';
460 if (!strcasecmp( filename, xmodname)) {
461 HeapFree( GetProcessHeap(), 0, filename );
462 HeapFree( GetProcessHeap(), 0, xmodname );
463 return wm;
465 if (dotptr) *dotptr='.';
466 /* FIXME: add paths, shortname */
467 HeapFree( GetProcessHeap(), 0, xmodname );
469 /* if that fails, try looking for the filename... */
470 for ( wm = PROCESS_Current()->modref_list; wm; wm=wm->next ) {
471 LPSTR xlname,xdotptr;
473 assert (wm->longname);
474 xlname = strrchr(wm->longname,'\\');
475 if (!xlname)
476 xlname = wm->longname;
477 else
478 xlname++;
479 xlname = HEAP_strdupA( GetProcessHeap(), 0, xlname );
480 xdotptr=strrchr(xlname,'.');
481 if ( (xdotptr && !dotptr) ||
482 (!xdotptr && dotptr)
484 if (dotptr) *dotptr = '\0';
485 if (xdotptr) *xdotptr = '\0';
487 if (!strcasecmp( filename, xlname)) {
488 HeapFree( GetProcessHeap(), 0, filename );
489 HeapFree( GetProcessHeap(), 0, xlname );
490 return wm;
492 if (dotptr) *dotptr='.';
493 /* FIXME: add paths, shortname */
494 HeapFree( GetProcessHeap(), 0, xlname );
496 HeapFree( GetProcessHeap(), 0, filename );
497 return NULL;
500 /***********************************************************************
501 * MODULE_GetBinaryType
503 * The GetBinaryType function determines whether a file is executable
504 * or not and if it is it returns what type of executable it is.
505 * The type of executable is a property that determines in which
506 * subsystem an executable file runs under.
508 * Binary types returned:
509 * SCS_32BIT_BINARY: A Win32 based application
510 * SCS_DOS_BINARY: An MS-Dos based application
511 * SCS_WOW_BINARY: A Win16 based application
512 * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
513 * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
514 * SCS_OS216_BINARY: A 16bit OS/2 based application
516 * Returns TRUE if the file is an executable in which case
517 * the value pointed by lpBinaryType is set.
518 * Returns FALSE if the file is not an executable or if the function fails.
520 * To do so it opens the file and reads in the header information
521 * if the extended header information is not presend it will
522 * assume that that the file is a DOS executable.
523 * If the extended header information is present it will
524 * determine if the file is an 16 or 32 bit Windows executable
525 * by check the flags in the header.
527 * Note that .COM and .PIF files are only recognized by their
528 * file name extension; but Windows does it the same way ...
530 static BOOL MODULE_GetBinaryType( HFILE hfile, OFSTRUCT *ofs,
531 LPDWORD lpBinaryType )
533 IMAGE_DOS_HEADER mz_header;
534 char magic[4], *ptr;
536 /* Seek to the start of the file and read the DOS header information.
538 if ( _llseek( hfile, 0, SEEK_SET ) >= 0 &&
539 _lread( hfile, &mz_header, sizeof(mz_header) ) == sizeof(mz_header) )
541 /* Now that we have the header check the e_magic field
542 * to see if this is a dos image.
544 if ( mz_header.e_magic == IMAGE_DOS_SIGNATURE )
546 BOOL lfanewValid = FALSE;
547 /* We do have a DOS image so we will now try to seek into
548 * the file by the amount indicated by the field
549 * "Offset to extended header" and read in the
550 * "magic" field information at that location.
551 * This will tell us if there is more header information
552 * to read or not.
554 /* But before we do we will make sure that header
555 * structure encompasses the "Offset to extended header"
556 * field.
558 if ( (mz_header.e_cparhdr<<4) >= sizeof(IMAGE_DOS_HEADER) )
559 if ( ( mz_header.e_crlc == 0 && mz_header.e_lfarlc == 0 ) ||
560 ( mz_header.e_lfarlc >= sizeof(IMAGE_DOS_HEADER) ) )
561 if ( mz_header.e_lfanew >= sizeof(IMAGE_DOS_HEADER) &&
562 _llseek( hfile, mz_header.e_lfanew, SEEK_SET ) >= 0 &&
563 _lread( hfile, magic, sizeof(magic) ) == sizeof(magic) )
564 lfanewValid = TRUE;
566 if ( !lfanewValid )
568 /* If we cannot read this "extended header" we will
569 * assume that we have a simple DOS executable.
571 *lpBinaryType = SCS_DOS_BINARY;
572 return TRUE;
574 else
576 /* Reading the magic field succeeded so
577 * we will try to determine what type it is.
579 if ( *(DWORD*)magic == IMAGE_NT_SIGNATURE )
581 /* This is an NT signature.
583 *lpBinaryType = SCS_32BIT_BINARY;
584 return TRUE;
586 else if ( *(WORD*)magic == IMAGE_OS2_SIGNATURE )
588 /* The IMAGE_OS2_SIGNATURE indicates that the
589 * "extended header is a Windows executable (NE)
590 * header." This can mean either a 16-bit OS/2
591 * or a 16-bit Windows or even a DOS program
592 * (running under a DOS extender). To decide
593 * which, we'll have to read the NE header.
596 IMAGE_OS2_HEADER ne;
597 if ( _llseek( hfile, mz_header.e_lfanew, SEEK_SET ) >= 0 &&
598 _lread( hfile, &ne, sizeof(ne) ) == sizeof(ne) )
600 switch ( ne.operating_system )
602 case 2: *lpBinaryType = SCS_WOW_BINARY; return TRUE;
603 case 5: *lpBinaryType = SCS_DOS_BINARY; return TRUE;
604 default: *lpBinaryType = SCS_OS216_BINARY; return TRUE;
607 /* Couldn't read header, so abort. */
608 return FALSE;
610 else
612 /* Unknown extended header, so abort.
614 return FALSE;
620 /* If we get here, we don't even have a correct MZ header.
621 * Try to check the file extension for known types ...
623 ptr = strrchr( ofs->szPathName, '.' );
624 if ( ptr && !strchr( ptr, '\\' ) && !strchr( ptr, '/' ) )
626 if ( !lstrcmpiA( ptr, ".COM" ) )
628 *lpBinaryType = SCS_DOS_BINARY;
629 return TRUE;
632 if ( !lstrcmpiA( ptr, ".PIF" ) )
634 *lpBinaryType = SCS_PIF_BINARY;
635 return TRUE;
639 return FALSE;
642 /***********************************************************************
643 * GetBinaryTypeA [KERNEL32.280]
645 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
647 BOOL ret = FALSE;
648 HFILE hfile;
649 OFSTRUCT ofs;
651 TRACE_(win32)("%s\n", lpApplicationName );
653 /* Sanity check.
655 if ( lpApplicationName == NULL || lpBinaryType == NULL )
656 return FALSE;
658 /* Open the file indicated by lpApplicationName for reading.
660 if ( (hfile = OpenFile( lpApplicationName, &ofs, OF_READ )) == HFILE_ERROR )
661 return FALSE;
663 /* Check binary type
665 ret = MODULE_GetBinaryType( hfile, &ofs, lpBinaryType );
667 /* Close the file.
669 CloseHandle( hfile );
671 return ret;
674 /***********************************************************************
675 * GetBinaryTypeW [KERNEL32.281]
677 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
679 BOOL ret = FALSE;
680 LPSTR strNew = NULL;
682 TRACE_(win32)("%s\n", debugstr_w(lpApplicationName) );
684 /* Sanity check.
686 if ( lpApplicationName == NULL || lpBinaryType == NULL )
687 return FALSE;
689 /* Convert the wide string to a ascii string.
691 strNew = HEAP_strdupWtoA( GetProcessHeap(), 0, lpApplicationName );
693 if ( strNew != NULL )
695 ret = GetBinaryTypeA( strNew, lpBinaryType );
697 /* Free the allocated string.
699 HeapFree( GetProcessHeap(), 0, strNew );
702 return ret;
705 /**********************************************************************
706 * MODULE_CreateUnixProcess
708 static BOOL MODULE_CreateUnixProcess( LPCSTR filename, LPCSTR lpCmdLine,
709 LPSTARTUPINFOA lpStartupInfo,
710 LPPROCESS_INFORMATION lpProcessInfo,
711 BOOL useWine )
713 DOS_FULL_NAME full_name;
714 const char *unixfilename = filename;
715 const char *argv[256], **argptr;
716 BOOL iconic = FALSE;
718 /* Get Unix file name and iconic flag */
720 if ( lpStartupInfo->dwFlags & STARTF_USESHOWWINDOW )
721 if ( lpStartupInfo->wShowWindow == SW_SHOWMINIMIZED
722 || lpStartupInfo->wShowWindow == SW_SHOWMINNOACTIVE )
723 iconic = TRUE;
725 /* Build argument list */
727 argptr = argv;
728 if ( !useWine )
730 char *p = strdup(lpCmdLine);
731 if ( strchr(filename, '/')
732 || strchr(filename, ':')
733 || strchr(filename, '\\') )
735 if ( DOSFS_GetFullName( filename, TRUE, &full_name ) )
736 unixfilename = full_name.long_name;
738 *argptr++ = unixfilename;
739 if (iconic) *argptr++ = "-iconic";
740 while (1)
742 while (*p && (*p == ' ' || *p == '\t')) *p++ = '\0';
743 if (!*p) break;
744 *argptr++ = p;
745 while (*p && *p != ' ' && *p != '\t') p++;
747 free (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;
779 SetLastError( ERROR_SUCCESS );
780 return TRUE;
783 /***********************************************************************
784 * WinExec16 (KERNEL.166)
786 HINSTANCE16 WINAPI WinExec16( LPCSTR lpCmdLine, UINT16 nCmdShow )
788 HINSTANCE16 hInst;
790 SYSLEVEL_ReleaseWin16Lock();
791 hInst = WinExec( lpCmdLine, nCmdShow );
792 SYSLEVEL_RestoreWin16Lock();
794 return hInst;
797 /***********************************************************************
798 * WinExec (KERNEL32.566)
800 HINSTANCE WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
802 LOADPARAMS params;
803 UINT16 paramCmdShow[2];
805 if (!lpCmdLine)
806 return 2; /* File not found */
808 /* Set up LOADPARAMS buffer for LoadModule */
810 memset( &params, '\0', sizeof(params) );
811 params.lpCmdLine = (LPSTR)lpCmdLine;
812 params.lpCmdShow = paramCmdShow;
813 params.lpCmdShow[0] = 2;
814 params.lpCmdShow[1] = nCmdShow;
816 /* Now load the executable file */
818 return LoadModule( NULL, &params );
821 /**********************************************************************
822 * LoadModule (KERNEL32.499)
824 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
826 LOADPARAMS *params = (LOADPARAMS *)paramBlock;
827 PROCESS_INFORMATION info;
828 STARTUPINFOA startup;
829 HINSTANCE hInstance;
830 PDB *pdb;
831 TDB *tdb;
833 memset( &startup, '\0', sizeof(startup) );
834 startup.cb = sizeof(startup);
835 startup.dwFlags = STARTF_USESHOWWINDOW;
836 startup.wShowWindow = params->lpCmdShow? params->lpCmdShow[1] : 0;
838 if ( !CreateProcessA( name, params->lpCmdLine,
839 NULL, NULL, FALSE, 0, params->lpEnvAddress,
840 NULL, &startup, &info ) )
842 hInstance = GetLastError();
843 if ( hInstance < 32 ) return hInstance;
845 FIXME_(module)("Strange error set by CreateProcess: %d\n", hInstance );
846 return 11;
849 /* Get 16-bit hInstance/hTask from process */
850 pdb = PROCESS_IdToPDB( info.dwProcessId );
851 tdb = pdb? (TDB *)GlobalLock16( pdb->task ) : NULL;
852 hInstance = tdb && tdb->hInstance? tdb->hInstance : pdb? pdb->task : 0;
853 /* If there is no hInstance (32-bit process) return a dummy value
854 * that must be > 31
855 * FIXME: should do this in all cases and fix Win16 callers */
856 if (!hInstance) hInstance = 33;
858 /* Close off the handles */
859 CloseHandle( info.hThread );
860 CloseHandle( info.hProcess );
862 return hInstance;
865 /*************************************************************************
866 * get_makename_token
868 * Get next blank delimited token from input string. If quoted then
869 * process till matching quote and then till blank.
871 * Returns number of characters in token (not including \0). On
872 * end of string (EOS), returns a 0.
874 * from (IO) address of start of input string to scan, updated to
875 * next non-processed character.
876 * to (IO) address of start of output string (previous token \0
877 * char), updated to end of new output string (the \0
878 * char).
880 static int get_makename_token(LPCSTR *from, LPSTR *to )
882 int len = 0;
883 LPCSTR to_old = *to; /* only used for tracing */
885 while ( **from == ' ') {
886 /* Copy leading blanks (separators between previous */
887 /* token and this token). */
888 **to = **from;
889 (*from)++;
890 (*to)++;
891 len++;
893 do {
894 while ( (**from != 0) && (**from != ' ') && (**from != '"') ) {
895 **to = **from; (*from)++; (*to)++; len++;
897 if ( **from == '"' ) {
898 /* Handle quoted string. */
899 (*from)++;
900 if ( !strchr(*from, '"') ) {
901 /* fail - no closing quote. Return entire string */
902 while ( **from != 0 ) {
903 **to = **from; (*from)++; (*to)++; len++;
905 break;
907 while( **from != '"') {
908 **to = **from;
909 len++;
910 (*to)++;
911 (*from)++;
913 (*from)++;
914 continue;
917 /* either EOS or ' ' */
918 break;
920 } while (1);
922 **to = 0; /* terminate output string */
924 TRACE_(module)("returning token len=%d, string=%s\n",
925 len, to_old);
927 return len;
930 /*************************************************************************
931 * make_lpCommandLine_name
933 * Try longer and longer strings from "line" to find an existing
934 * file name. Each attempt is delimited by a blank outside of quotes.
935 * Also will attempt to append ".exe" if requested and not already
936 * present. Returns the address of the remaining portion of the
937 * input line.
941 static BOOL make_lpCommandLine_name( LPCSTR line, LPSTR name, int namelen,
942 LPCSTR *after )
944 BOOL found = TRUE;
945 LPCSTR from;
946 char buffer[260];
947 DWORD retlen;
948 LPSTR to, lastpart;
950 from = line;
951 to = name;
953 /* scan over initial blanks if any */
954 while ( *from == ' ') from++;
956 /* get a token and append to previous data the check for existance */
957 do {
958 if ( !get_makename_token( &from, &to ) ) {
959 /* EOS has occured and not found - exit */
960 retlen = 0;
961 found = FALSE;
962 break;
964 TRACE_(module)("checking if file exists '%s'\n", name);
965 retlen = SearchPathA( NULL, name, ".exe", sizeof(buffer), buffer, &lastpart);
966 if ( retlen && (retlen < sizeof(buffer)) ) break;
967 } while (1);
969 /* if we have a non-null full path name in buffer then move to output */
970 if ( retlen ) {
971 if ( strlen(buffer) <= namelen ) {
972 strcpy( name, buffer );
973 } else {
974 /* not enough space to return full path string */
975 FIXME_(module)("internal string not long enough, need %d\n",
976 strlen(buffer) );
980 /* all done, indicate end of module name and then trace and exit */
981 if (after) *after = from;
982 TRACE_(module)("%i, selected file name '%s'\n and cmdline as %s\n",
983 found, name, debugstr_a(from));
984 return found;
987 /*************************************************************************
988 * make_lpApplicationName_name
990 * Scan input string (the lpApplicationName) and remove any quotes
991 * if they are balanced.
995 static BOOL make_lpApplicationName_name( LPCSTR line, LPSTR name, int namelen)
997 LPCSTR from;
998 LPSTR to, to_end, to_old;
999 DOS_FULL_NAME full_name;
1001 to = name;
1002 to_end = to + namelen - 1;
1003 to_old = to;
1005 while ( *line == ' ' ) line++; /* point to beginning of string */
1006 from = line;
1007 do {
1008 /* Copy all input till end, or quote */
1009 while((*from != 0) && (*from != '"') && (to < to_end))
1010 *to++ = *from++;
1011 if (to >= to_end) { *to = 0; break; }
1013 if (*from == '"')
1015 /* Handle quoted string. If there is a closing quote, copy all */
1016 /* that is inside. */
1017 from++;
1018 if (!strchr(from, '"'))
1020 /* fail - no closing quote */
1021 to = to_old; /* restore to previous attempt */
1022 *to = 0; /* end string */
1023 break; /* exit with previous attempt */
1025 while((*from != '"') && (to < to_end)) *to++ = *from++;
1026 if (to >= to_end) { *to = 0; break; }
1027 from++;
1028 continue; /* past quoted string, so restart from top */
1031 *to = 0; /* terminate output string */
1032 to_old = to; /* save for possible use in unmatched quote case */
1034 /* loop around keeping the blank as part of file name */
1035 if (!*from)
1036 break; /* exit if out of input string */
1037 } while (1);
1039 if (!DOSFS_GetFullName(name, TRUE, &full_name)) {
1040 TRACE_(module)("file not found '%s'\n", name );
1041 return FALSE;
1044 if (strlen(full_name.long_name) >= namelen ) {
1045 FIXME_(module)("name longer than buffer (len=%d), file=%s\n",
1046 namelen, full_name.long_name);
1047 return FALSE;
1049 strcpy(name, full_name.long_name);
1051 TRACE_(module)("selected as file name '%s'\n", name );
1052 return TRUE;
1055 /**********************************************************************
1056 * CreateProcessA (KERNEL32.171)
1058 BOOL WINAPI CreateProcessA( LPCSTR lpApplicationName, LPSTR lpCommandLine,
1059 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1060 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1061 BOOL bInheritHandles, DWORD dwCreationFlags,
1062 LPVOID lpEnvironment, LPCSTR lpCurrentDirectory,
1063 LPSTARTUPINFOA lpStartupInfo,
1064 LPPROCESS_INFORMATION lpProcessInfo )
1066 BOOL retv = FALSE;
1067 BOOL found_file = FALSE;
1068 HFILE hFile;
1069 OFSTRUCT ofs;
1070 DWORD type;
1071 char name[256], dummy[256];
1072 LPCSTR cmdline = NULL;
1073 LPSTR tidy_cmdline;
1074 int len = 0;
1076 /* Get name and command line */
1078 if (!lpApplicationName && !lpCommandLine)
1080 SetLastError( ERROR_FILE_NOT_FOUND );
1081 return FALSE;
1084 /* Process the AppName and/or CmdLine to get module name and path */
1086 name[0] = '\0';
1088 if (lpApplicationName) {
1089 found_file = make_lpApplicationName_name( lpApplicationName, name, sizeof(name) );
1090 if (lpCommandLine) {
1091 make_lpCommandLine_name( lpCommandLine, dummy, sizeof ( dummy ), &cmdline );
1093 else {
1094 cmdline = lpApplicationName;
1096 len += strlen(lpApplicationName);
1098 else {
1099 found_file = make_lpCommandLine_name( lpCommandLine, name, sizeof ( name ), &cmdline );
1100 if (lpCommandLine) len = strlen(lpCommandLine);
1103 if ( !found_file ) {
1104 /* make an early exit if file not found - save second pass */
1105 SetLastError( ERROR_FILE_NOT_FOUND );
1106 return FALSE;
1109 len += strlen(name) + 2;
1110 tidy_cmdline = HeapAlloc( GetProcessHeap(), 0, len );
1111 sprintf( tidy_cmdline, "\"%s\"%s", name, cmdline);
1113 /* Warn if unsupported features are used */
1115 if (dwCreationFlags & CREATE_SUSPENDED)
1116 FIXME_(module)("(%s,...): CREATE_SUSPENDED ignored\n", name);
1117 if (dwCreationFlags & DETACHED_PROCESS)
1118 FIXME_(module)("(%s,...): DETACHED_PROCESS ignored\n", name);
1119 if (dwCreationFlags & CREATE_NEW_CONSOLE)
1120 FIXME_(module)("(%s,...): CREATE_NEW_CONSOLE ignored\n", name);
1121 if (dwCreationFlags & NORMAL_PRIORITY_CLASS)
1122 FIXME_(module)("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
1123 if (dwCreationFlags & IDLE_PRIORITY_CLASS)
1124 FIXME_(module)("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
1125 if (dwCreationFlags & HIGH_PRIORITY_CLASS)
1126 FIXME_(module)("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
1127 if (dwCreationFlags & REALTIME_PRIORITY_CLASS)
1128 FIXME_(module)("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
1129 if (dwCreationFlags & CREATE_NEW_PROCESS_GROUP)
1130 FIXME_(module)("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
1131 if (dwCreationFlags & CREATE_UNICODE_ENVIRONMENT)
1132 FIXME_(module)("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
1133 if (dwCreationFlags & CREATE_SEPARATE_WOW_VDM)
1134 FIXME_(module)("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
1135 if (dwCreationFlags & CREATE_SHARED_WOW_VDM)
1136 FIXME_(module)("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
1137 if (dwCreationFlags & CREATE_DEFAULT_ERROR_MODE)
1138 FIXME_(module)("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
1139 if (dwCreationFlags & CREATE_NO_WINDOW)
1140 FIXME_(module)("(%s,...): CREATE_NO_WINDOW ignored\n", name);
1141 if (dwCreationFlags & PROFILE_USER)
1142 FIXME_(module)("(%s,...): PROFILE_USER ignored\n", name);
1143 if (dwCreationFlags & PROFILE_KERNEL)
1144 FIXME_(module)("(%s,...): PROFILE_KERNEL ignored\n", name);
1145 if (dwCreationFlags & PROFILE_SERVER)
1146 FIXME_(module)("(%s,...): PROFILE_SERVER ignored\n", name);
1147 if (lpCurrentDirectory)
1148 FIXME_(module)("(%s,...): lpCurrentDirectory %s ignored\n",
1149 name, lpCurrentDirectory);
1150 if (lpStartupInfo->lpDesktop)
1151 FIXME_(module)("(%s,...): lpStartupInfo->lpDesktop %s ignored\n",
1152 name, lpStartupInfo->lpDesktop);
1153 if (lpStartupInfo->lpTitle)
1154 FIXME_(module)("(%s,...): lpStartupInfo->lpTitle %s ignored\n",
1155 name, lpStartupInfo->lpTitle);
1156 if (lpStartupInfo->dwFlags & STARTF_USECOUNTCHARS)
1157 FIXME_(module)("(%s,...): STARTF_USECOUNTCHARS (%ld,%ld) ignored\n",
1158 name, lpStartupInfo->dwXCountChars, lpStartupInfo->dwYCountChars);
1159 if (lpStartupInfo->dwFlags & STARTF_USEFILLATTRIBUTE)
1160 FIXME_(module)("(%s,...): STARTF_USEFILLATTRIBUTE %lx ignored\n",
1161 name, lpStartupInfo->dwFillAttribute);
1162 if (lpStartupInfo->dwFlags & STARTF_RUNFULLSCREEN)
1163 FIXME_(module)("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
1164 if (lpStartupInfo->dwFlags & STARTF_FORCEONFEEDBACK)
1165 FIXME_(module)("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
1166 if (lpStartupInfo->dwFlags & STARTF_FORCEOFFFEEDBACK)
1167 FIXME_(module)("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
1168 if (lpStartupInfo->dwFlags & STARTF_USEHOTKEY)
1169 FIXME_(module)("(%s,...): STARTF_USEHOTKEY ignored\n", name);
1171 /* When in WineLib, always fork new Unix process */
1173 if ( __winelib ) {
1174 retv = MODULE_CreateUnixProcess( name, tidy_cmdline,
1175 lpStartupInfo, lpProcessInfo, TRUE );
1176 HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1177 return (retv);
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 * LoadLibraryEx32W (KERNEL.513)
1368 HMODULE WINAPI LoadLibraryEx32W16( LPCSTR libname, HANDLE16 hf,
1369 DWORD flags )
1371 HMODULE hModule;
1373 SYSLEVEL_ReleaseWin16Lock();
1374 hModule = LoadLibraryExA( libname, hf, flags );
1375 SYSLEVEL_RestoreWin16Lock();
1377 return hModule;
1380 /***********************************************************************
1381 * LoadLibrary32_16 (KERNEL.452)
1383 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
1385 return LoadLibraryEx32W16( libname, 0, 0 );
1388 /***********************************************************************
1389 * LoadLibraryExA (KERNEL32)
1391 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HFILE hfile, DWORD flags)
1393 WINE_MODREF *wm;
1395 if(!libname)
1397 SetLastError(ERROR_INVALID_PARAMETER);
1398 return 0;
1401 EnterCriticalSection(&PROCESS_Current()->crit_section);
1403 wm = MODULE_LoadLibraryExA( libname, hfile, flags );
1405 if(wm && !MODULE_DllProcessAttach(wm, NULL))
1407 WARN_(module)("Attach failed for module '%s', \n", libname);
1408 MODULE_FreeLibrary(wm);
1409 SetLastError(ERROR_DLL_INIT_FAILED);
1410 wm = NULL;
1413 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1415 return wm ? wm->module : 0;
1418 /***********************************************************************
1419 * MODULE_LoadLibraryExA (internal)
1421 * Load a PE style module according to the load order.
1423 * The HFILE parameter is not used and marked reserved in the SDK. I can
1424 * only guess that it should force a file to be mapped, but I rather
1425 * ignore the parameter because it would be extremely difficult to
1426 * integrate this with different types of module represenations.
1429 WINE_MODREF *MODULE_LoadLibraryExA( LPCSTR libname, HFILE hfile, DWORD flags )
1431 DWORD err;
1432 WINE_MODREF *pwm;
1433 int i;
1434 module_loadorder_t *plo;
1436 EnterCriticalSection(&PROCESS_Current()->crit_section);
1438 /* Check for already loaded module */
1439 if((pwm = MODULE_FindModule(libname)))
1441 if(!(pwm->flags & WINE_MODREF_MARKER))
1442 pwm->refCount++;
1443 TRACE_(module)("Already loaded module '%s' at 0x%08x, count=%d, \n", libname, pwm->module, pwm->refCount);
1444 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1445 return pwm;
1448 plo = MODULE_GetLoadOrder(libname);
1450 for(i = 0; i < MODULE_LOADORDER_NTYPES; i++)
1452 switch(plo->loadorder[i])
1454 case MODULE_LOADORDER_DLL:
1455 TRACE_(module)("Trying native dll '%s'\n", libname);
1456 pwm = PE_LoadLibraryExA(libname, flags, &err);
1457 break;
1459 case MODULE_LOADORDER_ELFDLL:
1460 TRACE_(module)("Trying elfdll '%s'\n", libname);
1461 pwm = ELFDLL_LoadLibraryExA(libname, flags, &err);
1462 break;
1464 case MODULE_LOADORDER_SO:
1465 TRACE_(module)("Trying so-library '%s'\n", libname);
1466 pwm = ELF_LoadLibraryExA(libname, flags, &err);
1467 break;
1469 case MODULE_LOADORDER_BI:
1470 TRACE_(module)("Trying built-in '%s'\n", libname);
1471 pwm = BUILTIN32_LoadLibraryExA(libname, flags, &err);
1472 break;
1474 default:
1475 ERR_(module)("Got invalid loadorder type %d (%s index %d)\n", plo->loadorder[i], plo->modulename, i);
1476 /* Fall through */
1478 case MODULE_LOADORDER_INVALID: /* We ignore this as it is an empty entry */
1479 pwm = NULL;
1480 break;
1483 if(pwm)
1485 /* Initialize DLL just loaded */
1486 TRACE_(module)("Loaded module '%s' at 0x%08x, \n", libname, pwm->module);
1488 /* Set the refCount here so that an attach failure will */
1489 /* decrement the dependencies through the MODULE_FreeLibrary call. */
1490 pwm->refCount++;
1492 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1494 if (PROCESS_Current()->flags & PDB32_DEBUGGED)
1495 DEBUG_SendLoadDLLEvent( -1 /*FIXME*/, pwm->module, pwm->modname );
1497 return pwm;
1500 if(err != ERROR_FILE_NOT_FOUND)
1501 break;
1504 ERR_(module)("Failed to load module '%s'; error=0x%08lx, \n", libname, err);
1505 SetLastError(err);
1506 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1507 return NULL;
1510 /***********************************************************************
1511 * LoadLibraryA (KERNEL32)
1513 HMODULE WINAPI LoadLibraryA(LPCSTR libname) {
1514 return LoadLibraryExA(libname,0,0);
1517 /***********************************************************************
1518 * LoadLibraryW (KERNEL32)
1520 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
1522 return LoadLibraryExW(libnameW,0,0);
1525 /***********************************************************************
1526 * LoadLibraryExW (KERNEL32)
1528 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW,HFILE hfile,DWORD flags)
1530 LPSTR libnameA = HEAP_strdupWtoA( GetProcessHeap(), 0, libnameW );
1531 HMODULE ret = LoadLibraryExA( libnameA , hfile, flags );
1533 HeapFree( GetProcessHeap(), 0, libnameA );
1534 return ret;
1537 /***********************************************************************
1538 * MODULE_FlushModrefs
1540 * NOTE: Assumes that the process critical section is held!
1542 * Remove all unused modrefs and call the internal unloading routines
1543 * for the library type.
1545 static void MODULE_FlushModrefs(void)
1547 WINE_MODREF *wm, *next;
1549 for(wm = PROCESS_Current()->modref_list; wm; wm = next)
1551 next = wm->next;
1553 if(wm->refCount)
1554 continue;
1556 /* Unlink this modref from the chain */
1557 if(wm->next)
1558 wm->next->prev = wm->prev;
1559 if(wm->prev)
1560 wm->prev->next = wm->next;
1561 if(wm == PROCESS_Current()->modref_list)
1562 PROCESS_Current()->modref_list = wm->next;
1565 * The unloaders are also responsible for freeing the modref itself
1566 * because the loaders were responsible for allocating it.
1568 switch(wm->type)
1570 case MODULE32_PE: PE_UnloadLibrary(wm); break;
1571 case MODULE32_ELF: ELF_UnloadLibrary(wm); break;
1572 case MODULE32_ELFDLL: ELFDLL_UnloadLibrary(wm); break;
1573 case MODULE32_BI: BUILTIN32_UnloadLibrary(wm); break;
1575 default:
1576 ERR_(module)("Invalid or unhandled MODREF type %d encountered (wm=%p)\n", wm->type, wm);
1581 /***********************************************************************
1582 * FreeLibrary
1584 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
1586 BOOL retv = FALSE;
1587 WINE_MODREF *wm;
1589 EnterCriticalSection( &PROCESS_Current()->crit_section );
1590 PROCESS_Current()->free_lib_count++;
1592 wm = MODULE32_LookupHMODULE( hLibModule );
1593 if ( !wm || !hLibModule )
1594 SetLastError( ERROR_INVALID_HANDLE );
1595 else
1596 retv = MODULE_FreeLibrary( wm );
1598 PROCESS_Current()->free_lib_count--;
1599 LeaveCriticalSection( &PROCESS_Current()->crit_section );
1601 return retv;
1604 /***********************************************************************
1605 * MODULE_DecRefCount
1607 * NOTE: Assumes that the process critical section is held!
1609 static void MODULE_DecRefCount( WINE_MODREF *wm )
1611 int i;
1613 if ( wm->flags & WINE_MODREF_MARKER )
1614 return;
1616 if ( wm->refCount <= 0 )
1617 return;
1619 --wm->refCount;
1620 TRACE_(module)("(%s) refCount: %d\n", wm->modname, wm->refCount );
1622 if ( wm->refCount == 0 )
1624 wm->flags |= WINE_MODREF_MARKER;
1626 for ( i = 0; i < wm->nDeps; i++ )
1627 if ( wm->deps[i] )
1628 MODULE_DecRefCount( wm->deps[i] );
1630 wm->flags &= ~WINE_MODREF_MARKER;
1634 /***********************************************************************
1635 * MODULE_FreeLibrary
1637 * NOTE: Assumes that the process critical section is held!
1639 BOOL MODULE_FreeLibrary( WINE_MODREF *wm )
1641 TRACE_(module)("(%s) - START\n", wm->modname );
1643 /* Recursively decrement reference counts */
1644 MODULE_DecRefCount( wm );
1646 /* Call process detach notifications */
1647 if ( PROCESS_Current()->free_lib_count <= 1 )
1649 MODULE_DllProcessDetach( FALSE, NULL );
1650 if (PROCESS_Current()->flags & PDB32_DEBUGGED)
1651 DEBUG_SendUnloadDLLEvent( wm->module );
1654 MODULE_FlushModrefs();
1656 TRACE_(module)("(%s) - END\n", wm->modname );
1658 return TRUE;
1662 /***********************************************************************
1663 * FreeLibraryAndExitThread
1665 VOID WINAPI FreeLibraryAndExitThread(HINSTANCE hLibModule, DWORD dwExitCode)
1667 FreeLibrary(hLibModule);
1668 ExitThread(dwExitCode);
1671 /***********************************************************************
1672 * PrivateLoadLibrary (KERNEL32)
1674 * FIXME: rough guesswork, don't know what "Private" means
1676 HINSTANCE WINAPI PrivateLoadLibrary(LPCSTR libname)
1678 return (HINSTANCE)LoadLibrary16(libname);
1683 /***********************************************************************
1684 * PrivateFreeLibrary (KERNEL32)
1686 * FIXME: rough guesswork, don't know what "Private" means
1688 void WINAPI PrivateFreeLibrary(HINSTANCE handle)
1690 FreeLibrary16((HINSTANCE16)handle);
1694 /***********************************************************************
1695 * WIN32_GetProcAddress16 (KERNEL32.36)
1696 * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
1698 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
1700 WORD ordinal;
1701 FARPROC16 ret;
1703 if (!hModule) {
1704 WARN_(module)("hModule may not be 0!\n");
1705 return (FARPROC16)0;
1707 if (HIWORD(hModule))
1709 WARN_(module)("hModule is Win32 handle (%08x)\n", hModule );
1710 return (FARPROC16)0;
1712 hModule = GetExePtr( hModule );
1713 if (HIWORD(name)) {
1714 ordinal = NE_GetOrdinal( hModule, name );
1715 TRACE_(module)("%04x '%s'\n",
1716 hModule, name );
1717 } else {
1718 ordinal = LOWORD(name);
1719 TRACE_(module)("%04x %04x\n",
1720 hModule, ordinal );
1722 if (!ordinal) return (FARPROC16)0;
1723 ret = NE_GetEntryPoint( hModule, ordinal );
1724 TRACE_(module)("returning %08x\n",(UINT)ret);
1725 return ret;
1728 /***********************************************************************
1729 * GetProcAddress16 (KERNEL.50)
1731 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, SEGPTR name )
1733 WORD ordinal;
1734 FARPROC16 ret;
1736 if (!hModule) hModule = GetCurrentTask();
1737 hModule = GetExePtr( hModule );
1739 if (HIWORD(name) != 0)
1741 ordinal = NE_GetOrdinal( hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1742 TRACE_(module)("%04x '%s'\n",
1743 hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1745 else
1747 ordinal = LOWORD(name);
1748 TRACE_(module)("%04x %04x\n",
1749 hModule, ordinal );
1751 if (!ordinal) return (FARPROC16)0;
1753 ret = NE_GetEntryPoint( hModule, ordinal );
1755 TRACE_(module)("returning %08x\n", (UINT)ret );
1756 return ret;
1760 /***********************************************************************
1761 * GetProcAddress32 (KERNEL32.257)
1763 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1765 return MODULE_GetProcAddress( hModule, function, TRUE );
1768 /***********************************************************************
1769 * WIN16_GetProcAddress32 (KERNEL.453)
1771 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
1773 return MODULE_GetProcAddress( hModule, function, FALSE );
1776 /***********************************************************************
1777 * MODULE_GetProcAddress32 (internal)
1779 FARPROC MODULE_GetProcAddress(
1780 HMODULE hModule, /* [in] current module handle */
1781 LPCSTR function, /* [in] function to be looked up */
1782 BOOL snoop )
1784 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1785 FARPROC retproc;
1787 if (HIWORD(function))
1788 TRACE_(win32)("(%08lx,%s)\n",(DWORD)hModule,function);
1789 else
1790 TRACE_(win32)("(%08lx,%p)\n",(DWORD)hModule,function);
1791 if (!wm) {
1792 SetLastError(ERROR_INVALID_HANDLE);
1793 return (FARPROC)0;
1795 switch (wm->type)
1797 case MODULE32_PE:
1798 retproc = PE_FindExportedFunction( wm, function, snoop );
1799 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1800 return retproc;
1801 case MODULE32_ELF:
1802 retproc = ELF_FindExportedFunction( wm, function);
1803 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1804 return retproc;
1805 default:
1806 ERR_(module)("wine_modref type %d not handled.\n",wm->type);
1807 SetLastError(ERROR_INVALID_HANDLE);
1808 return (FARPROC)0;
1813 /***********************************************************************
1814 * RtlImageNtHeaders (NTDLL)
1816 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
1818 /* basically:
1819 * return hModule+(((IMAGE_DOS_HEADER*)hModule)->e_lfanew);
1820 * but we could get HMODULE16 or the like (think builtin modules)
1823 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1824 if (!wm || (wm->type != MODULE32_PE)) return (PIMAGE_NT_HEADERS)0;
1825 return PE_HEADER(wm->module);
1829 /***************************************************************************
1830 * HasGPHandler (KERNEL.338)
1833 #include "pshpack1.h"
1834 typedef struct _GPHANDLERDEF
1836 WORD selector;
1837 WORD rangeStart;
1838 WORD rangeEnd;
1839 WORD handler;
1840 } GPHANDLERDEF;
1841 #include "poppack.h"
1843 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1845 HMODULE16 hModule;
1846 int gpOrdinal;
1847 SEGPTR gpPtr;
1848 GPHANDLERDEF *gpHandler;
1850 if ( (hModule = FarGetOwner16( SELECTOROF(address) )) != 0
1851 && (gpOrdinal = NE_GetOrdinal( hModule, "__GP" )) != 0
1852 && (gpPtr = (SEGPTR)NE_GetEntryPointEx( hModule, gpOrdinal, FALSE )) != 0
1853 && !IsBadReadPtr16( gpPtr, sizeof(GPHANDLERDEF) )
1854 && (gpHandler = PTR_SEG_TO_LIN( gpPtr )) != NULL )
1856 while (gpHandler->selector)
1858 if ( SELECTOROF(address) == gpHandler->selector
1859 && OFFSETOF(address) >= gpHandler->rangeStart
1860 && OFFSETOF(address) < gpHandler->rangeEnd )
1861 return PTR_SEG_OFF_TO_SEGPTR( gpHandler->selector,
1862 gpHandler->handler );
1863 gpHandler++;
1867 return 0;