Francois Boisvert
[wine.git] / loader / module.c
blob65a9624ac9636aea9a99cdc61b8f8b925994c62c
1 /*
2 * Modules
4 * Copyright 1995 Alexandre Julliard
5 */
7 #include <assert.h>
8 #include <fcntl.h>
9 #include <stdlib.h>
10 #include <stdio.h>
11 #include <string.h>
12 #include <sys/types.h>
13 #include <unistd.h>
14 #include "windef.h"
15 #include "wingdi.h"
16 #include "wine/winbase16.h"
17 #include "wine/winuser16.h"
18 #include "winerror.h"
19 #include "file.h"
20 #include "global.h"
21 #include "heap.h"
22 #include "module.h"
23 #include "snoop.h"
24 #include "neexe.h"
25 #include "pe_image.h"
26 #include "dosexe.h"
27 #include "process.h"
28 #include "syslevel.h"
29 #include "thread.h"
30 #include "selectors.h"
31 #include "stackframe.h"
32 #include "task.h"
33 #include "debugtools.h"
34 #include "callback.h"
35 #include "loadorder.h"
36 #include "elfdll.h"
37 #include "server.h"
39 DEFAULT_DEBUG_CHANNEL(module);
40 DECLARE_DEBUG_CHANNEL(win32);
42 /*************************************************************************
43 * MODULE_WalkModref
44 * Walk MODREFs for input process ID
46 void MODULE_WalkModref( DWORD id )
48 int i;
49 WINE_MODREF *zwm, *prev = NULL;
50 PDB *pdb = PROCESS_IdToPDB( id );
52 if (!pdb) {
53 MESSAGE("Invalid process id (pid)\n");
54 return;
57 MESSAGE("Modref list for process pdb=%p\n", pdb);
58 MESSAGE("Modref next prev handle deps flags name\n");
59 for ( zwm = pdb->modref_list; zwm; zwm = zwm->next) {
60 MESSAGE("%p %p %p %04x %5d %04x %s\n", zwm, zwm->next, zwm->prev,
61 zwm->module, zwm->nDeps, zwm->flags, zwm->modname);
62 for ( i = 0; i < zwm->nDeps; i++ ) {
63 if ( zwm->deps[i] )
64 MESSAGE(" %d %p %s\n", i, zwm->deps[i], zwm->deps[i]->modname);
66 if (prev != zwm->prev)
67 MESSAGE(" --> modref corrupt, previous pointer wrong!!\n");
68 prev = zwm;
72 /*************************************************************************
73 * MODULE32_LookupHMODULE
74 * looks for the referenced HMODULE in the current process
76 WINE_MODREF *MODULE32_LookupHMODULE( HMODULE hmod )
78 WINE_MODREF *wm;
80 if (!hmod)
81 return PROCESS_Current()->exe_modref;
83 if (!HIWORD(hmod)) {
84 ERR("tried to lookup 0x%04x in win32 module handler!\n",hmod);
85 return NULL;
87 for ( wm = PROCESS_Current()->modref_list; wm; wm=wm->next )
88 if (wm->module == hmod)
89 return wm;
90 return NULL;
93 /*************************************************************************
94 * MODULE_InitDll
96 static BOOL MODULE_InitDll( WINE_MODREF *wm, DWORD type, LPVOID lpReserved )
98 BOOL retv = TRUE;
100 static LPCSTR typeName[] = { "PROCESS_DETACH", "PROCESS_ATTACH",
101 "THREAD_ATTACH", "THREAD_DETACH" };
102 assert( wm );
105 /* Skip calls for modules loaded with special load flags */
107 if ( ( wm->flags & WINE_MODREF_DONT_RESOLVE_REFS )
108 || ( wm->flags & WINE_MODREF_LOAD_AS_DATAFILE ) )
109 return TRUE;
112 TRACE("(%s,%s,%p) - CALL\n", wm->modname, typeName[type], lpReserved );
114 /* Call the initialization routine */
115 switch ( wm->type )
117 case MODULE32_PE:
118 retv = PE_InitDLL( wm, type, lpReserved );
119 break;
121 case MODULE32_ELF:
122 /* no need to do that, dlopen() already does */
123 break;
125 default:
126 ERR("wine_modref type %d not handled.\n", wm->type );
127 retv = FALSE;
128 break;
131 /* The state of the module list may have changed due to the call
132 to PE_InitDLL. We cannot assume that this module has not been
133 deleted. */
134 TRACE("(%p,%s,%p) - RETURN %d\n", wm, typeName[type], lpReserved, retv );
136 return retv;
139 /*************************************************************************
140 * MODULE_DllProcessAttach
142 * Send the process attach notification to all DLLs the given module
143 * depends on (recursively). This is somewhat complicated due to the fact that
145 * - we have to respect the module dependencies, i.e. modules implicitly
146 * referenced by another module have to be initialized before the module
147 * itself can be initialized
149 * - the initialization routine of a DLL can itself call LoadLibrary,
150 * thereby introducing a whole new set of dependencies (even involving
151 * the 'old' modules) at any time during the whole process
153 * (Note that this routine can be recursively entered not only directly
154 * from itself, but also via LoadLibrary from one of the called initialization
155 * routines.)
157 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
158 * the process *detach* notifications to be sent in the correct order.
159 * This must not only take into account module dependencies, but also
160 * 'hidden' dependencies created by modules calling LoadLibrary in their
161 * attach notification routine.
163 * The strategy is rather simple: we move a WINE_MODREF to the head of the
164 * list after the attach notification has returned. This implies that the
165 * detach notifications are called in the reverse of the sequence the attach
166 * notifications *returned*.
168 * NOTE: Assumes that the process critical section is held!
171 BOOL MODULE_DllProcessAttach( WINE_MODREF *wm, LPVOID lpReserved )
173 BOOL retv = TRUE;
174 int i;
175 assert( wm );
177 /* prevent infinite recursion in case of cyclical dependencies */
178 if ( ( wm->flags & WINE_MODREF_MARKER )
179 || ( wm->flags & WINE_MODREF_PROCESS_ATTACHED ) )
180 return retv;
182 TRACE("(%s,%p) - START\n", wm->modname, lpReserved );
184 /* Tag current MODREF to prevent recursive loop */
185 wm->flags |= WINE_MODREF_MARKER;
187 /* Recursively attach all DLLs this one depends on */
188 for ( i = 0; retv && i < wm->nDeps; i++ )
189 if ( wm->deps[i] )
190 retv = MODULE_DllProcessAttach( wm->deps[i], lpReserved );
192 /* Call DLL entry point */
193 if ( retv )
195 retv = MODULE_InitDll( wm, DLL_PROCESS_ATTACH, lpReserved );
196 if ( retv )
197 wm->flags |= WINE_MODREF_PROCESS_ATTACHED;
200 /* Re-insert MODREF at head of list */
201 if ( retv && wm->prev )
203 wm->prev->next = wm->next;
204 if ( wm->next ) wm->next->prev = wm->prev;
206 wm->prev = NULL;
207 wm->next = PROCESS_Current()->modref_list;
208 PROCESS_Current()->modref_list = wm->next->prev = wm;
211 /* Remove recursion flag */
212 wm->flags &= ~WINE_MODREF_MARKER;
214 TRACE("(%s,%p) - END\n", wm->modname, lpReserved );
216 return retv;
219 /*************************************************************************
220 * MODULE_DllProcessDetach
222 * Send DLL process detach notifications. See the comment about calling
223 * sequence at MODULE_DllProcessAttach. Unless the bForceDetach flag
224 * is set, only DLLs with zero refcount are notified.
226 void MODULE_DllProcessDetach( BOOL bForceDetach, LPVOID lpReserved )
228 WINE_MODREF *wm;
230 EnterCriticalSection( &PROCESS_Current()->crit_section );
234 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
236 /* Check whether to detach this DLL */
237 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
238 continue;
239 if ( wm->refCount > 0 && !bForceDetach )
240 continue;
242 /* Call detach notification */
243 wm->flags &= ~WINE_MODREF_PROCESS_ATTACHED;
244 MODULE_InitDll( wm, DLL_PROCESS_DETACH, lpReserved );
246 /* Restart at head of WINE_MODREF list, as entries might have
247 been added and/or removed while performing the call ... */
248 break;
250 } while ( wm );
252 LeaveCriticalSection( &PROCESS_Current()->crit_section );
255 /*************************************************************************
256 * MODULE_DllThreadAttach
258 * Send DLL thread attach notifications. These are sent in the
259 * reverse sequence of process detach notification.
262 void MODULE_DllThreadAttach( LPVOID lpReserved )
264 WINE_MODREF *wm;
266 EnterCriticalSection( &PROCESS_Current()->crit_section );
268 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
269 if ( !wm->next )
270 break;
272 for ( ; wm; wm = wm->prev )
274 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
275 continue;
276 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
277 continue;
279 MODULE_InitDll( wm, DLL_THREAD_ATTACH, lpReserved );
282 LeaveCriticalSection( &PROCESS_Current()->crit_section );
285 /*************************************************************************
286 * MODULE_DllThreadDetach
288 * Send DLL thread detach notifications. These are sent in the
289 * same sequence as process detach notification.
292 void MODULE_DllThreadDetach( LPVOID lpReserved )
294 WINE_MODREF *wm;
296 EnterCriticalSection( &PROCESS_Current()->crit_section );
298 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
300 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
301 continue;
302 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
303 continue;
305 MODULE_InitDll( wm, DLL_THREAD_DETACH, lpReserved );
308 LeaveCriticalSection( &PROCESS_Current()->crit_section );
311 /****************************************************************************
312 * DisableThreadLibraryCalls (KERNEL32.74)
314 * Don't call DllEntryPoint for DLL_THREAD_{ATTACH,DETACH} if set.
316 BOOL WINAPI DisableThreadLibraryCalls( HMODULE hModule )
318 WINE_MODREF *wm;
319 BOOL retval = TRUE;
321 EnterCriticalSection( &PROCESS_Current()->crit_section );
323 wm = MODULE32_LookupHMODULE( hModule );
324 if ( !wm )
325 retval = FALSE;
326 else
327 wm->flags |= WINE_MODREF_NO_DLL_CALLS;
329 LeaveCriticalSection( &PROCESS_Current()->crit_section );
331 return retval;
335 /***********************************************************************
336 * MODULE_CreateDummyModule
338 * Create a dummy NE module for Win32 or Winelib.
340 HMODULE MODULE_CreateDummyModule( LPCSTR filename, HMODULE module32 )
342 HMODULE hModule;
343 NE_MODULE *pModule;
344 SEGTABLEENTRY *pSegment;
345 char *pStr,*s;
346 unsigned int len;
347 const char* basename;
348 OFSTRUCT *ofs;
349 int of_size, size;
351 /* Extract base filename */
352 basename = strrchr(filename, '\\');
353 if (!basename) basename = filename;
354 else basename++;
355 len = strlen(basename);
356 if ((s = strchr(basename, '.'))) len = s - basename;
358 /* Allocate module */
359 of_size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName)
360 + strlen(filename) + 1;
361 size = sizeof(NE_MODULE) +
362 /* loaded file info */
363 of_size +
364 /* segment table: DS,CS */
365 2 * sizeof(SEGTABLEENTRY) +
366 /* name table */
367 len + 2 +
368 /* several empty tables */
371 hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
372 if (!hModule) return (HMODULE)11; /* invalid exe */
374 FarSetOwner16( hModule, hModule );
375 pModule = (NE_MODULE *)GlobalLock16( hModule );
377 /* Set all used entries */
378 pModule->magic = IMAGE_OS2_SIGNATURE;
379 pModule->count = 1;
380 pModule->next = 0;
381 pModule->flags = 0;
382 pModule->dgroup = 0;
383 pModule->ss = 1;
384 pModule->cs = 2;
385 pModule->heap_size = 0;
386 pModule->stack_size = 0;
387 pModule->seg_count = 2;
388 pModule->modref_count = 0;
389 pModule->nrname_size = 0;
390 pModule->fileinfo = sizeof(NE_MODULE);
391 pModule->os_flags = NE_OSFLAGS_WINDOWS;
392 pModule->self = hModule;
393 pModule->module32 = module32;
395 /* Set version and flags */
396 if (module32)
398 pModule->expected_version =
399 ((PE_HEADER(module32)->OptionalHeader.MajorSubsystemVersion & 0xff) << 8 ) |
400 (PE_HEADER(module32)->OptionalHeader.MinorSubsystemVersion & 0xff);
401 pModule->flags |= NE_FFLAGS_WIN32;
402 if (PE_HEADER(module32)->FileHeader.Characteristics & IMAGE_FILE_DLL)
403 pModule->flags |= NE_FFLAGS_LIBMODULE | NE_FFLAGS_SINGLEDATA;
406 /* Set loaded file information */
407 ofs = (OFSTRUCT *)(pModule + 1);
408 memset( ofs, 0, of_size );
409 ofs->cBytes = of_size < 256 ? of_size : 255; /* FIXME */
410 strcpy( ofs->szPathName, filename );
412 pSegment = (SEGTABLEENTRY*)((char*)(pModule + 1) + of_size);
413 pModule->seg_table = (int)pSegment - (int)pModule;
414 /* Data segment */
415 pSegment->size = 0;
416 pSegment->flags = NE_SEGFLAGS_DATA;
417 pSegment->minsize = 0x1000;
418 pSegment++;
419 /* Code segment */
420 pSegment->flags = 0;
421 pSegment++;
423 /* Module name */
424 pStr = (char *)pSegment;
425 pModule->name_table = (int)pStr - (int)pModule;
426 assert(len<256);
427 *pStr = len;
428 lstrcpynA( pStr+1, basename, len+1 );
429 pStr += len+2;
431 /* All tables zero terminated */
432 pModule->res_table = pModule->import_table = pModule->entry_table =
433 (int)pStr - (int)pModule;
435 NE_RegisterModule( pModule );
436 return hModule;
440 /**********************************************************************
441 * MODULE_FindModule32
443 * Find a (loaded) win32 module depending on path
445 * RETURNS
446 * the module handle if found
447 * 0 if not
449 WINE_MODREF *MODULE_FindModule(
450 LPCSTR path /* [in] pathname of module/library to be found */
452 WINE_MODREF *wm;
453 char dllname[260], *p;
455 /* Append .DLL to name if no extension present */
456 strcpy( dllname, path );
457 if (!(p = strrchr( dllname, '.')) || strchr( p, '/' ) || strchr( p, '\\'))
458 strcat( dllname, ".DLL" );
460 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
462 if ( !strcasecmp( dllname, wm->modname ) )
463 break;
464 if ( !strcasecmp( dllname, wm->filename ) )
465 break;
466 if ( !strcasecmp( dllname, wm->short_modname ) )
467 break;
468 if ( !strcasecmp( dllname, wm->short_filename ) )
469 break;
472 return wm;
475 /***********************************************************************
476 * MODULE_GetBinaryType
478 * The GetBinaryType function determines whether a file is executable
479 * or not and if it is it returns what type of executable it is.
480 * The type of executable is a property that determines in which
481 * subsystem an executable file runs under.
483 * Binary types returned:
484 * SCS_32BIT_BINARY: A Win32 based application
485 * SCS_DOS_BINARY: An MS-Dos based application
486 * SCS_WOW_BINARY: A Win16 based application
487 * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
488 * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
489 * SCS_OS216_BINARY: A 16bit OS/2 based application
491 * Returns TRUE if the file is an executable in which case
492 * the value pointed by lpBinaryType is set.
493 * Returns FALSE if the file is not an executable or if the function fails.
495 * To do so it opens the file and reads in the header information
496 * if the extended header information is not present it will
497 * assume that the file is a DOS executable.
498 * If the extended header information is present it will
499 * determine if the file is a 16 or 32 bit Windows executable
500 * by check the flags in the header.
502 * Note that .COM and .PIF files are only recognized by their
503 * file name extension; but Windows does it the same way ...
505 static BOOL MODULE_GetBinaryType( HANDLE hfile, LPCSTR filename,
506 LPDWORD lpBinaryType )
508 IMAGE_DOS_HEADER mz_header;
509 char magic[4], *ptr;
510 DWORD len;
512 /* Seek to the start of the file and read the DOS header information.
514 if ( SetFilePointer( hfile, 0, NULL, SEEK_SET ) != -1
515 && ReadFile( hfile, &mz_header, sizeof(mz_header), &len, NULL )
516 && len == sizeof(mz_header) )
518 /* Now that we have the header check the e_magic field
519 * to see if this is a dos image.
521 if ( mz_header.e_magic == IMAGE_DOS_SIGNATURE )
523 BOOL lfanewValid = FALSE;
524 /* We do have a DOS image so we will now try to seek into
525 * the file by the amount indicated by the field
526 * "Offset to extended header" and read in the
527 * "magic" field information at that location.
528 * This will tell us if there is more header information
529 * to read or not.
531 /* But before we do we will make sure that header
532 * structure encompasses the "Offset to extended header"
533 * field.
535 if ( (mz_header.e_cparhdr<<4) >= sizeof(IMAGE_DOS_HEADER) )
536 if ( ( mz_header.e_crlc == 0 ) ||
537 ( mz_header.e_lfarlc >= sizeof(IMAGE_DOS_HEADER) ) )
538 if ( mz_header.e_lfanew >= sizeof(IMAGE_DOS_HEADER)
539 && SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET ) != -1
540 && ReadFile( hfile, magic, sizeof(magic), &len, NULL )
541 && len == sizeof(magic) )
542 lfanewValid = TRUE;
544 if ( !lfanewValid )
546 /* If we cannot read this "extended header" we will
547 * assume that we have a simple DOS executable.
549 *lpBinaryType = SCS_DOS_BINARY;
550 return TRUE;
552 else
554 /* Reading the magic field succeeded so
555 * we will try to determine what type it is.
557 if ( *(DWORD*)magic == IMAGE_NT_SIGNATURE )
559 /* This is an NT signature.
561 *lpBinaryType = SCS_32BIT_BINARY;
562 return TRUE;
564 else if ( *(WORD*)magic == IMAGE_OS2_SIGNATURE )
566 /* The IMAGE_OS2_SIGNATURE indicates that the
567 * "extended header is a Windows executable (NE)
568 * header." This can mean either a 16-bit OS/2
569 * or a 16-bit Windows or even a DOS program
570 * (running under a DOS extender). To decide
571 * which, we'll have to read the NE header.
574 IMAGE_OS2_HEADER ne;
575 if ( SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET ) != -1
576 && ReadFile( hfile, &ne, sizeof(ne), &len, NULL )
577 && len == sizeof(ne) )
579 switch ( ne.ne_exetyp )
581 case 2: *lpBinaryType = SCS_WOW_BINARY; return TRUE;
582 case 5: *lpBinaryType = SCS_DOS_BINARY; return TRUE;
583 default: *lpBinaryType = SCS_OS216_BINARY; return TRUE;
586 /* Couldn't read header, so abort. */
587 return FALSE;
589 else
591 /* Unknown extended header, but this file is nonetheless
592 DOS-executable.
594 *lpBinaryType = SCS_DOS_BINARY;
595 return TRUE;
601 /* If we get here, we don't even have a correct MZ header.
602 * Try to check the file extension for known types ...
604 ptr = strrchr( filename, '.' );
605 if ( ptr && !strchr( ptr, '\\' ) && !strchr( ptr, '/' ) )
607 if ( !lstrcmpiA( ptr, ".COM" ) )
609 *lpBinaryType = SCS_DOS_BINARY;
610 return TRUE;
613 if ( !lstrcmpiA( ptr, ".PIF" ) )
615 *lpBinaryType = SCS_PIF_BINARY;
616 return TRUE;
620 return FALSE;
623 /***********************************************************************
624 * GetBinaryTypeA [KERNEL32.280]
626 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
628 BOOL ret = FALSE;
629 HANDLE hfile;
631 TRACE_(win32)("%s\n", lpApplicationName );
633 /* Sanity check.
635 if ( lpApplicationName == NULL || lpBinaryType == NULL )
636 return FALSE;
638 /* Open the file indicated by lpApplicationName for reading.
640 hfile = CreateFileA( lpApplicationName, GENERIC_READ, 0,
641 NULL, OPEN_EXISTING, 0, -1 );
642 if ( hfile == INVALID_HANDLE_VALUE )
643 return FALSE;
645 /* Check binary type
647 ret = MODULE_GetBinaryType( hfile, lpApplicationName, lpBinaryType );
649 /* Close the file.
651 CloseHandle( hfile );
653 return ret;
656 /***********************************************************************
657 * GetBinaryTypeW [KERNEL32.281]
659 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
661 BOOL ret = FALSE;
662 LPSTR strNew = NULL;
664 TRACE_(win32)("%s\n", debugstr_w(lpApplicationName) );
666 /* Sanity check.
668 if ( lpApplicationName == NULL || lpBinaryType == NULL )
669 return FALSE;
671 /* Convert the wide string to a ascii string.
673 strNew = HEAP_strdupWtoA( GetProcessHeap(), 0, lpApplicationName );
675 if ( strNew != NULL )
677 ret = GetBinaryTypeA( strNew, lpBinaryType );
679 /* Free the allocated string.
681 HeapFree( GetProcessHeap(), 0, strNew );
684 return ret;
688 /***********************************************************************
689 * WinExec16 (KERNEL.166)
691 HINSTANCE16 WINAPI WinExec16( LPCSTR lpCmdLine, UINT16 nCmdShow )
693 HINSTANCE16 hInst;
695 SYSLEVEL_ReleaseWin16Lock();
696 hInst = WinExec( lpCmdLine, nCmdShow );
697 SYSLEVEL_RestoreWin16Lock();
699 return hInst;
702 /***********************************************************************
703 * WinExec (KERNEL32.566)
705 HINSTANCE WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
707 PROCESS_INFORMATION info;
708 STARTUPINFOA startup;
709 HINSTANCE hInstance;
711 memset( &startup, 0, sizeof(startup) );
712 startup.cb = sizeof(startup);
713 startup.dwFlags = STARTF_USESHOWWINDOW;
714 startup.wShowWindow = nCmdShow;
716 if (CreateProcessA( NULL, (LPSTR)lpCmdLine, NULL, NULL, FALSE,
717 0, NULL, NULL, &startup, &info ))
719 /* Give 30 seconds to the app to come up */
720 if (Callout.WaitForInputIdle ( info.hProcess, 30000 ) == 0xFFFFFFFF)
721 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
723 /* Get 16-bit hInstance/hTask from process */
724 hInstance = GetProcessDword( info.dwProcessId, GPD_HINSTANCE16 );
725 /* If there is no hInstance (32-bit process) return a dummy value
726 * that must be > 31
727 * FIXME: should do this in all cases and fix Win16 callers */
728 if (!hInstance) hInstance = 33;
730 /* Close off the handles */
731 CloseHandle( info.hThread );
732 CloseHandle( info.hProcess );
734 else if ((hInstance = GetLastError()) >= 32)
736 FIXME("Strange error set by CreateProcess: %d\n", hInstance );
737 hInstance = 11;
740 return hInstance;
743 /**********************************************************************
744 * LoadModule (KERNEL32.499)
746 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
748 LOADPARAMS *params = (LOADPARAMS *)paramBlock;
749 PROCESS_INFORMATION info;
750 STARTUPINFOA startup;
751 HINSTANCE hInstance;
752 LPSTR cmdline, p;
753 char filename[MAX_PATH];
754 BYTE len;
756 if (!name) return ERROR_FILE_NOT_FOUND;
758 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
759 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
760 return GetLastError();
762 len = (BYTE)params->lpCmdLine[0];
763 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
764 return ERROR_NOT_ENOUGH_MEMORY;
766 strcpy( cmdline, filename );
767 p = cmdline + strlen(cmdline);
768 *p++ = ' ';
769 memcpy( p, params->lpCmdLine + 1, len );
770 p[len] = 0;
772 memset( &startup, 0, sizeof(startup) );
773 startup.cb = sizeof(startup);
774 if (params->lpCmdShow)
776 startup.dwFlags = STARTF_USESHOWWINDOW;
777 startup.wShowWindow = params->lpCmdShow[1];
780 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
781 params->lpEnvAddress, NULL, &startup, &info ))
783 /* Give 30 seconds to the app to come up */
784 if ( Callout.WaitForInputIdle ( info.hProcess, 30000 ) == 0xFFFFFFFF )
785 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
787 /* Get 16-bit hInstance/hTask from process */
788 hInstance = GetProcessDword( info.dwProcessId, GPD_HINSTANCE16 );
789 /* If there is no hInstance (32-bit process) return a dummy value
790 * that must be > 31
791 * FIXME: should do this in all cases and fix Win16 callers */
792 if (!hInstance) hInstance = 33;
793 /* Close off the handles */
794 CloseHandle( info.hThread );
795 CloseHandle( info.hProcess );
797 else if ((hInstance = GetLastError()) >= 32)
799 FIXME("Strange error set by CreateProcess: %d\n", hInstance );
800 hInstance = 11;
803 HeapFree( GetProcessHeap(), 0, cmdline );
804 return hInstance;
808 /*************************************************************************
809 * get_file_name
811 * Helper for CreateProcess: retrieve the file name to load from the
812 * app name and command line. Store the file name in buffer, and
813 * return a possibly modified command line.
815 static LPSTR get_file_name( LPCSTR appname, LPSTR cmdline, LPSTR buffer, int buflen )
817 char *name, *pos, *ret = NULL;
818 const char *p;
820 /* if we have an app name, everything is easy */
822 if (appname)
824 /* use the unmodified app name as file name */
825 lstrcpynA( buffer, appname, buflen );
826 if (!(ret = cmdline))
828 /* no command-line, create one */
829 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(appname) + 3 )))
830 sprintf( ret, "\"%s\"", appname );
832 return ret;
835 if (!cmdline)
837 SetLastError( ERROR_INVALID_PARAMETER );
838 return NULL;
841 /* first check for a quoted file name */
843 if ((cmdline[0] == '"') && ((p = strchr( cmdline + 1, '"' ))))
845 int len = p - cmdline - 1;
846 /* extract the quoted portion as file name */
847 if (!(name = HeapAlloc( GetProcessHeap(), 0, len + 1 ))) return NULL;
848 memcpy( name, cmdline + 1, len );
849 name[len] = 0;
851 if (SearchPathA( NULL, name, ".exe", buflen, buffer, NULL ) ||
852 SearchPathA( NULL, name, NULL, buflen, buffer, NULL ))
853 ret = cmdline; /* no change necessary */
854 goto done;
857 /* now try the command-line word by word */
859 if (!(name = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 1 ))) return NULL;
860 pos = name;
861 p = cmdline;
863 while (*p)
865 do *pos++ = *p++; while (*p && *p != ' ');
866 *pos = 0;
867 TRACE("trying '%s'\n", name );
868 if (SearchPathA( NULL, name, ".exe", buflen, buffer, NULL ) ||
869 SearchPathA( NULL, name, NULL, buflen, buffer, NULL ))
871 ret = cmdline;
872 break;
876 if (!ret || !strchr( name, ' ' )) goto done; /* no change necessary */
878 /* now build a new command-line with quotes */
880 if (!(ret = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 3 ))) goto done;
881 sprintf( ret, "\"%s\"%s", name, p );
883 done:
884 HeapFree( GetProcessHeap(), 0, name );
885 return ret;
889 /**********************************************************************
890 * CreateProcessA (KERNEL32.171)
892 BOOL WINAPI CreateProcessA( LPCSTR lpApplicationName, LPSTR lpCommandLine,
893 LPSECURITY_ATTRIBUTES lpProcessAttributes,
894 LPSECURITY_ATTRIBUTES lpThreadAttributes,
895 BOOL bInheritHandles, DWORD dwCreationFlags,
896 LPVOID lpEnvironment, LPCSTR lpCurrentDirectory,
897 LPSTARTUPINFOA lpStartupInfo,
898 LPPROCESS_INFORMATION lpProcessInfo )
900 BOOL retv = FALSE;
901 HANDLE hFile;
902 DWORD type;
903 char name[MAX_PATH];
904 LPSTR tidy_cmdline;
906 /* Process the AppName and/or CmdLine to get module name and path */
908 if (!(tidy_cmdline = get_file_name( lpApplicationName, lpCommandLine, name, sizeof(name) )))
909 return FALSE;
911 /* Warn if unsupported features are used */
913 if (dwCreationFlags & DETACHED_PROCESS)
914 FIXME("(%s,...): DETACHED_PROCESS ignored\n", name);
915 if (dwCreationFlags & CREATE_NEW_CONSOLE)
916 FIXME("(%s,...): CREATE_NEW_CONSOLE ignored\n", name);
917 if (dwCreationFlags & NORMAL_PRIORITY_CLASS)
918 FIXME("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
919 if (dwCreationFlags & IDLE_PRIORITY_CLASS)
920 FIXME("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
921 if (dwCreationFlags & HIGH_PRIORITY_CLASS)
922 FIXME("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
923 if (dwCreationFlags & REALTIME_PRIORITY_CLASS)
924 FIXME("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
925 if (dwCreationFlags & CREATE_NEW_PROCESS_GROUP)
926 FIXME("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
927 if (dwCreationFlags & CREATE_UNICODE_ENVIRONMENT)
928 FIXME("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
929 if (dwCreationFlags & CREATE_SEPARATE_WOW_VDM)
930 FIXME("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
931 if (dwCreationFlags & CREATE_SHARED_WOW_VDM)
932 FIXME("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
933 if (dwCreationFlags & CREATE_DEFAULT_ERROR_MODE)
934 FIXME("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
935 if (dwCreationFlags & CREATE_NO_WINDOW)
936 FIXME("(%s,...): CREATE_NO_WINDOW ignored\n", name);
937 if (dwCreationFlags & PROFILE_USER)
938 FIXME("(%s,...): PROFILE_USER ignored\n", name);
939 if (dwCreationFlags & PROFILE_KERNEL)
940 FIXME("(%s,...): PROFILE_KERNEL ignored\n", name);
941 if (dwCreationFlags & PROFILE_SERVER)
942 FIXME("(%s,...): PROFILE_SERVER ignored\n", name);
943 if (lpCurrentDirectory)
944 FIXME("(%s,...): lpCurrentDirectory %s ignored\n",
945 name, lpCurrentDirectory);
946 if (lpStartupInfo->lpDesktop)
947 FIXME("(%s,...): lpStartupInfo->lpDesktop %s ignored\n",
948 name, lpStartupInfo->lpDesktop);
949 if (lpStartupInfo->lpTitle)
950 FIXME("(%s,...): lpStartupInfo->lpTitle %s ignored\n",
951 name, lpStartupInfo->lpTitle);
952 if (lpStartupInfo->dwFlags & STARTF_USECOUNTCHARS)
953 FIXME("(%s,...): STARTF_USECOUNTCHARS (%ld,%ld) ignored\n",
954 name, lpStartupInfo->dwXCountChars, lpStartupInfo->dwYCountChars);
955 if (lpStartupInfo->dwFlags & STARTF_USEFILLATTRIBUTE)
956 FIXME("(%s,...): STARTF_USEFILLATTRIBUTE %lx ignored\n",
957 name, lpStartupInfo->dwFillAttribute);
958 if (lpStartupInfo->dwFlags & STARTF_RUNFULLSCREEN)
959 FIXME("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
960 if (lpStartupInfo->dwFlags & STARTF_FORCEONFEEDBACK)
961 FIXME("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
962 if (lpStartupInfo->dwFlags & STARTF_FORCEOFFFEEDBACK)
963 FIXME("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
964 if (lpStartupInfo->dwFlags & STARTF_USEHOTKEY)
965 FIXME("(%s,...): STARTF_USEHOTKEY ignored\n", name);
967 /* Open file and determine executable type */
969 hFile = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, -1 );
970 if (hFile == INVALID_HANDLE_VALUE) goto done;
972 if ( !MODULE_GetBinaryType( hFile, name, &type ) )
974 CloseHandle( hFile );
975 /* FIXME: Try Unix executable only when appropriate! */
976 retv = PROCESS_CreateUnixProcess( name, tidy_cmdline, lpEnvironment,
977 lpProcessAttributes, lpThreadAttributes,
978 bInheritHandles, dwCreationFlags,
979 lpStartupInfo, lpProcessInfo );
980 goto done;
983 /* Create process */
985 switch ( type )
987 case SCS_32BIT_BINARY:
988 retv = PE_CreateProcess( hFile, name, tidy_cmdline, lpEnvironment,
989 lpProcessAttributes, lpThreadAttributes,
990 bInheritHandles, dwCreationFlags,
991 lpStartupInfo, lpProcessInfo );
992 break;
994 case SCS_DOS_BINARY:
995 retv = MZ_CreateProcess( hFile, name, tidy_cmdline, lpEnvironment,
996 lpProcessAttributes, lpThreadAttributes,
997 bInheritHandles, dwCreationFlags,
998 lpStartupInfo, lpProcessInfo );
999 break;
1001 case SCS_WOW_BINARY:
1002 retv = NE_CreateProcess( hFile, name, tidy_cmdline, lpEnvironment,
1003 lpProcessAttributes, lpThreadAttributes,
1004 bInheritHandles, dwCreationFlags,
1005 lpStartupInfo, lpProcessInfo );
1006 break;
1008 case SCS_PIF_BINARY:
1009 case SCS_POSIX_BINARY:
1010 case SCS_OS216_BINARY:
1011 FIXME("Unsupported executable type: %ld\n", type );
1012 /* fall through */
1014 default:
1015 SetLastError( ERROR_BAD_FORMAT );
1016 break;
1018 CloseHandle( hFile );
1020 done:
1021 if (tidy_cmdline != lpCommandLine) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1022 return retv;
1025 /**********************************************************************
1026 * CreateProcessW (KERNEL32.172)
1027 * NOTES
1028 * lpReserved is not converted
1030 BOOL WINAPI CreateProcessW( LPCWSTR lpApplicationName, LPWSTR lpCommandLine,
1031 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1032 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1033 BOOL bInheritHandles, DWORD dwCreationFlags,
1034 LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory,
1035 LPSTARTUPINFOW lpStartupInfo,
1036 LPPROCESS_INFORMATION lpProcessInfo )
1037 { BOOL ret;
1038 STARTUPINFOA StartupInfoA;
1040 LPSTR lpApplicationNameA = HEAP_strdupWtoA (GetProcessHeap(),0,lpApplicationName);
1041 LPSTR lpCommandLineA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCommandLine);
1042 LPSTR lpCurrentDirectoryA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCurrentDirectory);
1044 memcpy (&StartupInfoA, lpStartupInfo, sizeof(STARTUPINFOA));
1045 StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpDesktop);
1046 StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpTitle);
1048 TRACE_(win32)("(%s,%s,...)\n", debugstr_w(lpApplicationName), debugstr_w(lpCommandLine));
1050 if (lpStartupInfo->lpReserved)
1051 FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n", debugstr_w(lpStartupInfo->lpReserved));
1053 ret = CreateProcessA( lpApplicationNameA, lpCommandLineA,
1054 lpProcessAttributes, lpThreadAttributes,
1055 bInheritHandles, dwCreationFlags,
1056 lpEnvironment, lpCurrentDirectoryA,
1057 &StartupInfoA, lpProcessInfo );
1059 HeapFree( GetProcessHeap(), 0, lpCurrentDirectoryA );
1060 HeapFree( GetProcessHeap(), 0, lpCommandLineA );
1061 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1062 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1064 return ret;
1067 /***********************************************************************
1068 * GetModuleHandleA (KERNEL32.237)
1070 HMODULE WINAPI GetModuleHandleA(LPCSTR module)
1072 WINE_MODREF *wm;
1074 if ( module == NULL )
1075 wm = PROCESS_Current()->exe_modref;
1076 else
1077 wm = MODULE_FindModule( module );
1079 return wm? wm->module : 0;
1082 /***********************************************************************
1083 * GetModuleHandleW
1085 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
1087 HMODULE hModule;
1088 LPSTR modulea = HEAP_strdupWtoA( GetProcessHeap(), 0, module );
1089 hModule = GetModuleHandleA( modulea );
1090 HeapFree( GetProcessHeap(), 0, modulea );
1091 return hModule;
1095 /***********************************************************************
1096 * GetModuleFileNameA (KERNEL32.235)
1098 * GetModuleFileNameA seems to *always* return the long path;
1099 * it's only GetModuleFileName16 that decides between short/long path
1100 * by checking if exe version >= 4.0.
1101 * (SDK docu doesn't mention this)
1103 DWORD WINAPI GetModuleFileNameA(
1104 HMODULE hModule, /* [in] module handle (32bit) */
1105 LPSTR lpFileName, /* [out] filenamebuffer */
1106 DWORD size /* [in] size of filenamebuffer */
1107 ) {
1108 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1110 if (!wm) /* can happen on start up or the like */
1111 return 0;
1113 lstrcpynA( lpFileName, wm->filename, size );
1115 TRACE("%s\n", lpFileName );
1116 return strlen(lpFileName);
1120 /***********************************************************************
1121 * GetModuleFileNameW (KERNEL32.236)
1123 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName,
1124 DWORD size )
1126 LPSTR fnA = (char*)HeapAlloc( GetProcessHeap(), 0, size );
1127 DWORD res = GetModuleFileNameA( hModule, fnA, size );
1128 lstrcpynAtoW( lpFileName, fnA, size );
1129 HeapFree( GetProcessHeap(), 0, fnA );
1130 return res;
1134 /***********************************************************************
1135 * LoadLibraryExA (KERNEL32)
1137 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
1139 WINE_MODREF *wm;
1141 if(!libname)
1143 SetLastError(ERROR_INVALID_PARAMETER);
1144 return 0;
1147 EnterCriticalSection(&PROCESS_Current()->crit_section);
1149 wm = MODULE_LoadLibraryExA( libname, hfile, flags );
1150 if ( wm )
1152 if ( !MODULE_DllProcessAttach( wm, NULL ) )
1154 WARN_(module)("Attach failed for module '%s', \n", libname);
1155 MODULE_FreeLibrary(wm);
1156 SetLastError(ERROR_DLL_INIT_FAILED);
1157 wm = NULL;
1161 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1163 return wm ? wm->module : 0;
1166 /***********************************************************************
1167 * MODULE_LoadLibraryExA (internal)
1169 * Load a PE style module according to the load order.
1171 * The HFILE parameter is not used and marked reserved in the SDK. I can
1172 * only guess that it should force a file to be mapped, but I rather
1173 * ignore the parameter because it would be extremely difficult to
1174 * integrate this with different types of module represenations.
1177 WINE_MODREF *MODULE_LoadLibraryExA( LPCSTR libname, HFILE hfile, DWORD flags )
1179 DWORD err = GetLastError();
1180 WINE_MODREF *pwm;
1181 int i;
1182 module_loadorder_t *plo;
1184 EnterCriticalSection(&PROCESS_Current()->crit_section);
1186 /* Check for already loaded module */
1187 if((pwm = MODULE_FindModule(libname)))
1189 if(!(pwm->flags & WINE_MODREF_MARKER))
1190 pwm->refCount++;
1191 TRACE("Already loaded module '%s' at 0x%08x, count=%d, \n", libname, pwm->module, pwm->refCount);
1192 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1193 return pwm;
1196 plo = MODULE_GetLoadOrder(libname);
1198 for(i = 0; i < MODULE_LOADORDER_NTYPES; i++)
1200 SetLastError( ERROR_FILE_NOT_FOUND );
1201 switch(plo->loadorder[i])
1203 case MODULE_LOADORDER_DLL:
1204 TRACE("Trying native dll '%s'\n", libname);
1205 pwm = PE_LoadLibraryExA(libname, flags);
1206 break;
1208 case MODULE_LOADORDER_ELFDLL:
1209 TRACE("Trying elfdll '%s'\n", libname);
1210 if (!(pwm = BUILTIN32_LoadLibraryExA(libname, flags)))
1211 pwm = ELFDLL_LoadLibraryExA(libname, flags);
1212 break;
1214 case MODULE_LOADORDER_SO:
1215 TRACE("Trying so-library '%s'\n", libname);
1216 if (!(pwm = BUILTIN32_LoadLibraryExA(libname, flags)))
1217 pwm = ELF_LoadLibraryExA(libname, flags);
1218 break;
1220 case MODULE_LOADORDER_BI:
1221 TRACE("Trying built-in '%s'\n", libname);
1222 pwm = BUILTIN32_LoadLibraryExA(libname, flags);
1223 break;
1225 default:
1226 ERR("Got invalid loadorder type %d (%s index %d)\n", plo->loadorder[i], plo->modulename, i);
1227 /* Fall through */
1229 case MODULE_LOADORDER_INVALID: /* We ignore this as it is an empty entry */
1230 pwm = NULL;
1231 break;
1234 if(pwm)
1236 /* Initialize DLL just loaded */
1237 TRACE("Loaded module '%s' at 0x%08x, \n", libname, pwm->module);
1239 /* Set the refCount here so that an attach failure will */
1240 /* decrement the dependencies through the MODULE_FreeLibrary call. */
1241 pwm->refCount++;
1243 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1244 SetLastError( err ); /* restore last error */
1245 return pwm;
1248 if(GetLastError() != ERROR_FILE_NOT_FOUND)
1249 break;
1252 WARN("Failed to load module '%s'; error=0x%08lx, \n", libname, GetLastError());
1253 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1254 return NULL;
1257 /***********************************************************************
1258 * LoadLibraryA (KERNEL32)
1260 HMODULE WINAPI LoadLibraryA(LPCSTR libname) {
1261 return LoadLibraryExA(libname,0,0);
1264 /***********************************************************************
1265 * LoadLibraryW (KERNEL32)
1267 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
1269 return LoadLibraryExW(libnameW,0,0);
1272 /***********************************************************************
1273 * LoadLibrary32_16 (KERNEL.452)
1275 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
1277 HMODULE hModule;
1279 SYSLEVEL_ReleaseWin16Lock();
1280 hModule = LoadLibraryA( libname );
1281 SYSLEVEL_RestoreWin16Lock();
1283 return hModule;
1286 /***********************************************************************
1287 * LoadLibraryExW (KERNEL32)
1289 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW,HANDLE hfile,DWORD flags)
1291 LPSTR libnameA = HEAP_strdupWtoA( GetProcessHeap(), 0, libnameW );
1292 HMODULE ret = LoadLibraryExA( libnameA , hfile, flags );
1294 HeapFree( GetProcessHeap(), 0, libnameA );
1295 return ret;
1298 /***********************************************************************
1299 * MODULE_FlushModrefs
1301 * NOTE: Assumes that the process critical section is held!
1303 * Remove all unused modrefs and call the internal unloading routines
1304 * for the library type.
1306 static void MODULE_FlushModrefs(void)
1308 WINE_MODREF *wm, *next;
1310 for(wm = PROCESS_Current()->modref_list; wm; wm = next)
1312 next = wm->next;
1314 if(wm->refCount)
1315 continue;
1317 /* Unlink this modref from the chain */
1318 if(wm->next)
1319 wm->next->prev = wm->prev;
1320 if(wm->prev)
1321 wm->prev->next = wm->next;
1322 if(wm == PROCESS_Current()->modref_list)
1323 PROCESS_Current()->modref_list = wm->next;
1326 * The unloaders are also responsible for freeing the modref itself
1327 * because the loaders were responsible for allocating it.
1329 switch(wm->type)
1331 case MODULE32_PE: if ( !(wm->flags & WINE_MODREF_INTERNAL) )
1332 PE_UnloadLibrary(wm);
1333 else
1334 BUILTIN32_UnloadLibrary(wm);
1335 break;
1336 case MODULE32_ELF: ELF_UnloadLibrary(wm); break;
1337 case MODULE32_ELFDLL: ELFDLL_UnloadLibrary(wm); break;
1339 default:
1340 ERR("Invalid or unhandled MODREF type %d encountered (wm=%p)\n", wm->type, wm);
1345 /***********************************************************************
1346 * FreeLibrary
1348 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
1350 BOOL retv = FALSE;
1351 WINE_MODREF *wm;
1353 EnterCriticalSection( &PROCESS_Current()->crit_section );
1354 PROCESS_Current()->free_lib_count++;
1356 wm = MODULE32_LookupHMODULE( hLibModule );
1357 if ( !wm || !hLibModule )
1358 SetLastError( ERROR_INVALID_HANDLE );
1359 else
1360 retv = MODULE_FreeLibrary( wm );
1362 PROCESS_Current()->free_lib_count--;
1363 LeaveCriticalSection( &PROCESS_Current()->crit_section );
1365 return retv;
1368 /***********************************************************************
1369 * MODULE_DecRefCount
1371 * NOTE: Assumes that the process critical section is held!
1373 static void MODULE_DecRefCount( WINE_MODREF *wm )
1375 int i;
1377 if ( wm->flags & WINE_MODREF_MARKER )
1378 return;
1380 if ( wm->refCount <= 0 )
1381 return;
1383 --wm->refCount;
1384 TRACE("(%s) refCount: %d\n", wm->modname, wm->refCount );
1386 if ( wm->refCount == 0 )
1388 wm->flags |= WINE_MODREF_MARKER;
1390 for ( i = 0; i < wm->nDeps; i++ )
1391 if ( wm->deps[i] )
1392 MODULE_DecRefCount( wm->deps[i] );
1394 wm->flags &= ~WINE_MODREF_MARKER;
1398 /***********************************************************************
1399 * MODULE_FreeLibrary
1401 * NOTE: Assumes that the process critical section is held!
1403 BOOL MODULE_FreeLibrary( WINE_MODREF *wm )
1405 TRACE("(%s) - START\n", wm->modname );
1407 /* Recursively decrement reference counts */
1408 MODULE_DecRefCount( wm );
1410 /* Call process detach notifications */
1411 if ( PROCESS_Current()->free_lib_count <= 1 )
1413 struct unload_dll_request *req = get_req_buffer();
1415 MODULE_DllProcessDetach( FALSE, NULL );
1416 req->base = (void *)wm->module;
1417 server_call_noerr( REQ_UNLOAD_DLL );
1419 MODULE_FlushModrefs();
1422 TRACE("END\n");
1424 return TRUE;
1428 /***********************************************************************
1429 * FreeLibraryAndExitThread
1431 VOID WINAPI FreeLibraryAndExitThread(HINSTANCE hLibModule, DWORD dwExitCode)
1433 FreeLibrary(hLibModule);
1434 ExitThread(dwExitCode);
1437 /***********************************************************************
1438 * PrivateLoadLibrary (KERNEL32)
1440 * FIXME: rough guesswork, don't know what "Private" means
1442 HINSTANCE WINAPI PrivateLoadLibrary(LPCSTR libname)
1444 return (HINSTANCE)LoadLibrary16(libname);
1449 /***********************************************************************
1450 * PrivateFreeLibrary (KERNEL32)
1452 * FIXME: rough guesswork, don't know what "Private" means
1454 void WINAPI PrivateFreeLibrary(HINSTANCE handle)
1456 FreeLibrary16((HINSTANCE16)handle);
1460 /***********************************************************************
1461 * WIN32_GetProcAddress16 (KERNEL32.36)
1462 * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
1464 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
1466 WORD ordinal;
1467 FARPROC16 ret;
1469 if (!hModule) {
1470 WARN("hModule may not be 0!\n");
1471 return (FARPROC16)0;
1473 if (HIWORD(hModule))
1475 WARN("hModule is Win32 handle (%08x)\n", hModule );
1476 return (FARPROC16)0;
1478 hModule = GetExePtr( hModule );
1479 if (HIWORD(name)) {
1480 ordinal = NE_GetOrdinal( hModule, name );
1481 TRACE("%04x '%s'\n", hModule, name );
1482 } else {
1483 ordinal = LOWORD(name);
1484 TRACE("%04x %04x\n", hModule, ordinal );
1486 if (!ordinal) return (FARPROC16)0;
1487 ret = NE_GetEntryPoint( hModule, ordinal );
1488 TRACE("returning %08x\n",(UINT)ret);
1489 return ret;
1492 /***********************************************************************
1493 * GetProcAddress16 (KERNEL.50)
1495 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, SEGPTR name )
1497 WORD ordinal;
1498 FARPROC16 ret;
1500 if (!hModule) hModule = GetCurrentTask();
1501 hModule = GetExePtr( hModule );
1503 if (HIWORD(name) != 0)
1505 ordinal = NE_GetOrdinal( hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1506 TRACE("%04x '%s'\n", hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1508 else
1510 ordinal = LOWORD(name);
1511 TRACE("%04x %04x\n", hModule, ordinal );
1513 if (!ordinal) return (FARPROC16)0;
1515 ret = NE_GetEntryPoint( hModule, ordinal );
1517 TRACE("returning %08x\n", (UINT)ret );
1518 return ret;
1522 /***********************************************************************
1523 * GetProcAddress (KERNEL32.257)
1525 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1527 return MODULE_GetProcAddress( hModule, function, TRUE );
1530 /***********************************************************************
1531 * GetProcAddress32 (KERNEL.453)
1533 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
1535 return MODULE_GetProcAddress( hModule, function, FALSE );
1538 /***********************************************************************
1539 * MODULE_GetProcAddress (internal)
1541 FARPROC MODULE_GetProcAddress(
1542 HMODULE hModule, /* [in] current module handle */
1543 LPCSTR function, /* [in] function to be looked up */
1544 BOOL snoop )
1546 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1547 FARPROC retproc;
1549 if (HIWORD(function))
1550 TRACE_(win32)("(%08lx,%s)\n",(DWORD)hModule,function);
1551 else
1552 TRACE_(win32)("(%08lx,%p)\n",(DWORD)hModule,function);
1553 if (!wm) {
1554 SetLastError(ERROR_INVALID_HANDLE);
1555 return (FARPROC)0;
1557 switch (wm->type)
1559 case MODULE32_PE:
1560 retproc = PE_FindExportedFunction( wm, function, snoop );
1561 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1562 return retproc;
1563 case MODULE32_ELF:
1564 retproc = ELF_FindExportedFunction( wm, function);
1565 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1566 return retproc;
1567 default:
1568 ERR("wine_modref type %d not handled.\n",wm->type);
1569 SetLastError(ERROR_INVALID_HANDLE);
1570 return (FARPROC)0;
1575 /***********************************************************************
1576 * RtlImageNtHeader (NTDLL)
1578 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
1580 /* basically:
1581 * return hModule+(((IMAGE_DOS_HEADER*)hModule)->e_lfanew);
1582 * but we could get HMODULE16 or the like (think builtin modules)
1585 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1586 if (!wm || (wm->type != MODULE32_PE)) return (PIMAGE_NT_HEADERS)0;
1587 return PE_HEADER(wm->module);
1591 /***************************************************************************
1592 * HasGPHandler (KERNEL.338)
1595 #include "pshpack1.h"
1596 typedef struct _GPHANDLERDEF
1598 WORD selector;
1599 WORD rangeStart;
1600 WORD rangeEnd;
1601 WORD handler;
1602 } GPHANDLERDEF;
1603 #include "poppack.h"
1605 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1607 HMODULE16 hModule;
1608 int gpOrdinal;
1609 SEGPTR gpPtr;
1610 GPHANDLERDEF *gpHandler;
1612 if ( (hModule = FarGetOwner16( SELECTOROF(address) )) != 0
1613 && (gpOrdinal = NE_GetOrdinal( hModule, "__GP" )) != 0
1614 && (gpPtr = (SEGPTR)NE_GetEntryPointEx( hModule, gpOrdinal, FALSE )) != 0
1615 && !IsBadReadPtr16( gpPtr, sizeof(GPHANDLERDEF) )
1616 && (gpHandler = PTR_SEG_TO_LIN( gpPtr )) != NULL )
1618 while (gpHandler->selector)
1620 if ( SELECTOROF(address) == gpHandler->selector
1621 && OFFSETOF(address) >= gpHandler->rangeStart
1622 && OFFSETOF(address) < gpHandler->rangeEnd )
1623 return PTR_SEG_OFF_TO_SEGPTR( gpHandler->selector,
1624 gpHandler->handler );
1625 gpHandler++;
1629 return 0;