Fixed some warnings.
[wine/hacks.git] / loader / module.c
blobbe10fb436efd75188007ca332f854560affd4d7e
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);
43 /*************************************************************************
44 * MODULE32_LookupHMODULE
45 * looks for the referenced HMODULE in the current process
47 WINE_MODREF *MODULE32_LookupHMODULE( HMODULE hmod )
49 WINE_MODREF *wm;
51 if (!hmod)
52 return PROCESS_Current()->exe_modref;
54 if (!HIWORD(hmod)) {
55 ERR("tried to lookup 0x%04x in win32 module handler!\n",hmod);
56 return NULL;
58 for ( wm = PROCESS_Current()->modref_list; wm; wm=wm->next )
59 if (wm->module == hmod)
60 return wm;
61 return NULL;
64 /*************************************************************************
65 * MODULE_InitDLL
67 static BOOL MODULE_InitDLL( WINE_MODREF *wm, DWORD type, LPVOID lpReserved )
69 BOOL retv = TRUE;
71 static LPCSTR typeName[] = { "PROCESS_DETACH", "PROCESS_ATTACH",
72 "THREAD_ATTACH", "THREAD_DETACH" };
73 assert( wm );
76 /* Skip calls for modules loaded with special load flags */
78 if ( ( wm->flags & WINE_MODREF_DONT_RESOLVE_REFS )
79 || ( wm->flags & WINE_MODREF_LOAD_AS_DATAFILE ) )
80 return TRUE;
83 TRACE("(%s,%s,%p) - CALL\n", wm->modname, typeName[type], lpReserved );
85 /* Call the initialization routine */
86 switch ( wm->type )
88 case MODULE32_PE:
89 retv = PE_InitDLL( wm, type, lpReserved );
90 break;
92 case MODULE32_ELF:
93 /* no need to do that, dlopen() already does */
94 break;
96 default:
97 ERR("wine_modref type %d not handled.\n", wm->type );
98 retv = FALSE;
99 break;
102 /* The state of the module list may have changed due to the call
103 to PE_InitDLL. We cannot assume that this module has not been
104 deleted. */
105 TRACE("(%p,%s,%p) - RETURN %d\n", wm, typeName[type], lpReserved, retv );
107 return retv;
110 /*************************************************************************
111 * MODULE_DllProcessAttach
113 * Send the process attach notification to all DLLs the given module
114 * depends on (recursively). This is somewhat complicated due to the fact that
116 * - we have to respect the module dependencies, i.e. modules implicitly
117 * referenced by another module have to be initialized before the module
118 * itself can be initialized
120 * - the initialization routine of a DLL can itself call LoadLibrary,
121 * thereby introducing a whole new set of dependencies (even involving
122 * the 'old' modules) at any time during the whole process
124 * (Note that this routine can be recursively entered not only directly
125 * from itself, but also via LoadLibrary from one of the called initialization
126 * routines.)
128 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
129 * the process *detach* notifications to be sent in the correct order.
130 * This must not only take into account module dependencies, but also
131 * 'hidden' dependencies created by modules calling LoadLibrary in their
132 * attach notification routine.
134 * The strategy is rather simple: we move a WINE_MODREF to the head of the
135 * list after the attach notification has returned. This implies that the
136 * detach notifications are called in the reverse of the sequence the attach
137 * notifications *returned*.
139 * NOTE: Assumes that the process critical section is held!
142 BOOL MODULE_DllProcessAttach( WINE_MODREF *wm, LPVOID lpReserved )
144 BOOL retv = TRUE;
145 int i;
146 assert( wm );
148 /* prevent infinite recursion in case of cyclical dependencies */
149 if ( ( wm->flags & WINE_MODREF_MARKER )
150 || ( wm->flags & WINE_MODREF_PROCESS_ATTACHED ) )
151 return retv;
153 TRACE("(%s,%p) - START\n", wm->modname, lpReserved );
155 /* Tag current MODREF to prevent recursive loop */
156 wm->flags |= WINE_MODREF_MARKER;
158 /* Recursively attach all DLLs this one depends on */
159 for ( i = 0; retv && i < wm->nDeps; i++ )
160 if ( wm->deps[i] )
161 retv = MODULE_DllProcessAttach( wm->deps[i], lpReserved );
163 /* Call DLL entry point */
164 if ( retv )
166 retv = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
167 if ( retv )
168 wm->flags |= WINE_MODREF_PROCESS_ATTACHED;
171 /* Re-insert MODREF at head of list */
172 if ( retv && wm->prev )
174 wm->prev->next = wm->next;
175 if ( wm->next ) wm->next->prev = wm->prev;
177 wm->prev = NULL;
178 wm->next = PROCESS_Current()->modref_list;
179 PROCESS_Current()->modref_list = wm->next->prev = wm;
182 /* Remove recursion flag */
183 wm->flags &= ~WINE_MODREF_MARKER;
185 TRACE("(%s,%p) - END\n", wm->modname, lpReserved );
187 return retv;
190 /*************************************************************************
191 * MODULE_DllProcessDetach
193 * Send DLL process detach notifications. See the comment about calling
194 * sequence at MODULE_DllProcessAttach. Unless the bForceDetach flag
195 * is set, only DLLs with zero refcount are notified.
197 void MODULE_DllProcessDetach( BOOL bForceDetach, LPVOID lpReserved )
199 WINE_MODREF *wm;
201 EnterCriticalSection( &PROCESS_Current()->crit_section );
205 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
207 /* Check whether to detach this DLL */
208 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
209 continue;
210 if ( wm->refCount > 0 && !bForceDetach )
211 continue;
213 /* Call detach notification */
214 wm->flags &= ~WINE_MODREF_PROCESS_ATTACHED;
215 MODULE_InitDLL( wm, DLL_PROCESS_DETACH, lpReserved );
217 /* Restart at head of WINE_MODREF list, as entries might have
218 been added and/or removed while performing the call ... */
219 break;
221 } while ( wm );
223 LeaveCriticalSection( &PROCESS_Current()->crit_section );
226 /*************************************************************************
227 * MODULE_DllThreadAttach
229 * Send DLL thread attach notifications. These are sent in the
230 * reverse sequence of process detach notification.
233 void MODULE_DllThreadAttach( LPVOID lpReserved )
235 WINE_MODREF *wm;
237 EnterCriticalSection( &PROCESS_Current()->crit_section );
239 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
240 if ( !wm->next )
241 break;
243 for ( ; wm; wm = wm->prev )
245 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
246 continue;
247 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
248 continue;
250 MODULE_InitDLL( wm, DLL_THREAD_ATTACH, lpReserved );
253 LeaveCriticalSection( &PROCESS_Current()->crit_section );
256 /*************************************************************************
257 * MODULE_DllThreadDetach
259 * Send DLL thread detach notifications. These are sent in the
260 * same sequence as process detach notification.
263 void MODULE_DllThreadDetach( LPVOID lpReserved )
265 WINE_MODREF *wm;
267 EnterCriticalSection( &PROCESS_Current()->crit_section );
269 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
271 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
272 continue;
273 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
274 continue;
276 MODULE_InitDLL( wm, DLL_THREAD_DETACH, lpReserved );
279 LeaveCriticalSection( &PROCESS_Current()->crit_section );
282 /****************************************************************************
283 * DisableThreadLibraryCalls (KERNEL32.74)
285 * Don't call DllEntryPoint for DLL_THREAD_{ATTACH,DETACH} if set.
287 BOOL WINAPI DisableThreadLibraryCalls( HMODULE hModule )
289 WINE_MODREF *wm;
290 BOOL retval = TRUE;
292 EnterCriticalSection( &PROCESS_Current()->crit_section );
294 wm = MODULE32_LookupHMODULE( hModule );
295 if ( !wm )
296 retval = FALSE;
297 else
298 wm->flags |= WINE_MODREF_NO_DLL_CALLS;
300 LeaveCriticalSection( &PROCESS_Current()->crit_section );
302 return retval;
306 /***********************************************************************
307 * MODULE_CreateDummyModule
309 * Create a dummy NE module for Win32 or Winelib.
311 HMODULE MODULE_CreateDummyModule( LPCSTR filename, HMODULE module32 )
313 HMODULE hModule;
314 NE_MODULE *pModule;
315 SEGTABLEENTRY *pSegment;
316 char *pStr,*s;
317 unsigned int len;
318 const char* basename;
319 OFSTRUCT *ofs;
320 int of_size, size;
322 /* Extract base filename */
323 basename = strrchr(filename, '\\');
324 if (!basename) basename = filename;
325 else basename++;
326 len = strlen(basename);
327 if ((s = strchr(basename, '.'))) len = s - basename;
329 /* Allocate module */
330 of_size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName)
331 + strlen(filename) + 1;
332 size = sizeof(NE_MODULE) +
333 /* loaded file info */
334 of_size +
335 /* segment table: DS,CS */
336 2 * sizeof(SEGTABLEENTRY) +
337 /* name table */
338 len + 2 +
339 /* several empty tables */
342 hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
343 if (!hModule) return (HMODULE)11; /* invalid exe */
345 FarSetOwner16( hModule, hModule );
346 pModule = (NE_MODULE *)GlobalLock16( hModule );
348 /* Set all used entries */
349 pModule->magic = IMAGE_OS2_SIGNATURE;
350 pModule->count = 1;
351 pModule->next = 0;
352 pModule->flags = 0;
353 pModule->dgroup = 0;
354 pModule->ss = 1;
355 pModule->cs = 2;
356 pModule->heap_size = 0;
357 pModule->stack_size = 0;
358 pModule->seg_count = 2;
359 pModule->modref_count = 0;
360 pModule->nrname_size = 0;
361 pModule->fileinfo = sizeof(NE_MODULE);
362 pModule->os_flags = NE_OSFLAGS_WINDOWS;
363 pModule->self = hModule;
364 pModule->module32 = module32;
366 /* Set version and flags */
367 if (module32)
369 pModule->expected_version =
370 ((PE_HEADER(module32)->OptionalHeader.MajorSubsystemVersion & 0xff) << 8 ) |
371 (PE_HEADER(module32)->OptionalHeader.MinorSubsystemVersion & 0xff);
372 pModule->flags |= NE_FFLAGS_WIN32;
373 if (PE_HEADER(module32)->FileHeader.Characteristics & IMAGE_FILE_DLL)
374 pModule->flags |= NE_FFLAGS_LIBMODULE | NE_FFLAGS_SINGLEDATA;
377 /* Set loaded file information */
378 ofs = (OFSTRUCT *)(pModule + 1);
379 memset( ofs, 0, of_size );
380 ofs->cBytes = of_size < 256 ? of_size : 255; /* FIXME */
381 strcpy( ofs->szPathName, filename );
383 pSegment = (SEGTABLEENTRY*)((char*)(pModule + 1) + of_size);
384 pModule->seg_table = (int)pSegment - (int)pModule;
385 /* Data segment */
386 pSegment->size = 0;
387 pSegment->flags = NE_SEGFLAGS_DATA;
388 pSegment->minsize = 0x1000;
389 pSegment++;
390 /* Code segment */
391 pSegment->flags = 0;
392 pSegment++;
394 /* Module name */
395 pStr = (char *)pSegment;
396 pModule->name_table = (int)pStr - (int)pModule;
397 assert(len<256);
398 *pStr = len;
399 lstrcpynA( pStr+1, basename, len+1 );
400 pStr += len+2;
402 /* All tables zero terminated */
403 pModule->res_table = pModule->import_table = pModule->entry_table =
404 (int)pStr - (int)pModule;
406 NE_RegisterModule( pModule );
407 return hModule;
411 /**********************************************************************
412 * MODULE_FindModule32
414 * Find a (loaded) win32 module depending on path
416 * RETURNS
417 * the module handle if found
418 * 0 if not
420 WINE_MODREF *MODULE_FindModule(
421 LPCSTR path /* [in] pathname of module/library to be found */
423 WINE_MODREF *wm;
424 char dllname[260], *p;
426 /* Append .DLL to name if no extension present */
427 strcpy( dllname, path );
428 if (!(p = strrchr( dllname, '.')) || strchr( p, '/' ) || strchr( p, '\\'))
429 strcat( dllname, ".DLL" );
431 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
433 if ( !strcasecmp( dllname, wm->modname ) )
434 break;
435 if ( !strcasecmp( dllname, wm->filename ) )
436 break;
437 if ( !strcasecmp( dllname, wm->short_modname ) )
438 break;
439 if ( !strcasecmp( dllname, wm->short_filename ) )
440 break;
443 return wm;
447 /* Check whether a file is an OS/2 or a very old Windows executable
448 * by testing on import of KERNEL.
450 * FIXME: is reading the module imports the only way of discerning
451 * old Windows binaries from OS/2 ones ? At least it seems so...
453 static DWORD MODULE_Decide_OS2_OldWin(HANDLE hfile, IMAGE_DOS_HEADER *mz, IMAGE_OS2_HEADER *ne)
455 DWORD currpos = SetFilePointer( hfile, 0, NULL, SEEK_CUR);
456 DWORD type = SCS_OS216_BINARY;
457 LPWORD modtab = NULL;
458 LPSTR nametab = NULL;
459 DWORD len;
460 int i;
462 /* read modref table */
463 if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_modtab, NULL, SEEK_SET ) == -1)
464 || (!(modtab = HeapAlloc( GetProcessHeap(), 0, ne->ne_cmod*sizeof(WORD))))
465 || (!(ReadFile(hfile, modtab, ne->ne_cmod*sizeof(WORD), &len, NULL)))
466 || (len != ne->ne_cmod*sizeof(WORD)) )
467 goto broken;
469 /* read imported names table */
470 if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_imptab, NULL, SEEK_SET ) == -1)
471 || (!(nametab = HeapAlloc( GetProcessHeap(), 0, ne->ne_enttab - ne->ne_imptab)))
472 || (!(ReadFile(hfile, nametab, ne->ne_enttab - ne->ne_imptab, &len, NULL)))
473 || (len != ne->ne_enttab - ne->ne_imptab) )
474 goto broken;
476 for (i=0; i < ne->ne_cmod; i++)
478 LPSTR module = &nametab[modtab[i]];
479 TRACE("modref: %.*s\n", module[0], &module[1]);
480 if (!(strncmp(&module[1], "KERNEL", module[0])))
481 { /* very old Windows file */
482 MESSAGE("This seems to be a very old (pre-3.0) Windows executable. Expect crashes, especially if this is a real-mode binary !\n");
483 type = SCS_WOW_BINARY;
484 goto good;
488 broken:
489 ERR("Hmm, an error occurred. Is this binary file broken ?\n");
491 good:
492 HeapFree( GetProcessHeap(), 0, modtab);
493 HeapFree( GetProcessHeap(), 0, nametab);
494 SetFilePointer( hfile, currpos, NULL, SEEK_SET); /* restore filepos */
495 return type;
498 /***********************************************************************
499 * MODULE_GetBinaryType
501 * The GetBinaryType function determines whether a file is executable
502 * or not and if it is it returns what type of executable it is.
503 * The type of executable is a property that determines in which
504 * subsystem an executable file runs under.
506 * Binary types returned:
507 * SCS_32BIT_BINARY: A Win32 based application
508 * SCS_DOS_BINARY: An MS-Dos based application
509 * SCS_WOW_BINARY: A Win16 based application
510 * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
511 * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
512 * SCS_OS216_BINARY: A 16bit OS/2 based application
514 * Returns TRUE if the file is an executable in which case
515 * the value pointed by lpBinaryType is set.
516 * Returns FALSE if the file is not an executable or if the function fails.
518 * To do so it opens the file and reads in the header information
519 * if the extended header information is not present it will
520 * assume that the file is a DOS executable.
521 * If the extended header information is present it will
522 * determine if the file is a 16 or 32 bit Windows executable
523 * by check the flags in the header.
525 * Note that .COM and .PIF files are only recognized by their
526 * file name extension; but Windows does it the same way ...
528 BOOL MODULE_GetBinaryType( HANDLE hfile, LPCSTR filename, LPDWORD lpBinaryType )
530 IMAGE_DOS_HEADER mz_header;
531 char magic[4], *ptr;
532 DWORD len;
534 /* Seek to the start of the file and read the DOS header information.
536 if ( SetFilePointer( hfile, 0, NULL, SEEK_SET ) != -1
537 && ReadFile( hfile, &mz_header, sizeof(mz_header), &len, NULL )
538 && len == sizeof(mz_header) )
540 /* Now that we have the header check the e_magic field
541 * to see if this is a dos image.
543 if ( mz_header.e_magic == IMAGE_DOS_SIGNATURE )
545 BOOL lfanewValid = FALSE;
546 /* We do have a DOS image so we will now try to seek into
547 * the file by the amount indicated by the field
548 * "Offset to extended header" and read in the
549 * "magic" field information at that location.
550 * This will tell us if there is more header information
551 * to read or not.
553 /* But before we do we will make sure that header
554 * structure encompasses the "Offset to extended header"
555 * field.
557 if ( (mz_header.e_cparhdr<<4) >= sizeof(IMAGE_DOS_HEADER) )
558 if ( ( mz_header.e_crlc == 0 ) ||
559 ( mz_header.e_lfarlc >= sizeof(IMAGE_DOS_HEADER) ) )
560 if ( mz_header.e_lfanew >= sizeof(IMAGE_DOS_HEADER)
561 && SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET ) != -1
562 && ReadFile( hfile, magic, sizeof(magic), &len, NULL )
563 && len == sizeof(magic) )
564 lfanewValid = TRUE;
566 if ( !lfanewValid )
568 /* If we cannot read this "extended header" we will
569 * assume that we have a simple DOS executable.
571 *lpBinaryType = SCS_DOS_BINARY;
572 return TRUE;
574 else
576 /* Reading the magic field succeeded so
577 * we will try to determine what type it is.
579 if ( *(DWORD*)magic == IMAGE_NT_SIGNATURE )
581 /* This is an NT signature.
583 *lpBinaryType = SCS_32BIT_BINARY;
584 return TRUE;
586 else if ( *(WORD*)magic == IMAGE_OS2_SIGNATURE )
588 /* The IMAGE_OS2_SIGNATURE indicates that the
589 * "extended header is a Windows executable (NE)
590 * header." This can mean either a 16-bit OS/2
591 * or a 16-bit Windows or even a DOS program
592 * (running under a DOS extender). To decide
593 * which, we'll have to read the NE header.
596 IMAGE_OS2_HEADER ne;
597 if ( SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET ) != -1
598 && ReadFile( hfile, &ne, sizeof(ne), &len, NULL )
599 && len == sizeof(ne) )
601 switch ( ne.ne_exetyp )
603 case 2: *lpBinaryType = SCS_WOW_BINARY; return TRUE;
604 case 5: *lpBinaryType = SCS_DOS_BINARY; return TRUE;
605 default: *lpBinaryType =
606 MODULE_Decide_OS2_OldWin(hfile, &mz_header, &ne);
607 return TRUE;
610 /* Couldn't read header, so abort. */
611 return FALSE;
613 else
615 /* Unknown extended header, but this file is nonetheless
616 DOS-executable.
618 *lpBinaryType = SCS_DOS_BINARY;
619 return TRUE;
625 /* If we get here, we don't even have a correct MZ header.
626 * Try to check the file extension for known types ...
628 ptr = strrchr( filename, '.' );
629 if ( ptr && !strchr( ptr, '\\' ) && !strchr( ptr, '/' ) )
631 if ( !lstrcmpiA( ptr, ".COM" ) )
633 *lpBinaryType = SCS_DOS_BINARY;
634 return TRUE;
637 if ( !lstrcmpiA( ptr, ".PIF" ) )
639 *lpBinaryType = SCS_PIF_BINARY;
640 return TRUE;
644 return FALSE;
647 /***********************************************************************
648 * GetBinaryTypeA [KERNEL32.280]
650 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
652 BOOL ret = FALSE;
653 HANDLE hfile;
655 TRACE_(win32)("%s\n", lpApplicationName );
657 /* Sanity check.
659 if ( lpApplicationName == NULL || lpBinaryType == NULL )
660 return FALSE;
662 /* Open the file indicated by lpApplicationName for reading.
664 hfile = CreateFileA( lpApplicationName, GENERIC_READ, FILE_SHARE_READ,
665 NULL, OPEN_EXISTING, 0, -1 );
666 if ( hfile == INVALID_HANDLE_VALUE )
667 return FALSE;
669 /* Check binary type
671 ret = MODULE_GetBinaryType( hfile, lpApplicationName, lpBinaryType );
673 /* Close the file.
675 CloseHandle( hfile );
677 return ret;
680 /***********************************************************************
681 * GetBinaryTypeW [KERNEL32.281]
683 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
685 BOOL ret = FALSE;
686 LPSTR strNew = NULL;
688 TRACE_(win32)("%s\n", debugstr_w(lpApplicationName) );
690 /* Sanity check.
692 if ( lpApplicationName == NULL || lpBinaryType == NULL )
693 return FALSE;
695 /* Convert the wide string to a ascii string.
697 strNew = HEAP_strdupWtoA( GetProcessHeap(), 0, lpApplicationName );
699 if ( strNew != NULL )
701 ret = GetBinaryTypeA( strNew, lpBinaryType );
703 /* Free the allocated string.
705 HeapFree( GetProcessHeap(), 0, strNew );
708 return ret;
712 /***********************************************************************
713 * WinExec16 (KERNEL.166)
715 HINSTANCE16 WINAPI WinExec16( LPCSTR lpCmdLine, UINT16 nCmdShow )
717 LPCSTR p;
718 LPSTR name, cmdline;
719 int len;
720 HINSTANCE16 ret;
721 char buffer[MAX_PATH];
723 if ((p = strchr( lpCmdLine, ' ' )))
725 if (!(name = HeapAlloc( GetProcessHeap(), 0, p - lpCmdLine + 1 )))
726 return ERROR_NOT_ENOUGH_MEMORY;
727 memcpy( name, lpCmdLine, p - lpCmdLine );
728 name[p - lpCmdLine] = 0;
729 p++;
730 len = strlen(p);
731 cmdline = SEGPTR_ALLOC( len + 2 );
732 cmdline[0] = (BYTE)len;
733 strcpy( cmdline + 1, p );
735 else
737 name = (LPSTR)lpCmdLine;
738 cmdline = SEGPTR_ALLOC(2);
739 cmdline[0] = cmdline[1] = 0;
742 if (SearchPathA( NULL, name, ".exe", sizeof(buffer), buffer, NULL ))
744 LOADPARAMS16 params;
745 WORD *showCmd = SEGPTR_ALLOC( 2*sizeof(WORD) );
746 showCmd[0] = 2;
747 showCmd[1] = nCmdShow;
749 params.hEnvironment = 0;
750 params.cmdLine = SEGPTR_GET(cmdline);
751 params.showCmd = SEGPTR_GET(showCmd);
752 params.reserved = 0;
754 ret = LoadModule16( buffer, &params );
756 SEGPTR_FREE( showCmd );
757 SEGPTR_FREE( cmdline );
759 else ret = GetLastError();
761 if (name != lpCmdLine) HeapFree( GetProcessHeap(), 0, name );
763 if (ret == 21) /* 32-bit module */
765 SYSLEVEL_ReleaseWin16Lock();
766 ret = WinExec( lpCmdLine, nCmdShow );
767 SYSLEVEL_RestoreWin16Lock();
769 return ret;
772 /***********************************************************************
773 * WinExec (KERNEL32.566)
775 HINSTANCE WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
777 PROCESS_INFORMATION info;
778 STARTUPINFOA startup;
779 HINSTANCE hInstance;
780 char *cmdline;
782 memset( &startup, 0, sizeof(startup) );
783 startup.cb = sizeof(startup);
784 startup.dwFlags = STARTF_USESHOWWINDOW;
785 startup.wShowWindow = nCmdShow;
787 /* cmdline needs to be writeable for CreateProcess */
788 if (!(cmdline = HEAP_strdupA( GetProcessHeap(), 0, lpCmdLine ))) return 0;
790 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
791 0, NULL, NULL, &startup, &info ))
793 /* Give 30 seconds to the app to come up */
794 if (Callout.WaitForInputIdle ( info.hProcess, 30000 ) == 0xFFFFFFFF)
795 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
796 hInstance = 33;
797 /* Close off the handles */
798 CloseHandle( info.hThread );
799 CloseHandle( info.hProcess );
801 else if ((hInstance = GetLastError()) >= 32)
803 FIXME("Strange error set by CreateProcess: %d\n", hInstance );
804 hInstance = 11;
806 HeapFree( GetProcessHeap(), 0, cmdline );
807 return hInstance;
810 /**********************************************************************
811 * LoadModule (KERNEL32.499)
813 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
815 LOADPARAMS *params = (LOADPARAMS *)paramBlock;
816 PROCESS_INFORMATION info;
817 STARTUPINFOA startup;
818 HINSTANCE hInstance;
819 LPSTR cmdline, p;
820 char filename[MAX_PATH];
821 BYTE len;
823 if (!name) return ERROR_FILE_NOT_FOUND;
825 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
826 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
827 return GetLastError();
829 len = (BYTE)params->lpCmdLine[0];
830 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
831 return ERROR_NOT_ENOUGH_MEMORY;
833 strcpy( cmdline, filename );
834 p = cmdline + strlen(cmdline);
835 *p++ = ' ';
836 memcpy( p, params->lpCmdLine + 1, len );
837 p[len] = 0;
839 memset( &startup, 0, sizeof(startup) );
840 startup.cb = sizeof(startup);
841 if (params->lpCmdShow)
843 startup.dwFlags = STARTF_USESHOWWINDOW;
844 startup.wShowWindow = params->lpCmdShow[1];
847 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
848 params->lpEnvAddress, NULL, &startup, &info ))
850 /* Give 30 seconds to the app to come up */
851 if ( Callout.WaitForInputIdle ( info.hProcess, 30000 ) == 0xFFFFFFFF )
852 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
853 hInstance = 33;
854 /* Close off the handles */
855 CloseHandle( info.hThread );
856 CloseHandle( info.hProcess );
858 else if ((hInstance = GetLastError()) >= 32)
860 FIXME("Strange error set by CreateProcess: %d\n", hInstance );
861 hInstance = 11;
864 HeapFree( GetProcessHeap(), 0, cmdline );
865 return hInstance;
869 /*************************************************************************
870 * get_file_name
872 * Helper for CreateProcess: retrieve the file name to load from the
873 * app name and command line. Store the file name in buffer, and
874 * return a possibly modified command line.
876 static LPSTR get_file_name( LPCSTR appname, LPSTR cmdline, LPSTR buffer, int buflen )
878 char *name, *pos, *ret = NULL;
879 const char *p;
881 /* if we have an app name, everything is easy */
883 if (appname)
885 /* use the unmodified app name as file name */
886 lstrcpynA( buffer, appname, buflen );
887 if (!(ret = cmdline))
889 /* no command-line, create one */
890 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(appname) + 3 )))
891 sprintf( ret, "\"%s\"", appname );
893 return ret;
896 if (!cmdline)
898 SetLastError( ERROR_INVALID_PARAMETER );
899 return NULL;
902 /* first check for a quoted file name */
904 if ((cmdline[0] == '"') && ((p = strchr( cmdline + 1, '"' ))))
906 int len = p - cmdline - 1;
907 /* extract the quoted portion as file name */
908 if (!(name = HeapAlloc( GetProcessHeap(), 0, len + 1 ))) return NULL;
909 memcpy( name, cmdline + 1, len );
910 name[len] = 0;
912 if (SearchPathA( NULL, name, ".exe", buflen, buffer, NULL ) ||
913 SearchPathA( NULL, name, NULL, buflen, buffer, NULL ))
914 ret = cmdline; /* no change necessary */
915 goto done;
918 /* now try the command-line word by word */
920 if (!(name = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 1 ))) return NULL;
921 pos = name;
922 p = cmdline;
924 while (*p)
926 do *pos++ = *p++; while (*p && *p != ' ');
927 *pos = 0;
928 TRACE("trying '%s'\n", name );
929 if (SearchPathA( NULL, name, ".exe", buflen, buffer, NULL ) ||
930 SearchPathA( NULL, name, NULL, buflen, buffer, NULL ))
932 ret = cmdline;
933 break;
937 if (!ret || !strchr( name, ' ' )) goto done; /* no change necessary */
939 /* now build a new command-line with quotes */
941 if (!(ret = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 3 ))) goto done;
942 sprintf( ret, "\"%s\"%s", name, p );
944 done:
945 HeapFree( GetProcessHeap(), 0, name );
946 return ret;
950 /**********************************************************************
951 * CreateProcessA (KERNEL32.171)
953 BOOL WINAPI CreateProcessA( LPCSTR lpApplicationName, LPSTR lpCommandLine,
954 LPSECURITY_ATTRIBUTES lpProcessAttributes,
955 LPSECURITY_ATTRIBUTES lpThreadAttributes,
956 BOOL bInheritHandles, DWORD dwCreationFlags,
957 LPVOID lpEnvironment, LPCSTR lpCurrentDirectory,
958 LPSTARTUPINFOA lpStartupInfo,
959 LPPROCESS_INFORMATION lpProcessInfo )
961 BOOL retv = FALSE;
962 HANDLE hFile;
963 DWORD type;
964 char name[MAX_PATH];
965 LPSTR tidy_cmdline;
967 /* Process the AppName and/or CmdLine to get module name and path */
969 TRACE("app '%s' cmdline '%s'\n", lpApplicationName, lpCommandLine );
971 if (!(tidy_cmdline = get_file_name( lpApplicationName, lpCommandLine, name, sizeof(name) )))
972 return FALSE;
974 /* Warn if unsupported features are used */
976 if (dwCreationFlags & DETACHED_PROCESS)
977 FIXME("(%s,...): DETACHED_PROCESS ignored\n", name);
978 if (dwCreationFlags & CREATE_NEW_CONSOLE)
979 FIXME("(%s,...): CREATE_NEW_CONSOLE ignored\n", name);
980 if (dwCreationFlags & NORMAL_PRIORITY_CLASS)
981 FIXME("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
982 if (dwCreationFlags & IDLE_PRIORITY_CLASS)
983 FIXME("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
984 if (dwCreationFlags & HIGH_PRIORITY_CLASS)
985 FIXME("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
986 if (dwCreationFlags & REALTIME_PRIORITY_CLASS)
987 FIXME("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
988 if (dwCreationFlags & CREATE_NEW_PROCESS_GROUP)
989 FIXME("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
990 if (dwCreationFlags & CREATE_UNICODE_ENVIRONMENT)
991 FIXME("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
992 if (dwCreationFlags & CREATE_SEPARATE_WOW_VDM)
993 FIXME("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
994 if (dwCreationFlags & CREATE_SHARED_WOW_VDM)
995 FIXME("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
996 if (dwCreationFlags & CREATE_DEFAULT_ERROR_MODE)
997 FIXME("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
998 if (dwCreationFlags & CREATE_NO_WINDOW)
999 FIXME("(%s,...): CREATE_NO_WINDOW ignored\n", name);
1000 if (dwCreationFlags & PROFILE_USER)
1001 FIXME("(%s,...): PROFILE_USER ignored\n", name);
1002 if (dwCreationFlags & PROFILE_KERNEL)
1003 FIXME("(%s,...): PROFILE_KERNEL ignored\n", name);
1004 if (dwCreationFlags & PROFILE_SERVER)
1005 FIXME("(%s,...): PROFILE_SERVER ignored\n", name);
1006 if (lpStartupInfo->lpDesktop)
1007 FIXME("(%s,...): lpStartupInfo->lpDesktop %s ignored\n",
1008 name, lpStartupInfo->lpDesktop);
1009 if (lpStartupInfo->lpTitle)
1010 FIXME("(%s,...): lpStartupInfo->lpTitle %s ignored\n",
1011 name, lpStartupInfo->lpTitle);
1012 if (lpStartupInfo->dwFlags & STARTF_USECOUNTCHARS)
1013 FIXME("(%s,...): STARTF_USECOUNTCHARS (%ld,%ld) ignored\n",
1014 name, lpStartupInfo->dwXCountChars, lpStartupInfo->dwYCountChars);
1015 if (lpStartupInfo->dwFlags & STARTF_USEFILLATTRIBUTE)
1016 FIXME("(%s,...): STARTF_USEFILLATTRIBUTE %lx ignored\n",
1017 name, lpStartupInfo->dwFillAttribute);
1018 if (lpStartupInfo->dwFlags & STARTF_RUNFULLSCREEN)
1019 FIXME("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
1020 if (lpStartupInfo->dwFlags & STARTF_FORCEONFEEDBACK)
1021 FIXME("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
1022 if (lpStartupInfo->dwFlags & STARTF_FORCEOFFFEEDBACK)
1023 FIXME("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
1024 if (lpStartupInfo->dwFlags & STARTF_USEHOTKEY)
1025 FIXME("(%s,...): STARTF_USEHOTKEY ignored\n", name);
1027 /* Open file and determine executable type */
1029 hFile = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, -1 );
1030 if (hFile == INVALID_HANDLE_VALUE) goto done;
1032 if ( !MODULE_GetBinaryType( hFile, name, &type ) )
1034 CloseHandle( hFile );
1035 retv = PROCESS_Create( -1, name, tidy_cmdline, lpEnvironment,
1036 lpProcessAttributes, lpThreadAttributes,
1037 bInheritHandles, dwCreationFlags,
1038 lpStartupInfo, lpProcessInfo, lpCurrentDirectory );
1039 goto done;
1042 /* Create process */
1044 switch ( type )
1046 case SCS_32BIT_BINARY:
1047 case SCS_WOW_BINARY:
1048 case SCS_DOS_BINARY:
1049 retv = PROCESS_Create( hFile, name, tidy_cmdline, lpEnvironment,
1050 lpProcessAttributes, lpThreadAttributes,
1051 bInheritHandles, dwCreationFlags,
1052 lpStartupInfo, lpProcessInfo, lpCurrentDirectory);
1053 break;
1055 case SCS_PIF_BINARY:
1056 case SCS_POSIX_BINARY:
1057 case SCS_OS216_BINARY:
1058 FIXME("Unsupported executable type: %ld\n", type );
1059 /* fall through */
1061 default:
1062 SetLastError( ERROR_BAD_FORMAT );
1063 break;
1065 CloseHandle( hFile );
1067 done:
1068 if (tidy_cmdline != lpCommandLine) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1069 return retv;
1072 /**********************************************************************
1073 * CreateProcessW (KERNEL32.172)
1074 * NOTES
1075 * lpReserved is not converted
1077 BOOL WINAPI CreateProcessW( LPCWSTR lpApplicationName, LPWSTR lpCommandLine,
1078 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1079 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1080 BOOL bInheritHandles, DWORD dwCreationFlags,
1081 LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory,
1082 LPSTARTUPINFOW lpStartupInfo,
1083 LPPROCESS_INFORMATION lpProcessInfo )
1084 { BOOL ret;
1085 STARTUPINFOA StartupInfoA;
1087 LPSTR lpApplicationNameA = HEAP_strdupWtoA (GetProcessHeap(),0,lpApplicationName);
1088 LPSTR lpCommandLineA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCommandLine);
1089 LPSTR lpCurrentDirectoryA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCurrentDirectory);
1091 memcpy (&StartupInfoA, lpStartupInfo, sizeof(STARTUPINFOA));
1092 StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpDesktop);
1093 StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpTitle);
1095 TRACE_(win32)("(%s,%s,...)\n", debugstr_w(lpApplicationName), debugstr_w(lpCommandLine));
1097 if (lpStartupInfo->lpReserved)
1098 FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n", debugstr_w(lpStartupInfo->lpReserved));
1100 ret = CreateProcessA( lpApplicationNameA, lpCommandLineA,
1101 lpProcessAttributes, lpThreadAttributes,
1102 bInheritHandles, dwCreationFlags,
1103 lpEnvironment, lpCurrentDirectoryA,
1104 &StartupInfoA, lpProcessInfo );
1106 HeapFree( GetProcessHeap(), 0, lpCurrentDirectoryA );
1107 HeapFree( GetProcessHeap(), 0, lpCommandLineA );
1108 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1109 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1111 return ret;
1114 /***********************************************************************
1115 * GetModuleHandleA (KERNEL32.237)
1117 HMODULE WINAPI GetModuleHandleA(LPCSTR module)
1119 WINE_MODREF *wm;
1121 if ( module == NULL )
1122 wm = PROCESS_Current()->exe_modref;
1123 else
1124 wm = MODULE_FindModule( module );
1126 return wm? wm->module : 0;
1129 /***********************************************************************
1130 * GetModuleHandleW
1132 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
1134 HMODULE hModule;
1135 LPSTR modulea = HEAP_strdupWtoA( GetProcessHeap(), 0, module );
1136 hModule = GetModuleHandleA( modulea );
1137 HeapFree( GetProcessHeap(), 0, modulea );
1138 return hModule;
1142 /***********************************************************************
1143 * GetModuleFileNameA (KERNEL32.235)
1145 * GetModuleFileNameA seems to *always* return the long path;
1146 * it's only GetModuleFileName16 that decides between short/long path
1147 * by checking if exe version >= 4.0.
1148 * (SDK docu doesn't mention this)
1150 DWORD WINAPI GetModuleFileNameA(
1151 HMODULE hModule, /* [in] module handle (32bit) */
1152 LPSTR lpFileName, /* [out] filenamebuffer */
1153 DWORD size /* [in] size of filenamebuffer */
1154 ) {
1155 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1157 if (!wm) /* can happen on start up or the like */
1158 return 0;
1160 lstrcpynA( lpFileName, wm->filename, size );
1162 TRACE("%s\n", lpFileName );
1163 return strlen(lpFileName);
1167 /***********************************************************************
1168 * GetModuleFileNameW (KERNEL32.236)
1170 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName,
1171 DWORD size )
1173 LPSTR fnA = (char*)HeapAlloc( GetProcessHeap(), 0, size );
1174 DWORD res = GetModuleFileNameA( hModule, fnA, size );
1175 lstrcpynAtoW( lpFileName, fnA, size );
1176 HeapFree( GetProcessHeap(), 0, fnA );
1177 return res;
1181 /***********************************************************************
1182 * LoadLibraryExA (KERNEL32)
1184 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
1186 WINE_MODREF *wm;
1188 if(!libname)
1190 SetLastError(ERROR_INVALID_PARAMETER);
1191 return 0;
1194 EnterCriticalSection(&PROCESS_Current()->crit_section);
1196 wm = MODULE_LoadLibraryExA( libname, hfile, flags );
1197 if ( wm )
1199 if ( !MODULE_DllProcessAttach( wm, NULL ) )
1201 WARN_(module)("Attach failed for module '%s', \n", libname);
1202 MODULE_FreeLibrary(wm);
1203 SetLastError(ERROR_DLL_INIT_FAILED);
1204 wm = NULL;
1208 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1210 return wm ? wm->module : 0;
1213 /***********************************************************************
1214 * MODULE_LoadLibraryExA (internal)
1216 * Load a PE style module according to the load order.
1218 * The HFILE parameter is not used and marked reserved in the SDK. I can
1219 * only guess that it should force a file to be mapped, but I rather
1220 * ignore the parameter because it would be extremely difficult to
1221 * integrate this with different types of module represenations.
1224 WINE_MODREF *MODULE_LoadLibraryExA( LPCSTR libname, HFILE hfile, DWORD flags )
1226 DWORD err = GetLastError();
1227 WINE_MODREF *pwm;
1228 int i;
1229 module_loadorder_t *plo;
1231 EnterCriticalSection(&PROCESS_Current()->crit_section);
1233 /* Check for already loaded module */
1234 if((pwm = MODULE_FindModule(libname)))
1236 if(!(pwm->flags & WINE_MODREF_MARKER))
1237 pwm->refCount++;
1238 TRACE("Already loaded module '%s' at 0x%08x, count=%d, \n", libname, pwm->module, pwm->refCount);
1239 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1240 return pwm;
1243 plo = MODULE_GetLoadOrder(libname);
1245 for(i = 0; i < MODULE_LOADORDER_NTYPES; i++)
1247 SetLastError( ERROR_FILE_NOT_FOUND );
1248 switch(plo->loadorder[i])
1250 case MODULE_LOADORDER_DLL:
1251 TRACE("Trying native dll '%s'\n", libname);
1252 pwm = PE_LoadLibraryExA(libname, flags);
1253 break;
1255 case MODULE_LOADORDER_ELFDLL:
1256 TRACE("Trying elfdll '%s'\n", libname);
1257 if (!(pwm = BUILTIN32_LoadLibraryExA(libname, flags)))
1258 pwm = ELFDLL_LoadLibraryExA(libname, flags);
1259 break;
1261 case MODULE_LOADORDER_SO:
1262 TRACE("Trying so-library '%s'\n", libname);
1263 if (!(pwm = BUILTIN32_LoadLibraryExA(libname, flags)))
1264 pwm = ELF_LoadLibraryExA(libname, flags);
1265 break;
1267 case MODULE_LOADORDER_BI:
1268 TRACE("Trying built-in '%s'\n", libname);
1269 pwm = BUILTIN32_LoadLibraryExA(libname, flags);
1270 break;
1272 default:
1273 ERR("Got invalid loadorder type %d (%s index %d)\n", plo->loadorder[i], plo->modulename, i);
1274 /* Fall through */
1276 case MODULE_LOADORDER_INVALID: /* We ignore this as it is an empty entry */
1277 pwm = NULL;
1278 break;
1281 if(pwm)
1283 /* Initialize DLL just loaded */
1284 TRACE("Loaded module '%s' at 0x%08x, \n", libname, pwm->module);
1286 /* Set the refCount here so that an attach failure will */
1287 /* decrement the dependencies through the MODULE_FreeLibrary call. */
1288 pwm->refCount++;
1290 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1291 SetLastError( err ); /* restore last error */
1292 return pwm;
1295 if(GetLastError() != ERROR_FILE_NOT_FOUND)
1296 break;
1299 WARN("Failed to load module '%s'; error=0x%08lx, \n", libname, GetLastError());
1300 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1301 return NULL;
1304 /***********************************************************************
1305 * LoadLibraryA (KERNEL32)
1307 HMODULE WINAPI LoadLibraryA(LPCSTR libname) {
1308 return LoadLibraryExA(libname,0,0);
1311 /***********************************************************************
1312 * LoadLibraryW (KERNEL32)
1314 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
1316 return LoadLibraryExW(libnameW,0,0);
1319 /***********************************************************************
1320 * LoadLibrary32_16 (KERNEL.452)
1322 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
1324 HMODULE hModule;
1326 SYSLEVEL_ReleaseWin16Lock();
1327 hModule = LoadLibraryA( libname );
1328 SYSLEVEL_RestoreWin16Lock();
1330 return hModule;
1333 /***********************************************************************
1334 * LoadLibraryExW (KERNEL32)
1336 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW,HANDLE hfile,DWORD flags)
1338 LPSTR libnameA = HEAP_strdupWtoA( GetProcessHeap(), 0, libnameW );
1339 HMODULE ret = LoadLibraryExA( libnameA , hfile, flags );
1341 HeapFree( GetProcessHeap(), 0, libnameA );
1342 return ret;
1345 /***********************************************************************
1346 * MODULE_FlushModrefs
1348 * NOTE: Assumes that the process critical section is held!
1350 * Remove all unused modrefs and call the internal unloading routines
1351 * for the library type.
1353 static void MODULE_FlushModrefs(void)
1355 WINE_MODREF *wm, *next;
1357 for(wm = PROCESS_Current()->modref_list; wm; wm = next)
1359 next = wm->next;
1361 if(wm->refCount)
1362 continue;
1364 /* Unlink this modref from the chain */
1365 if(wm->next)
1366 wm->next->prev = wm->prev;
1367 if(wm->prev)
1368 wm->prev->next = wm->next;
1369 if(wm == PROCESS_Current()->modref_list)
1370 PROCESS_Current()->modref_list = wm->next;
1373 * The unloaders are also responsible for freeing the modref itself
1374 * because the loaders were responsible for allocating it.
1376 switch(wm->type)
1378 case MODULE32_PE: if ( !(wm->flags & WINE_MODREF_INTERNAL) )
1379 PE_UnloadLibrary(wm);
1380 else
1381 BUILTIN32_UnloadLibrary(wm);
1382 break;
1383 case MODULE32_ELF: ELF_UnloadLibrary(wm); break;
1384 case MODULE32_ELFDLL: ELFDLL_UnloadLibrary(wm); break;
1386 default:
1387 ERR("Invalid or unhandled MODREF type %d encountered (wm=%p)\n", wm->type, wm);
1392 /***********************************************************************
1393 * FreeLibrary
1395 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
1397 BOOL retv = FALSE;
1398 WINE_MODREF *wm;
1400 EnterCriticalSection( &PROCESS_Current()->crit_section );
1401 PROCESS_Current()->free_lib_count++;
1403 wm = MODULE32_LookupHMODULE( hLibModule );
1404 if ( !wm || !hLibModule )
1405 SetLastError( ERROR_INVALID_HANDLE );
1406 else
1407 retv = MODULE_FreeLibrary( wm );
1409 PROCESS_Current()->free_lib_count--;
1410 LeaveCriticalSection( &PROCESS_Current()->crit_section );
1412 return retv;
1415 /***********************************************************************
1416 * MODULE_DecRefCount
1418 * NOTE: Assumes that the process critical section is held!
1420 static void MODULE_DecRefCount( WINE_MODREF *wm )
1422 int i;
1424 if ( wm->flags & WINE_MODREF_MARKER )
1425 return;
1427 if ( wm->refCount <= 0 )
1428 return;
1430 --wm->refCount;
1431 TRACE("(%s) refCount: %d\n", wm->modname, wm->refCount );
1433 if ( wm->refCount == 0 )
1435 wm->flags |= WINE_MODREF_MARKER;
1437 for ( i = 0; i < wm->nDeps; i++ )
1438 if ( wm->deps[i] )
1439 MODULE_DecRefCount( wm->deps[i] );
1441 wm->flags &= ~WINE_MODREF_MARKER;
1445 /***********************************************************************
1446 * MODULE_FreeLibrary
1448 * NOTE: Assumes that the process critical section is held!
1450 BOOL MODULE_FreeLibrary( WINE_MODREF *wm )
1452 TRACE("(%s) - START\n", wm->modname );
1454 /* Recursively decrement reference counts */
1455 MODULE_DecRefCount( wm );
1457 /* Call process detach notifications */
1458 if ( PROCESS_Current()->free_lib_count <= 1 )
1460 struct unload_dll_request *req = get_req_buffer();
1462 MODULE_DllProcessDetach( FALSE, NULL );
1463 req->base = (void *)wm->module;
1464 server_call_noerr( REQ_UNLOAD_DLL );
1466 MODULE_FlushModrefs();
1469 TRACE("END\n");
1471 return TRUE;
1475 /***********************************************************************
1476 * FreeLibraryAndExitThread
1478 VOID WINAPI FreeLibraryAndExitThread(HINSTANCE hLibModule, DWORD dwExitCode)
1480 FreeLibrary(hLibModule);
1481 ExitThread(dwExitCode);
1484 /***********************************************************************
1485 * PrivateLoadLibrary (KERNEL32)
1487 * FIXME: rough guesswork, don't know what "Private" means
1489 HINSTANCE WINAPI PrivateLoadLibrary(LPCSTR libname)
1491 return (HINSTANCE)LoadLibrary16(libname);
1496 /***********************************************************************
1497 * PrivateFreeLibrary (KERNEL32)
1499 * FIXME: rough guesswork, don't know what "Private" means
1501 void WINAPI PrivateFreeLibrary(HINSTANCE handle)
1503 FreeLibrary16((HINSTANCE16)handle);
1507 /***********************************************************************
1508 * WIN32_GetProcAddress16 (KERNEL32.36)
1509 * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
1511 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
1513 WORD ordinal;
1514 FARPROC16 ret;
1516 if (!hModule) {
1517 WARN("hModule may not be 0!\n");
1518 return (FARPROC16)0;
1520 if (HIWORD(hModule))
1522 WARN("hModule is Win32 handle (%08x)\n", hModule );
1523 return (FARPROC16)0;
1525 hModule = GetExePtr( hModule );
1526 if (HIWORD(name)) {
1527 ordinal = NE_GetOrdinal( hModule, name );
1528 TRACE("%04x '%s'\n", hModule, name );
1529 } else {
1530 ordinal = LOWORD(name);
1531 TRACE("%04x %04x\n", hModule, ordinal );
1533 if (!ordinal) return (FARPROC16)0;
1534 ret = NE_GetEntryPoint( hModule, ordinal );
1535 TRACE("returning %08x\n",(UINT)ret);
1536 return ret;
1539 /***********************************************************************
1540 * GetProcAddress16 (KERNEL.50)
1542 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, SEGPTR name )
1544 WORD ordinal;
1545 FARPROC16 ret;
1547 if (!hModule) hModule = GetCurrentTask();
1548 hModule = GetExePtr( hModule );
1550 if (HIWORD(name) != 0)
1552 ordinal = NE_GetOrdinal( hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1553 TRACE("%04x '%s'\n", hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1555 else
1557 ordinal = LOWORD(name);
1558 TRACE("%04x %04x\n", hModule, ordinal );
1560 if (!ordinal) return (FARPROC16)0;
1562 ret = NE_GetEntryPoint( hModule, ordinal );
1564 TRACE("returning %08x\n", (UINT)ret );
1565 return ret;
1569 /***********************************************************************
1570 * GetProcAddress (KERNEL32.257)
1572 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1574 return MODULE_GetProcAddress( hModule, function, TRUE );
1577 /***********************************************************************
1578 * GetProcAddress32 (KERNEL.453)
1580 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
1582 return MODULE_GetProcAddress( hModule, function, FALSE );
1585 /***********************************************************************
1586 * MODULE_GetProcAddress (internal)
1588 FARPROC MODULE_GetProcAddress(
1589 HMODULE hModule, /* [in] current module handle */
1590 LPCSTR function, /* [in] function to be looked up */
1591 BOOL snoop )
1593 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1594 FARPROC retproc;
1596 if (HIWORD(function))
1597 TRACE_(win32)("(%08lx,%s)\n",(DWORD)hModule,function);
1598 else
1599 TRACE_(win32)("(%08lx,%p)\n",(DWORD)hModule,function);
1600 if (!wm) {
1601 SetLastError(ERROR_INVALID_HANDLE);
1602 return (FARPROC)0;
1604 switch (wm->type)
1606 case MODULE32_PE:
1607 retproc = PE_FindExportedFunction( wm, function, snoop );
1608 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1609 return retproc;
1610 case MODULE32_ELF:
1611 retproc = ELF_FindExportedFunction( wm, function);
1612 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1613 return retproc;
1614 default:
1615 ERR("wine_modref type %d not handled.\n",wm->type);
1616 SetLastError(ERROR_INVALID_HANDLE);
1617 return (FARPROC)0;
1622 /***********************************************************************
1623 * RtlImageNtHeader (NTDLL)
1625 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
1627 /* basically:
1628 * return hModule+(((IMAGE_DOS_HEADER*)hModule)->e_lfanew);
1629 * but we could get HMODULE16 or the like (think builtin modules)
1632 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1633 if (!wm || (wm->type != MODULE32_PE)) return (PIMAGE_NT_HEADERS)0;
1634 return PE_HEADER(wm->module);
1638 /***************************************************************************
1639 * HasGPHandler (KERNEL.338)
1642 #include "pshpack1.h"
1643 typedef struct _GPHANDLERDEF
1645 WORD selector;
1646 WORD rangeStart;
1647 WORD rangeEnd;
1648 WORD handler;
1649 } GPHANDLERDEF;
1650 #include "poppack.h"
1652 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1654 HMODULE16 hModule;
1655 int gpOrdinal;
1656 SEGPTR gpPtr;
1657 GPHANDLERDEF *gpHandler;
1659 if ( (hModule = FarGetOwner16( SELECTOROF(address) )) != 0
1660 && (gpOrdinal = NE_GetOrdinal( hModule, "__GP" )) != 0
1661 && (gpPtr = (SEGPTR)NE_GetEntryPointEx( hModule, gpOrdinal, FALSE )) != 0
1662 && !IsBadReadPtr16( gpPtr, sizeof(GPHANDLERDEF) )
1663 && (gpHandler = PTR_SEG_TO_LIN( gpPtr )) != NULL )
1665 while (gpHandler->selector)
1667 if ( SELECTOROF(address) == gpHandler->selector
1668 && OFFSETOF(address) >= gpHandler->rangeStart
1669 && OFFSETOF(address) < gpHandler->rangeEnd )
1670 return PTR_SEG_OFF_TO_SEGPTR( gpHandler->selector,
1671 gpHandler->handler );
1672 gpHandler++;
1676 return 0;