Added IPersistFolder2 interface.
[wine/wine-kai.git] / loader / module.c
blobafafa28481350d3acaebd480d0bc2ad71ab14726
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 DEFAULT_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("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("(%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("wine_modref type %d not handled.\n", wm->type );
124 retv = FALSE;
125 break;
128 TRACE("(%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("(%s,%p) - START\n", 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("(%s,%p) - END\n", wm->modname, lpReserved );
211 return retv;
214 /*************************************************************************
215 * MODULE_DllProcessDetach
217 * Send DLL process detach notifications. See the comment about calling
218 * sequence at MODULE_DllProcessAttach. Unless the bForceDetach flag
219 * is set, only DLLs with zero refcount are notified.
221 * NOTE: Assumes that the process critical section is held!
224 void MODULE_DllProcessDetach( BOOL bForceDetach, LPVOID lpReserved )
226 WINE_MODREF *wm;
230 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
232 /* Check whether to detach this DLL */
233 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
234 continue;
235 if ( wm->refCount > 0 && !bForceDetach )
236 continue;
238 /* Call detach notification */
239 wm->flags &= ~WINE_MODREF_PROCESS_ATTACHED;
240 MODULE_InitDll( wm, DLL_PROCESS_DETACH, lpReserved );
242 /* Restart at head of WINE_MODREF list, as entries might have
243 been added and/or removed while performing the call ... */
244 break;
246 } while ( wm );
249 /*************************************************************************
250 * MODULE_DllThreadAttach
252 * Send DLL thread attach notifications. These are sent in the
253 * reverse sequence of process detach notification.
256 void MODULE_DllThreadAttach( LPVOID lpReserved )
258 WINE_MODREF *wm;
260 EnterCriticalSection( &PROCESS_Current()->crit_section );
262 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
263 if ( !wm->next )
264 break;
266 for ( ; wm; wm = wm->prev )
268 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
269 continue;
270 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
271 continue;
273 MODULE_InitDll( wm, DLL_THREAD_ATTACH, lpReserved );
276 LeaveCriticalSection( &PROCESS_Current()->crit_section );
279 /*************************************************************************
280 * MODULE_DllThreadDetach
282 * Send DLL thread detach notifications. These are sent in the
283 * same sequence as process detach notification.
286 void MODULE_DllThreadDetach( LPVOID lpReserved )
288 WINE_MODREF *wm;
290 EnterCriticalSection( &PROCESS_Current()->crit_section );
292 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
294 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
295 continue;
296 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
297 continue;
299 MODULE_InitDll( wm, DLL_THREAD_DETACH, lpReserved );
302 LeaveCriticalSection( &PROCESS_Current()->crit_section );
305 /****************************************************************************
306 * DisableThreadLibraryCalls (KERNEL32.74)
308 * Don't call DllEntryPoint for DLL_THREAD_{ATTACH,DETACH} if set.
310 BOOL WINAPI DisableThreadLibraryCalls( HMODULE hModule )
312 WINE_MODREF *wm;
313 BOOL retval = TRUE;
315 EnterCriticalSection( &PROCESS_Current()->crit_section );
317 wm = MODULE32_LookupHMODULE( hModule );
318 if ( !wm )
319 retval = FALSE;
320 else
321 wm->flags |= WINE_MODREF_NO_DLL_CALLS;
323 LeaveCriticalSection( &PROCESS_Current()->crit_section );
325 return retval;
328 /*************************************************************************
329 * MODULE_SendLoadDLLEvents
331 * Sends DEBUG_DLL_LOAD events for all outstanding modules.
333 * NOTE: Assumes that the process critical section is held!
336 void MODULE_SendLoadDLLEvents( void )
338 WINE_MODREF *wm;
340 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
342 if ( wm->type != MODULE32_PE ) continue;
343 if ( wm == PROCESS_Current()->exe_modref ) continue;
344 if ( wm->flags & WINE_MODREF_DEBUG_EVENT_SENT ) continue;
346 DEBUG_SendLoadDLLEvent( -1 /*FIXME*/, wm->module, &wm->modname );
347 wm->flags |= WINE_MODREF_DEBUG_EVENT_SENT;
352 /***********************************************************************
353 * MODULE_CreateDummyModule
355 * Create a dummy NE module for Win32 or Winelib.
357 HMODULE MODULE_CreateDummyModule( LPCSTR filename, WORD version )
359 HMODULE hModule;
360 NE_MODULE *pModule;
361 SEGTABLEENTRY *pSegment;
362 char *pStr,*s;
363 unsigned int len;
364 const char* basename;
365 OFSTRUCT *ofs;
366 int of_size, size;
368 /* Extract base filename */
369 basename = strrchr(filename, '\\');
370 if (!basename) basename = filename;
371 else basename++;
372 len = strlen(basename);
373 if ((s = strchr(basename, '.'))) len = s - basename;
375 /* Allocate module */
376 of_size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName)
377 + strlen(filename) + 1;
378 size = sizeof(NE_MODULE) +
379 /* loaded file info */
380 of_size +
381 /* segment table: DS,CS */
382 2 * sizeof(SEGTABLEENTRY) +
383 /* name table */
384 len + 2 +
385 /* several empty tables */
388 hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
389 if (!hModule) return (HMODULE)11; /* invalid exe */
391 FarSetOwner16( hModule, hModule );
392 pModule = (NE_MODULE *)GlobalLock16( hModule );
394 /* Set all used entries */
395 pModule->magic = IMAGE_OS2_SIGNATURE;
396 pModule->count = 1;
397 pModule->next = 0;
398 pModule->flags = 0;
399 pModule->dgroup = 0;
400 pModule->ss = 1;
401 pModule->cs = 2;
402 pModule->heap_size = 0;
403 pModule->stack_size = 0;
404 pModule->seg_count = 2;
405 pModule->modref_count = 0;
406 pModule->nrname_size = 0;
407 pModule->fileinfo = sizeof(NE_MODULE);
408 pModule->os_flags = NE_OSFLAGS_WINDOWS;
409 pModule->expected_version = version;
410 pModule->self = hModule;
412 /* Set loaded file information */
413 ofs = (OFSTRUCT *)(pModule + 1);
414 memset( ofs, 0, of_size );
415 ofs->cBytes = of_size < 256 ? of_size : 255; /* FIXME */
416 strcpy( ofs->szPathName, filename );
418 pSegment = (SEGTABLEENTRY*)((char*)(pModule + 1) + of_size);
419 pModule->seg_table = (int)pSegment - (int)pModule;
420 /* Data segment */
421 pSegment->size = 0;
422 pSegment->flags = NE_SEGFLAGS_DATA;
423 pSegment->minsize = 0x1000;
424 pSegment++;
425 /* Code segment */
426 pSegment->flags = 0;
427 pSegment++;
429 /* Module name */
430 pStr = (char *)pSegment;
431 pModule->name_table = (int)pStr - (int)pModule;
432 assert(len<256);
433 *pStr = len;
434 lstrcpynA( pStr+1, basename, len+1 );
435 pStr += len+2;
437 /* All tables zero terminated */
438 pModule->res_table = pModule->import_table = pModule->entry_table =
439 (int)pStr - (int)pModule;
441 NE_RegisterModule( pModule );
442 return hModule;
446 /**********************************************************************
447 * MODULE_FindModule32
449 * Find a (loaded) win32 module depending on path
451 * RETURNS
452 * the module handle if found
453 * 0 if not
455 WINE_MODREF *MODULE_FindModule(
456 LPCSTR path /* [in] pathname of module/library to be found */
458 WINE_MODREF *wm;
459 char dllname[260], *p;
461 /* Append .DLL to name if no extension present */
462 strcpy( dllname, path );
463 if (!(p = strrchr( dllname, '.')) || strchr( p, '/' ) || strchr( p, '\\'))
464 strcat( dllname, ".DLL" );
466 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
468 if ( !strcasecmp( dllname, wm->modname ) )
469 break;
470 if ( !strcasecmp( dllname, wm->filename ) )
471 break;
472 if ( !strcasecmp( dllname, wm->short_modname ) )
473 break;
474 if ( !strcasecmp( dllname, wm->short_filename ) )
475 break;
478 return wm;
481 /***********************************************************************
482 * MODULE_GetBinaryType
484 * The GetBinaryType function determines whether a file is executable
485 * or not and if it is it returns what type of executable it is.
486 * The type of executable is a property that determines in which
487 * subsystem an executable file runs under.
489 * Binary types returned:
490 * SCS_32BIT_BINARY: A Win32 based application
491 * SCS_DOS_BINARY: An MS-Dos based application
492 * SCS_WOW_BINARY: A Win16 based application
493 * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
494 * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
495 * SCS_OS216_BINARY: A 16bit OS/2 based application
497 * Returns TRUE if the file is an executable in which case
498 * the value pointed by lpBinaryType is set.
499 * Returns FALSE if the file is not an executable or if the function fails.
501 * To do so it opens the file and reads in the header information
502 * if the extended header information is not present it will
503 * assume that the file is a DOS executable.
504 * If the extended header information is present it will
505 * determine if the file is a 16 or 32 bit Windows executable
506 * by check the flags in the header.
508 * Note that .COM and .PIF files are only recognized by their
509 * file name extension; but Windows does it the same way ...
511 static BOOL MODULE_GetBinaryType( HANDLE hfile, LPCSTR filename,
512 LPDWORD lpBinaryType )
514 IMAGE_DOS_HEADER mz_header;
515 char magic[4], *ptr;
516 DWORD len;
518 /* Seek to the start of the file and read the DOS header information.
520 if ( SetFilePointer( hfile, 0, NULL, SEEK_SET ) != -1
521 && ReadFile( hfile, &mz_header, sizeof(mz_header), &len, NULL )
522 && len == sizeof(mz_header) )
524 /* Now that we have the header check the e_magic field
525 * to see if this is a dos image.
527 if ( mz_header.e_magic == IMAGE_DOS_SIGNATURE )
529 BOOL lfanewValid = FALSE;
530 /* We do have a DOS image so we will now try to seek into
531 * the file by the amount indicated by the field
532 * "Offset to extended header" and read in the
533 * "magic" field information at that location.
534 * This will tell us if there is more header information
535 * to read or not.
537 /* But before we do we will make sure that header
538 * structure encompasses the "Offset to extended header"
539 * field.
541 if ( (mz_header.e_cparhdr<<4) >= sizeof(IMAGE_DOS_HEADER) )
542 if ( ( mz_header.e_crlc == 0 ) ||
543 ( mz_header.e_lfarlc >= sizeof(IMAGE_DOS_HEADER) ) )
544 if ( mz_header.e_lfanew >= sizeof(IMAGE_DOS_HEADER)
545 && SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET ) != -1
546 && ReadFile( hfile, magic, sizeof(magic), &len, NULL )
547 && len == sizeof(magic) )
548 lfanewValid = TRUE;
550 if ( !lfanewValid )
552 /* If we cannot read this "extended header" we will
553 * assume that we have a simple DOS executable.
555 *lpBinaryType = SCS_DOS_BINARY;
556 return TRUE;
558 else
560 /* Reading the magic field succeeded so
561 * we will try to determine what type it is.
563 if ( *(DWORD*)magic == IMAGE_NT_SIGNATURE )
565 /* This is an NT signature.
567 *lpBinaryType = SCS_32BIT_BINARY;
568 return TRUE;
570 else if ( *(WORD*)magic == IMAGE_OS2_SIGNATURE )
572 /* The IMAGE_OS2_SIGNATURE indicates that the
573 * "extended header is a Windows executable (NE)
574 * header." This can mean either a 16-bit OS/2
575 * or a 16-bit Windows or even a DOS program
576 * (running under a DOS extender). To decide
577 * which, we'll have to read the NE header.
580 IMAGE_OS2_HEADER ne;
581 if ( SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET ) != -1
582 && ReadFile( hfile, &ne, sizeof(ne), &len, NULL )
583 && len == sizeof(ne) )
585 switch ( ne.operating_system )
587 case 2: *lpBinaryType = SCS_WOW_BINARY; return TRUE;
588 case 5: *lpBinaryType = SCS_DOS_BINARY; return TRUE;
589 default: *lpBinaryType = SCS_OS216_BINARY; return TRUE;
592 /* Couldn't read header, so abort. */
593 return FALSE;
595 else
597 /* Unknown extended header, but this file is nonetheless
598 DOS-executable.
600 *lpBinaryType = SCS_DOS_BINARY;
601 return TRUE;
607 /* If we get here, we don't even have a correct MZ header.
608 * Try to check the file extension for known types ...
610 ptr = strrchr( filename, '.' );
611 if ( ptr && !strchr( ptr, '\\' ) && !strchr( ptr, '/' ) )
613 if ( !lstrcmpiA( ptr, ".COM" ) )
615 *lpBinaryType = SCS_DOS_BINARY;
616 return TRUE;
619 if ( !lstrcmpiA( ptr, ".PIF" ) )
621 *lpBinaryType = SCS_PIF_BINARY;
622 return TRUE;
626 return FALSE;
629 /***********************************************************************
630 * GetBinaryTypeA [KERNEL32.280]
632 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
634 BOOL ret = FALSE;
635 HANDLE hfile;
637 TRACE_(win32)("%s\n", lpApplicationName );
639 /* Sanity check.
641 if ( lpApplicationName == NULL || lpBinaryType == NULL )
642 return FALSE;
644 /* Open the file indicated by lpApplicationName for reading.
646 hfile = CreateFileA( lpApplicationName, GENERIC_READ, 0,
647 NULL, OPEN_EXISTING, 0, -1 );
648 if ( hfile == INVALID_HANDLE_VALUE )
649 return FALSE;
651 /* Check binary type
653 ret = MODULE_GetBinaryType( hfile, lpApplicationName, lpBinaryType );
655 /* Close the file.
657 CloseHandle( hfile );
659 return ret;
662 /***********************************************************************
663 * GetBinaryTypeW [KERNEL32.281]
665 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
667 BOOL ret = FALSE;
668 LPSTR strNew = NULL;
670 TRACE_(win32)("%s\n", debugstr_w(lpApplicationName) );
672 /* Sanity check.
674 if ( lpApplicationName == NULL || lpBinaryType == NULL )
675 return FALSE;
677 /* Convert the wide string to a ascii string.
679 strNew = HEAP_strdupWtoA( GetProcessHeap(), 0, lpApplicationName );
681 if ( strNew != NULL )
683 ret = GetBinaryTypeA( strNew, lpBinaryType );
685 /* Free the allocated string.
687 HeapFree( GetProcessHeap(), 0, strNew );
690 return ret;
693 /**********************************************************************
694 * MODULE_CreateUnixProcess
696 static BOOL MODULE_CreateUnixProcess( LPCSTR filename, LPCSTR lpCmdLine,
697 LPSTARTUPINFOA lpStartupInfo,
698 LPPROCESS_INFORMATION lpProcessInfo,
699 BOOL useWine )
701 DOS_FULL_NAME full_name;
702 const char *unixfilename = filename;
703 const char *argv[256], **argptr;
704 char *cmdline = NULL;
705 BOOL iconic = FALSE;
707 /* Get Unix file name and iconic flag */
709 if ( lpStartupInfo->dwFlags & STARTF_USESHOWWINDOW )
710 if ( lpStartupInfo->wShowWindow == SW_SHOWMINIMIZED
711 || lpStartupInfo->wShowWindow == SW_SHOWMINNOACTIVE )
712 iconic = TRUE;
714 /* Build argument list */
716 argptr = argv;
717 if ( !useWine )
719 char *p;
720 p = cmdline = strdup(lpCmdLine);
721 if (strchr(filename, '/') || strchr(filename, ':') || strchr(filename, '\\'))
723 if ( DOSFS_GetFullName( filename, TRUE, &full_name ) )
724 unixfilename = full_name.long_name;
726 *argptr++ = unixfilename;
727 if (iconic) *argptr++ = "-iconic";
728 while (1)
730 while (*p && (*p == ' ' || *p == '\t')) *p++ = '\0';
731 if (!*p) break;
732 *argptr++ = p;
733 while (*p && *p != ' ' && *p != '\t') p++;
736 else
738 *argptr++ = "wine";
739 if (iconic) *argptr++ = "-iconic";
740 *argptr++ = lpCmdLine;
742 *argptr++ = 0;
744 /* Fork and execute */
746 if ( !fork() )
748 /* Note: don't use Wine routines here, as this process
749 has not been correctly initialized! */
751 execvp( argv[0], (char**)argv );
753 /* Failed ! */
754 if ( useWine )
755 fprintf( stderr, "CreateProcess: can't exec 'wine %s'\n",
756 lpCmdLine );
757 exit( 1 );
760 /* Fake success return value */
762 memset( lpProcessInfo, '\0', sizeof( *lpProcessInfo ) );
763 lpProcessInfo->hProcess = INVALID_HANDLE_VALUE;
764 lpProcessInfo->hThread = INVALID_HANDLE_VALUE;
765 if (cmdline) free(cmdline);
767 SetLastError( ERROR_SUCCESS );
768 return TRUE;
771 /***********************************************************************
772 * WinExec16 (KERNEL.166)
774 HINSTANCE16 WINAPI WinExec16( LPCSTR lpCmdLine, UINT16 nCmdShow )
776 HINSTANCE16 hInst;
778 SYSLEVEL_ReleaseWin16Lock();
779 hInst = WinExec( lpCmdLine, nCmdShow );
780 SYSLEVEL_RestoreWin16Lock();
782 return hInst;
785 /***********************************************************************
786 * WinExec (KERNEL32.566)
788 HINSTANCE WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
790 LOADPARAMS params;
791 UINT16 paramCmdShow[2];
793 if (!lpCmdLine)
794 return 2; /* File not found */
796 /* Set up LOADPARAMS buffer for LoadModule */
798 memset( &params, '\0', sizeof(params) );
799 params.lpCmdLine = (LPSTR)lpCmdLine;
800 params.lpCmdShow = paramCmdShow;
801 params.lpCmdShow[0] = 2;
802 params.lpCmdShow[1] = nCmdShow;
804 /* Now load the executable file */
806 return LoadModule( NULL, &params );
809 /**********************************************************************
810 * LoadModule (KERNEL32.499)
812 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
814 LOADPARAMS *params = (LOADPARAMS *)paramBlock;
815 PROCESS_INFORMATION info;
816 STARTUPINFOA startup;
817 HINSTANCE hInstance;
818 PDB *pdb;
819 TDB *tdb;
821 memset( &startup, '\0', sizeof(startup) );
822 startup.cb = sizeof(startup);
823 startup.dwFlags = STARTF_USESHOWWINDOW;
824 startup.wShowWindow = params->lpCmdShow? params->lpCmdShow[1] : 0;
826 if ( !CreateProcessA( name, params->lpCmdLine,
827 NULL, NULL, FALSE, 0, params->lpEnvAddress,
828 NULL, &startup, &info ) )
830 hInstance = GetLastError();
831 if ( hInstance < 32 ) return hInstance;
833 FIXME("Strange error set by CreateProcess: %d\n", hInstance );
834 return 11;
837 /* Give 30 seconds to the app to come up */
838 if ( Callout.WaitForInputIdle ( info.hProcess, 30000 ) == 0xFFFFFFFF )
839 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
841 /* Get 16-bit hInstance/hTask from process */
842 pdb = PROCESS_IdToPDB( info.dwProcessId );
843 tdb = pdb? (TDB *)GlobalLock16( pdb->task ) : NULL;
844 hInstance = tdb && tdb->hInstance? tdb->hInstance : pdb? pdb->task : 0;
845 /* If there is no hInstance (32-bit process) return a dummy value
846 * that must be > 31
847 * FIXME: should do this in all cases and fix Win16 callers */
848 if (!hInstance) hInstance = 33;
850 /* Close off the handles */
851 CloseHandle( info.hThread );
852 CloseHandle( info.hProcess );
854 return hInstance;
857 /*************************************************************************
858 * get_makename_token
860 * Get next blank delimited token from input string. If quoted then
861 * process till matching quote and then till blank.
863 * Returns number of characters in token (not including \0). On
864 * end of string (EOS), returns a 0.
866 * from (IO) address of start of input string to scan, updated to
867 * next non-processed character.
868 * to (IO) address of start of output string (previous token \0
869 * char), updated to end of new output string (the \0
870 * char).
872 static int get_makename_token(LPCSTR *from, LPSTR *to )
874 int len = 0;
875 LPCSTR to_old = *to; /* only used for tracing */
877 while ( **from == ' ') {
878 /* Copy leading blanks (separators between previous */
879 /* token and this token). */
880 **to = **from;
881 (*from)++;
882 (*to)++;
883 len++;
885 do {
886 while ( (**from != 0) && (**from != ' ') && (**from != '"') ) {
887 **to = **from; (*from)++; (*to)++; len++;
889 if ( **from == '"' ) {
890 /* Handle quoted string. */
891 (*from)++;
892 if ( !strchr(*from, '"') ) {
893 /* fail - no closing quote. Return entire string */
894 while ( **from != 0 ) {
895 **to = **from; (*from)++; (*to)++; len++;
897 break;
899 while( **from != '"') {
900 **to = **from;
901 len++;
902 (*to)++;
903 (*from)++;
905 (*from)++;
906 continue;
909 /* either EOS or ' ' */
910 break;
912 } while (1);
914 **to = 0; /* terminate output string */
916 TRACE("returning token len=%d, string=%s\n", len, to_old);
918 return len;
921 /*************************************************************************
922 * make_lpCommandLine_name
924 * Try longer and longer strings from "line" to find an existing
925 * file name. Each attempt is delimited by a blank outside of quotes.
926 * Also will attempt to append ".exe" if requested and not already
927 * present. Returns the address of the remaining portion of the
928 * input line.
932 static BOOL make_lpCommandLine_name( LPCSTR line, LPSTR name, int namelen,
933 LPCSTR *after )
935 BOOL found = TRUE;
936 LPCSTR from;
937 char buffer[260];
938 DWORD retlen;
939 LPSTR to, lastpart;
941 from = line;
942 to = name;
944 /* scan over initial blanks if any */
945 while ( *from == ' ') from++;
947 /* get a token and append to previous data the check for existance */
948 do {
949 if ( !get_makename_token( &from, &to ) ) {
950 /* EOS has occured and not found - exit */
951 retlen = 0;
952 found = FALSE;
953 break;
955 TRACE("checking if file exists '%s'\n", name);
956 retlen = SearchPathA( NULL, name, ".exe", sizeof(buffer), buffer, &lastpart);
957 if ( retlen && (retlen < sizeof(buffer)) ) break;
958 } while (1);
960 /* if we have a non-null full path name in buffer then move to output */
961 if ( retlen ) {
962 if ( strlen(buffer) <= namelen ) {
963 strcpy( name, buffer );
964 } else {
965 /* not enough space to return full path string */
966 FIXME("internal string not long enough, need %d\n",
967 strlen(buffer) );
971 /* all done, indicate end of module name and then trace and exit */
972 if (after) *after = from;
973 TRACE("%i, selected file name '%s'\n and cmdline as %s\n",
974 found, name, debugstr_a(from));
975 return found;
978 /*************************************************************************
979 * make_lpApplicationName_name
981 * Scan input string (the lpApplicationName) and remove any quotes
982 * if they are balanced.
986 static BOOL make_lpApplicationName_name( LPCSTR line, LPSTR name, int namelen)
988 LPCSTR from;
989 LPSTR to, to_end, to_old;
990 char buffer[260];
992 to = buffer;
993 to_end = to + sizeof(buffer) - 1;
994 to_old = to;
996 while ( *line == ' ' ) line++; /* point to beginning of string */
997 from = line;
998 do {
999 /* Copy all input till end, or quote */
1000 while((*from != 0) && (*from != '"') && (to < to_end))
1001 *to++ = *from++;
1002 if (to >= to_end) { *to = 0; break; }
1004 if (*from == '"')
1006 /* Handle quoted string. If there is a closing quote, copy all */
1007 /* that is inside. */
1008 from++;
1009 if (!strchr(from, '"'))
1011 /* fail - no closing quote */
1012 to = to_old; /* restore to previous attempt */
1013 *to = 0; /* end string */
1014 break; /* exit with previous attempt */
1016 while((*from != '"') && (to < to_end)) *to++ = *from++;
1017 if (to >= to_end) { *to = 0; break; }
1018 from++;
1019 continue; /* past quoted string, so restart from top */
1022 *to = 0; /* terminate output string */
1023 to_old = to; /* save for possible use in unmatched quote case */
1025 /* loop around keeping the blank as part of file name */
1026 if (!*from)
1027 break; /* exit if out of input string */
1028 } while (1);
1030 if (!SearchPathA( NULL, buffer, ".exe", namelen, name, NULL )) {
1031 TRACE("file not found '%s'\n", buffer );
1032 return FALSE;
1035 TRACE("selected as file name '%s'\n", name );
1036 return TRUE;
1039 /**********************************************************************
1040 * CreateProcessA (KERNEL32.171)
1042 BOOL WINAPI CreateProcessA( LPCSTR lpApplicationName, LPSTR lpCommandLine,
1043 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1044 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1045 BOOL bInheritHandles, DWORD dwCreationFlags,
1046 LPVOID lpEnvironment, LPCSTR lpCurrentDirectory,
1047 LPSTARTUPINFOA lpStartupInfo,
1048 LPPROCESS_INFORMATION lpProcessInfo )
1050 BOOL retv = FALSE;
1051 BOOL found_file = FALSE;
1052 HANDLE hFile;
1053 DWORD type;
1054 char name[256], dummy[256];
1055 LPCSTR cmdline = NULL;
1056 LPSTR tidy_cmdline;
1058 /* Get name and command line */
1060 if (!lpApplicationName && !lpCommandLine)
1062 SetLastError( ERROR_FILE_NOT_FOUND );
1063 return FALSE;
1066 /* Process the AppName and/or CmdLine to get module name and path */
1068 name[0] = '\0';
1070 if (lpApplicationName)
1072 found_file = make_lpApplicationName_name( lpApplicationName, name, sizeof(name) );
1073 if (lpCommandLine)
1074 make_lpCommandLine_name( lpCommandLine, dummy, sizeof ( dummy ), &cmdline );
1075 else
1076 cmdline = lpApplicationName;
1078 else
1080 if (lpCommandLine)
1081 found_file = make_lpCommandLine_name( lpCommandLine, name, sizeof ( name ), &cmdline );
1084 if ( !found_file ) {
1085 /* make an early exit if file not found - save second pass */
1086 SetLastError( ERROR_FILE_NOT_FOUND );
1087 return FALSE;
1090 if (!cmdline) cmdline = "";
1091 tidy_cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(name) + strlen(cmdline) + 3 );
1092 TRACE_(module)("tidy_cmdline: name '%s'[%d], cmdline '%s'[%d]\n",
1093 name, strlen(name), cmdline, strlen(cmdline));
1094 sprintf( tidy_cmdline, "\"%s\"%s", name, cmdline);
1096 /* Warn if unsupported features are used */
1098 if (dwCreationFlags & DETACHED_PROCESS)
1099 FIXME("(%s,...): DETACHED_PROCESS ignored\n", name);
1100 if (dwCreationFlags & CREATE_NEW_CONSOLE)
1101 FIXME("(%s,...): CREATE_NEW_CONSOLE ignored\n", name);
1102 if (dwCreationFlags & NORMAL_PRIORITY_CLASS)
1103 FIXME("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
1104 if (dwCreationFlags & IDLE_PRIORITY_CLASS)
1105 FIXME("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
1106 if (dwCreationFlags & HIGH_PRIORITY_CLASS)
1107 FIXME("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
1108 if (dwCreationFlags & REALTIME_PRIORITY_CLASS)
1109 FIXME("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
1110 if (dwCreationFlags & CREATE_NEW_PROCESS_GROUP)
1111 FIXME("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
1112 if (dwCreationFlags & CREATE_UNICODE_ENVIRONMENT)
1113 FIXME("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
1114 if (dwCreationFlags & CREATE_SEPARATE_WOW_VDM)
1115 FIXME("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
1116 if (dwCreationFlags & CREATE_SHARED_WOW_VDM)
1117 FIXME("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
1118 if (dwCreationFlags & CREATE_DEFAULT_ERROR_MODE)
1119 FIXME("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
1120 if (dwCreationFlags & CREATE_NO_WINDOW)
1121 FIXME("(%s,...): CREATE_NO_WINDOW ignored\n", name);
1122 if (dwCreationFlags & PROFILE_USER)
1123 FIXME("(%s,...): PROFILE_USER ignored\n", name);
1124 if (dwCreationFlags & PROFILE_KERNEL)
1125 FIXME("(%s,...): PROFILE_KERNEL ignored\n", name);
1126 if (dwCreationFlags & PROFILE_SERVER)
1127 FIXME("(%s,...): PROFILE_SERVER ignored\n", name);
1128 if (lpCurrentDirectory)
1129 FIXME("(%s,...): lpCurrentDirectory %s ignored\n",
1130 name, lpCurrentDirectory);
1131 if (lpStartupInfo->lpDesktop)
1132 FIXME("(%s,...): lpStartupInfo->lpDesktop %s ignored\n",
1133 name, lpStartupInfo->lpDesktop);
1134 if (lpStartupInfo->lpTitle)
1135 FIXME("(%s,...): lpStartupInfo->lpTitle %s ignored\n",
1136 name, lpStartupInfo->lpTitle);
1137 if (lpStartupInfo->dwFlags & STARTF_USECOUNTCHARS)
1138 FIXME("(%s,...): STARTF_USECOUNTCHARS (%ld,%ld) ignored\n",
1139 name, lpStartupInfo->dwXCountChars, lpStartupInfo->dwYCountChars);
1140 if (lpStartupInfo->dwFlags & STARTF_USEFILLATTRIBUTE)
1141 FIXME("(%s,...): STARTF_USEFILLATTRIBUTE %lx ignored\n",
1142 name, lpStartupInfo->dwFillAttribute);
1143 if (lpStartupInfo->dwFlags & STARTF_RUNFULLSCREEN)
1144 FIXME("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
1145 if (lpStartupInfo->dwFlags & STARTF_FORCEONFEEDBACK)
1146 FIXME("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
1147 if (lpStartupInfo->dwFlags & STARTF_FORCEOFFFEEDBACK)
1148 FIXME("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
1149 if (lpStartupInfo->dwFlags & STARTF_USEHOTKEY)
1150 FIXME("(%s,...): STARTF_USEHOTKEY ignored\n", name);
1153 /* Load file and create process */
1155 if ( !retv )
1157 /* Open file and determine executable type */
1159 hFile = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ,
1160 NULL, OPEN_EXISTING, 0, -1 );
1161 if ( hFile == INVALID_HANDLE_VALUE )
1163 SetLastError( ERROR_FILE_NOT_FOUND );
1164 HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1165 return FALSE;
1168 if ( !MODULE_GetBinaryType( hFile, name, &type ) )
1170 CloseHandle( hFile );
1172 /* FIXME: Try Unix executable only when appropriate! */
1173 if ( MODULE_CreateUnixProcess( name, tidy_cmdline,
1174 lpStartupInfo, lpProcessInfo, FALSE ) )
1176 HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1177 return TRUE;
1179 HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1180 SetLastError( ERROR_BAD_FORMAT );
1181 return FALSE;
1185 /* Create process */
1187 switch ( type )
1189 case SCS_32BIT_BINARY:
1190 retv = PE_CreateProcess( hFile, name, tidy_cmdline, lpEnvironment,
1191 lpProcessAttributes, lpThreadAttributes,
1192 bInheritHandles, dwCreationFlags,
1193 lpStartupInfo, lpProcessInfo );
1194 break;
1196 case SCS_DOS_BINARY:
1197 retv = MZ_CreateProcess( hFile, name, tidy_cmdline, lpEnvironment,
1198 lpProcessAttributes, lpThreadAttributes,
1199 bInheritHandles, dwCreationFlags,
1200 lpStartupInfo, lpProcessInfo );
1201 break;
1203 case SCS_WOW_BINARY:
1204 retv = NE_CreateProcess( hFile, name, tidy_cmdline, lpEnvironment,
1205 lpProcessAttributes, lpThreadAttributes,
1206 bInheritHandles, dwCreationFlags,
1207 lpStartupInfo, lpProcessInfo );
1208 break;
1210 case SCS_PIF_BINARY:
1211 case SCS_POSIX_BINARY:
1212 case SCS_OS216_BINARY:
1213 FIXME("Unsupported executable type: %ld\n", type );
1214 /* fall through */
1216 default:
1217 SetLastError( ERROR_BAD_FORMAT );
1218 retv = FALSE;
1219 break;
1222 CloseHandle( hFile );
1224 HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1225 return retv;
1228 /**********************************************************************
1229 * CreateProcessW (KERNEL32.172)
1230 * NOTES
1231 * lpReserved is not converted
1233 BOOL WINAPI CreateProcessW( LPCWSTR lpApplicationName, LPWSTR lpCommandLine,
1234 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1235 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1236 BOOL bInheritHandles, DWORD dwCreationFlags,
1237 LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory,
1238 LPSTARTUPINFOW lpStartupInfo,
1239 LPPROCESS_INFORMATION lpProcessInfo )
1240 { BOOL ret;
1241 STARTUPINFOA StartupInfoA;
1243 LPSTR lpApplicationNameA = HEAP_strdupWtoA (GetProcessHeap(),0,lpApplicationName);
1244 LPSTR lpCommandLineA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCommandLine);
1245 LPSTR lpCurrentDirectoryA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCurrentDirectory);
1247 memcpy (&StartupInfoA, lpStartupInfo, sizeof(STARTUPINFOA));
1248 StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpDesktop);
1249 StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpTitle);
1251 TRACE_(win32)("(%s,%s,...)\n", debugstr_w(lpApplicationName), debugstr_w(lpCommandLine));
1253 if (lpStartupInfo->lpReserved)
1254 FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n", debugstr_w(lpStartupInfo->lpReserved));
1256 ret = CreateProcessA( lpApplicationNameA, lpCommandLineA,
1257 lpProcessAttributes, lpThreadAttributes,
1258 bInheritHandles, dwCreationFlags,
1259 lpEnvironment, lpCurrentDirectoryA,
1260 &StartupInfoA, lpProcessInfo );
1262 HeapFree( GetProcessHeap(), 0, lpCurrentDirectoryA );
1263 HeapFree( GetProcessHeap(), 0, lpCommandLineA );
1264 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1265 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1267 return ret;
1270 /***********************************************************************
1271 * GetModuleHandle (KERNEL32.237)
1273 HMODULE WINAPI GetModuleHandleA(LPCSTR module)
1275 WINE_MODREF *wm;
1277 if ( module == NULL )
1278 wm = PROCESS_Current()->exe_modref;
1279 else
1280 wm = MODULE_FindModule( module );
1282 return wm? wm->module : 0;
1285 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
1287 HMODULE hModule;
1288 LPSTR modulea = HEAP_strdupWtoA( GetProcessHeap(), 0, module );
1289 hModule = GetModuleHandleA( modulea );
1290 HeapFree( GetProcessHeap(), 0, modulea );
1291 return hModule;
1295 /***********************************************************************
1296 * GetModuleFileNameA (KERNEL32.235)
1298 DWORD WINAPI GetModuleFileNameA(
1299 HMODULE hModule, /* [in] module handle (32bit) */
1300 LPSTR lpFileName, /* [out] filenamebuffer */
1301 DWORD size /* [in] size of filenamebuffer */
1302 ) {
1303 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1305 if (!wm) /* can happen on start up or the like */
1306 return 0;
1308 if (PE_HEADER(wm->module)->OptionalHeader.MajorOperatingSystemVersion >= 4.0)
1309 lstrcpynA( lpFileName, wm->filename, size );
1310 else
1311 lstrcpynA( lpFileName, wm->short_filename, size );
1313 TRACE("%s\n", lpFileName );
1314 return strlen(lpFileName);
1318 /***********************************************************************
1319 * GetModuleFileName32W (KERNEL32.236)
1321 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName,
1322 DWORD size )
1324 LPSTR fnA = (char*)HeapAlloc( GetProcessHeap(), 0, size );
1325 DWORD res = GetModuleFileNameA( hModule, fnA, size );
1326 lstrcpynAtoW( lpFileName, fnA, size );
1327 HeapFree( GetProcessHeap(), 0, fnA );
1328 return res;
1332 /***********************************************************************
1333 * LoadLibraryExA (KERNEL32)
1335 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
1337 WINE_MODREF *wm;
1339 if(!libname)
1341 SetLastError(ERROR_INVALID_PARAMETER);
1342 return 0;
1345 EnterCriticalSection(&PROCESS_Current()->crit_section);
1347 wm = MODULE_LoadLibraryExA( libname, hfile, flags );
1348 if ( wm )
1350 if ( PROCESS_Current()->flags & PDB32_DEBUGGED )
1351 MODULE_SendLoadDLLEvents();
1353 if ( !MODULE_DllProcessAttach( wm, NULL ) )
1355 WARN_(module)("Attach failed for module '%s', \n", libname);
1356 MODULE_FreeLibrary(wm);
1357 SetLastError(ERROR_DLL_INIT_FAILED);
1358 wm = NULL;
1362 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1364 return wm ? wm->module : 0;
1367 /***********************************************************************
1368 * MODULE_LoadLibraryExA (internal)
1370 * Load a PE style module according to the load order.
1372 * The HFILE parameter is not used and marked reserved in the SDK. I can
1373 * only guess that it should force a file to be mapped, but I rather
1374 * ignore the parameter because it would be extremely difficult to
1375 * integrate this with different types of module represenations.
1378 WINE_MODREF *MODULE_LoadLibraryExA( LPCSTR libname, HFILE hfile, DWORD flags )
1380 DWORD err;
1381 WINE_MODREF *pwm;
1382 int i;
1383 module_loadorder_t *plo;
1385 EnterCriticalSection(&PROCESS_Current()->crit_section);
1387 /* Check for already loaded module */
1388 if((pwm = MODULE_FindModule(libname)))
1390 if(!(pwm->flags & WINE_MODREF_MARKER))
1391 pwm->refCount++;
1392 TRACE("Already loaded module '%s' at 0x%08x, count=%d, \n", libname, pwm->module, pwm->refCount);
1393 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1394 return pwm;
1397 plo = MODULE_GetLoadOrder(libname);
1399 for(i = 0; i < MODULE_LOADORDER_NTYPES; i++)
1401 switch(plo->loadorder[i])
1403 case MODULE_LOADORDER_DLL:
1404 TRACE("Trying native dll '%s'\n", libname);
1405 pwm = PE_LoadLibraryExA(libname, flags, &err);
1406 break;
1408 case MODULE_LOADORDER_ELFDLL:
1409 TRACE("Trying elfdll '%s'\n", libname);
1410 pwm = ELFDLL_LoadLibraryExA(libname, flags, &err);
1411 break;
1413 case MODULE_LOADORDER_SO:
1414 TRACE("Trying so-library '%s'\n", libname);
1415 pwm = ELF_LoadLibraryExA(libname, flags, &err);
1416 break;
1418 case MODULE_LOADORDER_BI:
1419 TRACE("Trying built-in '%s'\n", libname);
1420 pwm = BUILTIN32_LoadLibraryExA(libname, flags, &err);
1421 break;
1423 default:
1424 ERR("Got invalid loadorder type %d (%s index %d)\n", plo->loadorder[i], plo->modulename, i);
1425 /* Fall through */
1427 case MODULE_LOADORDER_INVALID: /* We ignore this as it is an empty entry */
1428 pwm = NULL;
1429 break;
1432 if(pwm)
1434 /* Initialize DLL just loaded */
1435 TRACE("Loaded module '%s' at 0x%08x, \n", libname, pwm->module);
1437 /* Set the refCount here so that an attach failure will */
1438 /* decrement the dependencies through the MODULE_FreeLibrary call. */
1439 pwm->refCount++;
1441 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1443 return pwm;
1446 if(err != ERROR_FILE_NOT_FOUND)
1447 break;
1450 WARN("Failed to load module '%s'; error=0x%08lx, \n", libname, err);
1451 SetLastError(err);
1452 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1453 return NULL;
1456 /***********************************************************************
1457 * LoadLibraryA (KERNEL32)
1459 HMODULE WINAPI LoadLibraryA(LPCSTR libname) {
1460 return LoadLibraryExA(libname,0,0);
1463 /***********************************************************************
1464 * LoadLibraryW (KERNEL32)
1466 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
1468 return LoadLibraryExW(libnameW,0,0);
1471 /***********************************************************************
1472 * LoadLibrary32_16 (KERNEL.452)
1474 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
1476 HMODULE hModule;
1478 SYSLEVEL_ReleaseWin16Lock();
1479 hModule = LoadLibraryA( libname );
1480 SYSLEVEL_RestoreWin16Lock();
1482 return hModule;
1485 /***********************************************************************
1486 * LoadLibraryExW (KERNEL32)
1488 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW,HANDLE hfile,DWORD flags)
1490 LPSTR libnameA = HEAP_strdupWtoA( GetProcessHeap(), 0, libnameW );
1491 HMODULE ret = LoadLibraryExA( libnameA , hfile, flags );
1493 HeapFree( GetProcessHeap(), 0, libnameA );
1494 return ret;
1497 /***********************************************************************
1498 * MODULE_FlushModrefs
1500 * NOTE: Assumes that the process critical section is held!
1502 * Remove all unused modrefs and call the internal unloading routines
1503 * for the library type.
1505 static void MODULE_FlushModrefs(void)
1507 WINE_MODREF *wm, *next;
1509 for(wm = PROCESS_Current()->modref_list; wm; wm = next)
1511 next = wm->next;
1513 if(wm->refCount)
1514 continue;
1516 /* Unlink this modref from the chain */
1517 if(wm->next)
1518 wm->next->prev = wm->prev;
1519 if(wm->prev)
1520 wm->prev->next = wm->next;
1521 if(wm == PROCESS_Current()->modref_list)
1522 PROCESS_Current()->modref_list = wm->next;
1525 * The unloaders are also responsible for freeing the modref itself
1526 * because the loaders were responsible for allocating it.
1528 switch(wm->type)
1530 case MODULE32_PE: PE_UnloadLibrary(wm); break;
1531 case MODULE32_ELF: ELF_UnloadLibrary(wm); break;
1532 case MODULE32_ELFDLL: ELFDLL_UnloadLibrary(wm); break;
1533 case MODULE32_BI: BUILTIN32_UnloadLibrary(wm); break;
1535 default:
1536 ERR("Invalid or unhandled MODREF type %d encountered (wm=%p)\n", wm->type, wm);
1541 /***********************************************************************
1542 * FreeLibrary
1544 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
1546 BOOL retv = FALSE;
1547 WINE_MODREF *wm;
1549 EnterCriticalSection( &PROCESS_Current()->crit_section );
1550 PROCESS_Current()->free_lib_count++;
1552 wm = MODULE32_LookupHMODULE( hLibModule );
1553 if ( !wm || !hLibModule )
1554 SetLastError( ERROR_INVALID_HANDLE );
1555 else
1556 retv = MODULE_FreeLibrary( wm );
1558 PROCESS_Current()->free_lib_count--;
1559 LeaveCriticalSection( &PROCESS_Current()->crit_section );
1561 return retv;
1564 /***********************************************************************
1565 * MODULE_DecRefCount
1567 * NOTE: Assumes that the process critical section is held!
1569 static void MODULE_DecRefCount( WINE_MODREF *wm )
1571 int i;
1573 if ( wm->flags & WINE_MODREF_MARKER )
1574 return;
1576 if ( wm->refCount <= 0 )
1577 return;
1579 --wm->refCount;
1580 TRACE("(%s) refCount: %d\n", wm->modname, wm->refCount );
1582 if ( wm->refCount == 0 )
1584 wm->flags |= WINE_MODREF_MARKER;
1586 for ( i = 0; i < wm->nDeps; i++ )
1587 if ( wm->deps[i] )
1588 MODULE_DecRefCount( wm->deps[i] );
1590 wm->flags &= ~WINE_MODREF_MARKER;
1594 /***********************************************************************
1595 * MODULE_FreeLibrary
1597 * NOTE: Assumes that the process critical section is held!
1599 BOOL MODULE_FreeLibrary( WINE_MODREF *wm )
1601 TRACE("(%s) - START\n", wm->modname );
1603 /* Recursively decrement reference counts */
1604 MODULE_DecRefCount( wm );
1606 /* Call process detach notifications */
1607 if ( PROCESS_Current()->free_lib_count <= 1 )
1609 MODULE_DllProcessDetach( FALSE, NULL );
1610 if (PROCESS_Current()->flags & PDB32_DEBUGGED)
1611 DEBUG_SendUnloadDLLEvent( wm->module );
1614 TRACE("(%s) - END\n", wm->modname );
1616 MODULE_FlushModrefs();
1618 return TRUE;
1622 /***********************************************************************
1623 * FreeLibraryAndExitThread
1625 VOID WINAPI FreeLibraryAndExitThread(HINSTANCE hLibModule, DWORD dwExitCode)
1627 FreeLibrary(hLibModule);
1628 ExitThread(dwExitCode);
1631 /***********************************************************************
1632 * PrivateLoadLibrary (KERNEL32)
1634 * FIXME: rough guesswork, don't know what "Private" means
1636 HINSTANCE WINAPI PrivateLoadLibrary(LPCSTR libname)
1638 return (HINSTANCE)LoadLibrary16(libname);
1643 /***********************************************************************
1644 * PrivateFreeLibrary (KERNEL32)
1646 * FIXME: rough guesswork, don't know what "Private" means
1648 void WINAPI PrivateFreeLibrary(HINSTANCE handle)
1650 FreeLibrary16((HINSTANCE16)handle);
1654 /***********************************************************************
1655 * WIN32_GetProcAddress16 (KERNEL32.36)
1656 * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
1658 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
1660 WORD ordinal;
1661 FARPROC16 ret;
1663 if (!hModule) {
1664 WARN("hModule may not be 0!\n");
1665 return (FARPROC16)0;
1667 if (HIWORD(hModule))
1669 WARN("hModule is Win32 handle (%08x)\n", hModule );
1670 return (FARPROC16)0;
1672 hModule = GetExePtr( hModule );
1673 if (HIWORD(name)) {
1674 ordinal = NE_GetOrdinal( hModule, name );
1675 TRACE("%04x '%s'\n", hModule, name );
1676 } else {
1677 ordinal = LOWORD(name);
1678 TRACE("%04x %04x\n", hModule, ordinal );
1680 if (!ordinal) return (FARPROC16)0;
1681 ret = NE_GetEntryPoint( hModule, ordinal );
1682 TRACE("returning %08x\n",(UINT)ret);
1683 return ret;
1686 /***********************************************************************
1687 * GetProcAddress16 (KERNEL.50)
1689 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, SEGPTR name )
1691 WORD ordinal;
1692 FARPROC16 ret;
1694 if (!hModule) hModule = GetCurrentTask();
1695 hModule = GetExePtr( hModule );
1697 if (HIWORD(name) != 0)
1699 ordinal = NE_GetOrdinal( hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1700 TRACE("%04x '%s'\n", hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1702 else
1704 ordinal = LOWORD(name);
1705 TRACE("%04x %04x\n", hModule, ordinal );
1707 if (!ordinal) return (FARPROC16)0;
1709 ret = NE_GetEntryPoint( hModule, ordinal );
1711 TRACE("returning %08x\n", (UINT)ret );
1712 return ret;
1716 /***********************************************************************
1717 * GetProcAddress32 (KERNEL32.257)
1719 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1721 return MODULE_GetProcAddress( hModule, function, TRUE );
1724 /***********************************************************************
1725 * WIN16_GetProcAddress32 (KERNEL.453)
1727 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
1729 return MODULE_GetProcAddress( hModule, function, FALSE );
1732 /***********************************************************************
1733 * MODULE_GetProcAddress32 (internal)
1735 FARPROC MODULE_GetProcAddress(
1736 HMODULE hModule, /* [in] current module handle */
1737 LPCSTR function, /* [in] function to be looked up */
1738 BOOL snoop )
1740 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1741 FARPROC retproc;
1743 if (HIWORD(function))
1744 TRACE_(win32)("(%08lx,%s)\n",(DWORD)hModule,function);
1745 else
1746 TRACE_(win32)("(%08lx,%p)\n",(DWORD)hModule,function);
1747 if (!wm) {
1748 SetLastError(ERROR_INVALID_HANDLE);
1749 return (FARPROC)0;
1751 switch (wm->type)
1753 case MODULE32_PE:
1754 retproc = PE_FindExportedFunction( wm, function, snoop );
1755 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1756 return retproc;
1757 case MODULE32_ELF:
1758 retproc = ELF_FindExportedFunction( wm, function);
1759 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1760 return retproc;
1761 default:
1762 ERR("wine_modref type %d not handled.\n",wm->type);
1763 SetLastError(ERROR_INVALID_HANDLE);
1764 return (FARPROC)0;
1769 /***********************************************************************
1770 * RtlImageNtHeaders (NTDLL)
1772 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
1774 /* basically:
1775 * return hModule+(((IMAGE_DOS_HEADER*)hModule)->e_lfanew);
1776 * but we could get HMODULE16 or the like (think builtin modules)
1779 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1780 if (!wm || (wm->type != MODULE32_PE)) return (PIMAGE_NT_HEADERS)0;
1781 return PE_HEADER(wm->module);
1785 /***************************************************************************
1786 * HasGPHandler (KERNEL.338)
1789 #include "pshpack1.h"
1790 typedef struct _GPHANDLERDEF
1792 WORD selector;
1793 WORD rangeStart;
1794 WORD rangeEnd;
1795 WORD handler;
1796 } GPHANDLERDEF;
1797 #include "poppack.h"
1799 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1801 HMODULE16 hModule;
1802 int gpOrdinal;
1803 SEGPTR gpPtr;
1804 GPHANDLERDEF *gpHandler;
1806 if ( (hModule = FarGetOwner16( SELECTOROF(address) )) != 0
1807 && (gpOrdinal = NE_GetOrdinal( hModule, "__GP" )) != 0
1808 && (gpPtr = (SEGPTR)NE_GetEntryPointEx( hModule, gpOrdinal, FALSE )) != 0
1809 && !IsBadReadPtr16( gpPtr, sizeof(GPHANDLERDEF) )
1810 && (gpHandler = PTR_SEG_TO_LIN( gpPtr )) != NULL )
1812 while (gpHandler->selector)
1814 if ( SELECTOROF(address) == gpHandler->selector
1815 && OFFSETOF(address) >= gpHandler->rangeStart
1816 && OFFSETOF(address) < gpHandler->rangeEnd )
1817 return PTR_SEG_OFF_TO_SEGPTR( gpHandler->selector,
1818 gpHandler->handler );
1819 gpHandler++;
1823 return 0;