Text of WWN article "The Registry".
[wine.git] / loader / module.c
blob65db9cf3424af0a79ebf8d480d262e109b82fde2
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;
446 /***********************************************************************
447 * MODULE_GetBinaryType
449 * The GetBinaryType function determines whether a file is executable
450 * or not and if it is it returns what type of executable it is.
451 * The type of executable is a property that determines in which
452 * subsystem an executable file runs under.
454 * Binary types returned:
455 * SCS_32BIT_BINARY: A Win32 based application
456 * SCS_DOS_BINARY: An MS-Dos based application
457 * SCS_WOW_BINARY: A Win16 based application
458 * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
459 * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
460 * SCS_OS216_BINARY: A 16bit OS/2 based application
462 * Returns TRUE if the file is an executable in which case
463 * the value pointed by lpBinaryType is set.
464 * Returns FALSE if the file is not an executable or if the function fails.
466 * To do so it opens the file and reads in the header information
467 * if the extended header information is not present it will
468 * assume that the file is a DOS executable.
469 * If the extended header information is present it will
470 * determine if the file is a 16 or 32 bit Windows executable
471 * by check the flags in the header.
473 * Note that .COM and .PIF files are only recognized by their
474 * file name extension; but Windows does it the same way ...
476 BOOL MODULE_GetBinaryType( HANDLE hfile, LPCSTR filename, LPDWORD lpBinaryType )
478 IMAGE_DOS_HEADER mz_header;
479 char magic[4], *ptr;
480 DWORD len;
482 /* Seek to the start of the file and read the DOS header information.
484 if ( SetFilePointer( hfile, 0, NULL, SEEK_SET ) != -1
485 && ReadFile( hfile, &mz_header, sizeof(mz_header), &len, NULL )
486 && len == sizeof(mz_header) )
488 /* Now that we have the header check the e_magic field
489 * to see if this is a dos image.
491 if ( mz_header.e_magic == IMAGE_DOS_SIGNATURE )
493 BOOL lfanewValid = FALSE;
494 /* We do have a DOS image so we will now try to seek into
495 * the file by the amount indicated by the field
496 * "Offset to extended header" and read in the
497 * "magic" field information at that location.
498 * This will tell us if there is more header information
499 * to read or not.
501 /* But before we do we will make sure that header
502 * structure encompasses the "Offset to extended header"
503 * field.
505 if ( (mz_header.e_cparhdr<<4) >= sizeof(IMAGE_DOS_HEADER) )
506 if ( ( mz_header.e_crlc == 0 ) ||
507 ( mz_header.e_lfarlc >= sizeof(IMAGE_DOS_HEADER) ) )
508 if ( mz_header.e_lfanew >= sizeof(IMAGE_DOS_HEADER)
509 && SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET ) != -1
510 && ReadFile( hfile, magic, sizeof(magic), &len, NULL )
511 && len == sizeof(magic) )
512 lfanewValid = TRUE;
514 if ( !lfanewValid )
516 /* If we cannot read this "extended header" we will
517 * assume that we have a simple DOS executable.
519 *lpBinaryType = SCS_DOS_BINARY;
520 return TRUE;
522 else
524 /* Reading the magic field succeeded so
525 * we will try to determine what type it is.
527 if ( *(DWORD*)magic == IMAGE_NT_SIGNATURE )
529 /* This is an NT signature.
531 *lpBinaryType = SCS_32BIT_BINARY;
532 return TRUE;
534 else if ( *(WORD*)magic == IMAGE_OS2_SIGNATURE )
536 /* The IMAGE_OS2_SIGNATURE indicates that the
537 * "extended header is a Windows executable (NE)
538 * header." This can mean either a 16-bit OS/2
539 * or a 16-bit Windows or even a DOS program
540 * (running under a DOS extender). To decide
541 * which, we'll have to read the NE header.
544 IMAGE_OS2_HEADER ne;
545 if ( SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET ) != -1
546 && ReadFile( hfile, &ne, sizeof(ne), &len, NULL )
547 && len == sizeof(ne) )
549 switch ( ne.ne_exetyp )
551 case 2: *lpBinaryType = SCS_WOW_BINARY; return TRUE;
552 case 5: *lpBinaryType = SCS_DOS_BINARY; return TRUE;
553 default: *lpBinaryType = SCS_OS216_BINARY; return TRUE;
556 /* Couldn't read header, so abort. */
557 return FALSE;
559 else
561 /* Unknown extended header, but this file is nonetheless
562 DOS-executable.
564 *lpBinaryType = SCS_DOS_BINARY;
565 return TRUE;
571 /* If we get here, we don't even have a correct MZ header.
572 * Try to check the file extension for known types ...
574 ptr = strrchr( filename, '.' );
575 if ( ptr && !strchr( ptr, '\\' ) && !strchr( ptr, '/' ) )
577 if ( !lstrcmpiA( ptr, ".COM" ) )
579 *lpBinaryType = SCS_DOS_BINARY;
580 return TRUE;
583 if ( !lstrcmpiA( ptr, ".PIF" ) )
585 *lpBinaryType = SCS_PIF_BINARY;
586 return TRUE;
590 return FALSE;
593 /***********************************************************************
594 * GetBinaryTypeA [KERNEL32.280]
596 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
598 BOOL ret = FALSE;
599 HANDLE hfile;
601 TRACE_(win32)("%s\n", lpApplicationName );
603 /* Sanity check.
605 if ( lpApplicationName == NULL || lpBinaryType == NULL )
606 return FALSE;
608 /* Open the file indicated by lpApplicationName for reading.
610 hfile = CreateFileA( lpApplicationName, GENERIC_READ, FILE_SHARE_READ,
611 NULL, OPEN_EXISTING, 0, -1 );
612 if ( hfile == INVALID_HANDLE_VALUE )
613 return FALSE;
615 /* Check binary type
617 ret = MODULE_GetBinaryType( hfile, lpApplicationName, lpBinaryType );
619 /* Close the file.
621 CloseHandle( hfile );
623 return ret;
626 /***********************************************************************
627 * GetBinaryTypeW [KERNEL32.281]
629 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
631 BOOL ret = FALSE;
632 LPSTR strNew = NULL;
634 TRACE_(win32)("%s\n", debugstr_w(lpApplicationName) );
636 /* Sanity check.
638 if ( lpApplicationName == NULL || lpBinaryType == NULL )
639 return FALSE;
641 /* Convert the wide string to a ascii string.
643 strNew = HEAP_strdupWtoA( GetProcessHeap(), 0, lpApplicationName );
645 if ( strNew != NULL )
647 ret = GetBinaryTypeA( strNew, lpBinaryType );
649 /* Free the allocated string.
651 HeapFree( GetProcessHeap(), 0, strNew );
654 return ret;
658 /***********************************************************************
659 * WinExec16 (KERNEL.166)
661 HINSTANCE16 WINAPI WinExec16( LPCSTR lpCmdLine, UINT16 nCmdShow )
663 LPCSTR p;
664 LPSTR name, cmdline;
665 int len;
666 HINSTANCE16 ret;
667 char buffer[MAX_PATH];
669 if ((p = strchr( lpCmdLine, ' ' )))
671 if (!(name = HeapAlloc( GetProcessHeap(), 0, p - lpCmdLine + 1 )))
672 return ERROR_NOT_ENOUGH_MEMORY;
673 memcpy( name, lpCmdLine, p - lpCmdLine );
674 name[p - lpCmdLine] = 0;
675 p++;
676 len = strlen(p);
677 cmdline = SEGPTR_ALLOC( len + 2 );
678 cmdline[0] = (BYTE)len;
679 strcpy( cmdline + 1, p );
681 else
683 name = (LPSTR)lpCmdLine;
684 cmdline = SEGPTR_ALLOC(2);
685 cmdline[0] = cmdline[1] = 0;
688 if (SearchPathA( NULL, name, ".exe", sizeof(buffer), buffer, NULL ))
690 LOADPARAMS16 params;
691 WORD *showCmd = SEGPTR_ALLOC( 2*sizeof(WORD) );
692 showCmd[0] = 2;
693 showCmd[1] = nCmdShow;
695 params.hEnvironment = 0;
696 params.cmdLine = SEGPTR_GET(cmdline);
697 params.showCmd = SEGPTR_GET(showCmd);
698 params.reserved = 0;
700 ret = LoadModule16( buffer, &params );
702 SEGPTR_FREE( showCmd );
703 SEGPTR_FREE( cmdline );
705 else ret = GetLastError();
707 if (name != lpCmdLine) HeapFree( GetProcessHeap(), 0, name );
709 if (ret == 21) /* 32-bit module */
711 SYSLEVEL_ReleaseWin16Lock();
712 ret = WinExec( lpCmdLine, nCmdShow );
713 SYSLEVEL_RestoreWin16Lock();
715 return ret;
718 /***********************************************************************
719 * WinExec (KERNEL32.566)
721 HINSTANCE WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
723 PROCESS_INFORMATION info;
724 STARTUPINFOA startup;
725 HINSTANCE hInstance;
726 char *cmdline;
728 memset( &startup, 0, sizeof(startup) );
729 startup.cb = sizeof(startup);
730 startup.dwFlags = STARTF_USESHOWWINDOW;
731 startup.wShowWindow = nCmdShow;
733 /* cmdline needs to be writeable for CreateProcess */
734 if (!(cmdline = HEAP_strdupA( GetProcessHeap(), 0, lpCmdLine ))) return 0;
736 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
737 0, NULL, NULL, &startup, &info ))
739 /* Give 30 seconds to the app to come up */
740 if (Callout.WaitForInputIdle ( info.hProcess, 30000 ) == 0xFFFFFFFF)
741 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
742 hInstance = 33;
743 /* Close off the handles */
744 CloseHandle( info.hThread );
745 CloseHandle( info.hProcess );
747 else if ((hInstance = GetLastError()) >= 32)
749 FIXME("Strange error set by CreateProcess: %d\n", hInstance );
750 hInstance = 11;
752 HeapFree( GetProcessHeap(), 0, cmdline );
753 return hInstance;
756 /**********************************************************************
757 * LoadModule (KERNEL32.499)
759 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
761 LOADPARAMS *params = (LOADPARAMS *)paramBlock;
762 PROCESS_INFORMATION info;
763 STARTUPINFOA startup;
764 HINSTANCE hInstance;
765 LPSTR cmdline, p;
766 char filename[MAX_PATH];
767 BYTE len;
769 if (!name) return ERROR_FILE_NOT_FOUND;
771 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
772 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
773 return GetLastError();
775 len = (BYTE)params->lpCmdLine[0];
776 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
777 return ERROR_NOT_ENOUGH_MEMORY;
779 strcpy( cmdline, filename );
780 p = cmdline + strlen(cmdline);
781 *p++ = ' ';
782 memcpy( p, params->lpCmdLine + 1, len );
783 p[len] = 0;
785 memset( &startup, 0, sizeof(startup) );
786 startup.cb = sizeof(startup);
787 if (params->lpCmdShow)
789 startup.dwFlags = STARTF_USESHOWWINDOW;
790 startup.wShowWindow = params->lpCmdShow[1];
793 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
794 params->lpEnvAddress, NULL, &startup, &info ))
796 /* Give 30 seconds to the app to come up */
797 if ( Callout.WaitForInputIdle ( info.hProcess, 30000 ) == 0xFFFFFFFF )
798 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
799 hInstance = 33;
800 /* Close off the handles */
801 CloseHandle( info.hThread );
802 CloseHandle( info.hProcess );
804 else if ((hInstance = GetLastError()) >= 32)
806 FIXME("Strange error set by CreateProcess: %d\n", hInstance );
807 hInstance = 11;
810 HeapFree( GetProcessHeap(), 0, cmdline );
811 return hInstance;
815 /*************************************************************************
816 * get_file_name
818 * Helper for CreateProcess: retrieve the file name to load from the
819 * app name and command line. Store the file name in buffer, and
820 * return a possibly modified command line.
822 static LPSTR get_file_name( LPCSTR appname, LPSTR cmdline, LPSTR buffer, int buflen )
824 char *name, *pos, *ret = NULL;
825 const char *p;
827 /* if we have an app name, everything is easy */
829 if (appname)
831 /* use the unmodified app name as file name */
832 lstrcpynA( buffer, appname, buflen );
833 if (!(ret = cmdline))
835 /* no command-line, create one */
836 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(appname) + 3 )))
837 sprintf( ret, "\"%s\"", appname );
839 return ret;
842 if (!cmdline)
844 SetLastError( ERROR_INVALID_PARAMETER );
845 return NULL;
848 /* first check for a quoted file name */
850 if ((cmdline[0] == '"') && ((p = strchr( cmdline + 1, '"' ))))
852 int len = p - cmdline - 1;
853 /* extract the quoted portion as file name */
854 if (!(name = HeapAlloc( GetProcessHeap(), 0, len + 1 ))) return NULL;
855 memcpy( name, cmdline + 1, len );
856 name[len] = 0;
858 if (SearchPathA( NULL, name, ".exe", buflen, buffer, NULL ) ||
859 SearchPathA( NULL, name, NULL, buflen, buffer, NULL ))
860 ret = cmdline; /* no change necessary */
861 goto done;
864 /* now try the command-line word by word */
866 if (!(name = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 1 ))) return NULL;
867 pos = name;
868 p = cmdline;
870 while (*p)
872 do *pos++ = *p++; while (*p && *p != ' ');
873 *pos = 0;
874 TRACE("trying '%s'\n", name );
875 if (SearchPathA( NULL, name, ".exe", buflen, buffer, NULL ) ||
876 SearchPathA( NULL, name, NULL, buflen, buffer, NULL ))
878 ret = cmdline;
879 break;
883 if (!ret || !strchr( name, ' ' )) goto done; /* no change necessary */
885 /* now build a new command-line with quotes */
887 if (!(ret = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 3 ))) goto done;
888 sprintf( ret, "\"%s\"%s", name, p );
890 done:
891 HeapFree( GetProcessHeap(), 0, name );
892 return ret;
896 /**********************************************************************
897 * CreateProcessA (KERNEL32.171)
899 BOOL WINAPI CreateProcessA( LPCSTR lpApplicationName, LPSTR lpCommandLine,
900 LPSECURITY_ATTRIBUTES lpProcessAttributes,
901 LPSECURITY_ATTRIBUTES lpThreadAttributes,
902 BOOL bInheritHandles, DWORD dwCreationFlags,
903 LPVOID lpEnvironment, LPCSTR lpCurrentDirectory,
904 LPSTARTUPINFOA lpStartupInfo,
905 LPPROCESS_INFORMATION lpProcessInfo )
907 BOOL retv = FALSE;
908 HANDLE hFile;
909 DWORD type;
910 char name[MAX_PATH];
911 LPSTR tidy_cmdline;
913 /* Process the AppName and/or CmdLine to get module name and path */
915 TRACE("app '%s' cmdline '%s'\n", lpApplicationName, lpCommandLine );
917 if (!(tidy_cmdline = get_file_name( lpApplicationName, lpCommandLine, name, sizeof(name) )))
918 return FALSE;
920 /* Warn if unsupported features are used */
922 if (dwCreationFlags & DETACHED_PROCESS)
923 FIXME("(%s,...): DETACHED_PROCESS ignored\n", name);
924 if (dwCreationFlags & CREATE_NEW_CONSOLE)
925 FIXME("(%s,...): CREATE_NEW_CONSOLE ignored\n", name);
926 if (dwCreationFlags & NORMAL_PRIORITY_CLASS)
927 FIXME("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
928 if (dwCreationFlags & IDLE_PRIORITY_CLASS)
929 FIXME("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
930 if (dwCreationFlags & HIGH_PRIORITY_CLASS)
931 FIXME("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
932 if (dwCreationFlags & REALTIME_PRIORITY_CLASS)
933 FIXME("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
934 if (dwCreationFlags & CREATE_NEW_PROCESS_GROUP)
935 FIXME("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
936 if (dwCreationFlags & CREATE_UNICODE_ENVIRONMENT)
937 FIXME("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
938 if (dwCreationFlags & CREATE_SEPARATE_WOW_VDM)
939 FIXME("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
940 if (dwCreationFlags & CREATE_SHARED_WOW_VDM)
941 FIXME("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
942 if (dwCreationFlags & CREATE_DEFAULT_ERROR_MODE)
943 FIXME("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
944 if (dwCreationFlags & CREATE_NO_WINDOW)
945 FIXME("(%s,...): CREATE_NO_WINDOW ignored\n", name);
946 if (dwCreationFlags & PROFILE_USER)
947 FIXME("(%s,...): PROFILE_USER ignored\n", name);
948 if (dwCreationFlags & PROFILE_KERNEL)
949 FIXME("(%s,...): PROFILE_KERNEL ignored\n", name);
950 if (dwCreationFlags & PROFILE_SERVER)
951 FIXME("(%s,...): PROFILE_SERVER ignored\n", name);
952 if (lpCurrentDirectory)
953 FIXME("(%s,...): lpCurrentDirectory %s ignored\n",
954 name, lpCurrentDirectory);
955 if (lpStartupInfo->lpDesktop)
956 FIXME("(%s,...): lpStartupInfo->lpDesktop %s ignored\n",
957 name, lpStartupInfo->lpDesktop);
958 if (lpStartupInfo->lpTitle)
959 FIXME("(%s,...): lpStartupInfo->lpTitle %s ignored\n",
960 name, lpStartupInfo->lpTitle);
961 if (lpStartupInfo->dwFlags & STARTF_USECOUNTCHARS)
962 FIXME("(%s,...): STARTF_USECOUNTCHARS (%ld,%ld) ignored\n",
963 name, lpStartupInfo->dwXCountChars, lpStartupInfo->dwYCountChars);
964 if (lpStartupInfo->dwFlags & STARTF_USEFILLATTRIBUTE)
965 FIXME("(%s,...): STARTF_USEFILLATTRIBUTE %lx ignored\n",
966 name, lpStartupInfo->dwFillAttribute);
967 if (lpStartupInfo->dwFlags & STARTF_RUNFULLSCREEN)
968 FIXME("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
969 if (lpStartupInfo->dwFlags & STARTF_FORCEONFEEDBACK)
970 FIXME("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
971 if (lpStartupInfo->dwFlags & STARTF_FORCEOFFFEEDBACK)
972 FIXME("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
973 if (lpStartupInfo->dwFlags & STARTF_USEHOTKEY)
974 FIXME("(%s,...): STARTF_USEHOTKEY ignored\n", name);
976 /* Open file and determine executable type */
978 hFile = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, -1 );
979 if (hFile == INVALID_HANDLE_VALUE) goto done;
981 if ( !MODULE_GetBinaryType( hFile, name, &type ) )
983 CloseHandle( hFile );
984 retv = PROCESS_Create( -1, name, tidy_cmdline, lpEnvironment,
985 lpProcessAttributes, lpThreadAttributes,
986 bInheritHandles, dwCreationFlags,
987 lpStartupInfo, lpProcessInfo );
988 goto done;
991 /* Create process */
993 switch ( type )
995 case SCS_32BIT_BINARY:
996 case SCS_WOW_BINARY:
997 case SCS_DOS_BINARY:
998 retv = PROCESS_Create( hFile, name, tidy_cmdline, lpEnvironment,
999 lpProcessAttributes, lpThreadAttributes,
1000 bInheritHandles, dwCreationFlags,
1001 lpStartupInfo, lpProcessInfo );
1002 break;
1004 case SCS_PIF_BINARY:
1005 case SCS_POSIX_BINARY:
1006 case SCS_OS216_BINARY:
1007 FIXME("Unsupported executable type: %ld\n", type );
1008 /* fall through */
1010 default:
1011 SetLastError( ERROR_BAD_FORMAT );
1012 break;
1014 CloseHandle( hFile );
1016 done:
1017 if (tidy_cmdline != lpCommandLine) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1018 return retv;
1021 /**********************************************************************
1022 * CreateProcessW (KERNEL32.172)
1023 * NOTES
1024 * lpReserved is not converted
1026 BOOL WINAPI CreateProcessW( LPCWSTR lpApplicationName, LPWSTR lpCommandLine,
1027 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1028 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1029 BOOL bInheritHandles, DWORD dwCreationFlags,
1030 LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory,
1031 LPSTARTUPINFOW lpStartupInfo,
1032 LPPROCESS_INFORMATION lpProcessInfo )
1033 { BOOL ret;
1034 STARTUPINFOA StartupInfoA;
1036 LPSTR lpApplicationNameA = HEAP_strdupWtoA (GetProcessHeap(),0,lpApplicationName);
1037 LPSTR lpCommandLineA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCommandLine);
1038 LPSTR lpCurrentDirectoryA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCurrentDirectory);
1040 memcpy (&StartupInfoA, lpStartupInfo, sizeof(STARTUPINFOA));
1041 StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpDesktop);
1042 StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpTitle);
1044 TRACE_(win32)("(%s,%s,...)\n", debugstr_w(lpApplicationName), debugstr_w(lpCommandLine));
1046 if (lpStartupInfo->lpReserved)
1047 FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n", debugstr_w(lpStartupInfo->lpReserved));
1049 ret = CreateProcessA( lpApplicationNameA, lpCommandLineA,
1050 lpProcessAttributes, lpThreadAttributes,
1051 bInheritHandles, dwCreationFlags,
1052 lpEnvironment, lpCurrentDirectoryA,
1053 &StartupInfoA, lpProcessInfo );
1055 HeapFree( GetProcessHeap(), 0, lpCurrentDirectoryA );
1056 HeapFree( GetProcessHeap(), 0, lpCommandLineA );
1057 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1058 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1060 return ret;
1063 /***********************************************************************
1064 * GetModuleHandleA (KERNEL32.237)
1066 HMODULE WINAPI GetModuleHandleA(LPCSTR module)
1068 WINE_MODREF *wm;
1070 if ( module == NULL )
1071 wm = PROCESS_Current()->exe_modref;
1072 else
1073 wm = MODULE_FindModule( module );
1075 return wm? wm->module : 0;
1078 /***********************************************************************
1079 * GetModuleHandleW
1081 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
1083 HMODULE hModule;
1084 LPSTR modulea = HEAP_strdupWtoA( GetProcessHeap(), 0, module );
1085 hModule = GetModuleHandleA( modulea );
1086 HeapFree( GetProcessHeap(), 0, modulea );
1087 return hModule;
1091 /***********************************************************************
1092 * GetModuleFileNameA (KERNEL32.235)
1094 * GetModuleFileNameA seems to *always* return the long path;
1095 * it's only GetModuleFileName16 that decides between short/long path
1096 * by checking if exe version >= 4.0.
1097 * (SDK docu doesn't mention this)
1099 DWORD WINAPI GetModuleFileNameA(
1100 HMODULE hModule, /* [in] module handle (32bit) */
1101 LPSTR lpFileName, /* [out] filenamebuffer */
1102 DWORD size /* [in] size of filenamebuffer */
1103 ) {
1104 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1106 if (!wm) /* can happen on start up or the like */
1107 return 0;
1109 lstrcpynA( lpFileName, wm->filename, size );
1111 TRACE("%s\n", lpFileName );
1112 return strlen(lpFileName);
1116 /***********************************************************************
1117 * GetModuleFileNameW (KERNEL32.236)
1119 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName,
1120 DWORD size )
1122 LPSTR fnA = (char*)HeapAlloc( GetProcessHeap(), 0, size );
1123 DWORD res = GetModuleFileNameA( hModule, fnA, size );
1124 lstrcpynAtoW( lpFileName, fnA, size );
1125 HeapFree( GetProcessHeap(), 0, fnA );
1126 return res;
1130 /***********************************************************************
1131 * LoadLibraryExA (KERNEL32)
1133 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
1135 WINE_MODREF *wm;
1137 if(!libname)
1139 SetLastError(ERROR_INVALID_PARAMETER);
1140 return 0;
1143 EnterCriticalSection(&PROCESS_Current()->crit_section);
1145 wm = MODULE_LoadLibraryExA( libname, hfile, flags );
1146 if ( wm )
1148 if ( !MODULE_DllProcessAttach( wm, NULL ) )
1150 WARN_(module)("Attach failed for module '%s', \n", libname);
1151 MODULE_FreeLibrary(wm);
1152 SetLastError(ERROR_DLL_INIT_FAILED);
1153 wm = NULL;
1157 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1159 return wm ? wm->module : 0;
1162 /***********************************************************************
1163 * MODULE_LoadLibraryExA (internal)
1165 * Load a PE style module according to the load order.
1167 * The HFILE parameter is not used and marked reserved in the SDK. I can
1168 * only guess that it should force a file to be mapped, but I rather
1169 * ignore the parameter because it would be extremely difficult to
1170 * integrate this with different types of module represenations.
1173 WINE_MODREF *MODULE_LoadLibraryExA( LPCSTR libname, HFILE hfile, DWORD flags )
1175 DWORD err = GetLastError();
1176 WINE_MODREF *pwm;
1177 int i;
1178 module_loadorder_t *plo;
1180 EnterCriticalSection(&PROCESS_Current()->crit_section);
1182 /* Check for already loaded module */
1183 if((pwm = MODULE_FindModule(libname)))
1185 if(!(pwm->flags & WINE_MODREF_MARKER))
1186 pwm->refCount++;
1187 TRACE("Already loaded module '%s' at 0x%08x, count=%d, \n", libname, pwm->module, pwm->refCount);
1188 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1189 return pwm;
1192 plo = MODULE_GetLoadOrder(libname);
1194 for(i = 0; i < MODULE_LOADORDER_NTYPES; i++)
1196 SetLastError( ERROR_FILE_NOT_FOUND );
1197 switch(plo->loadorder[i])
1199 case MODULE_LOADORDER_DLL:
1200 TRACE("Trying native dll '%s'\n", libname);
1201 pwm = PE_LoadLibraryExA(libname, flags);
1202 break;
1204 case MODULE_LOADORDER_ELFDLL:
1205 TRACE("Trying elfdll '%s'\n", libname);
1206 if (!(pwm = BUILTIN32_LoadLibraryExA(libname, flags)))
1207 pwm = ELFDLL_LoadLibraryExA(libname, flags);
1208 break;
1210 case MODULE_LOADORDER_SO:
1211 TRACE("Trying so-library '%s'\n", libname);
1212 if (!(pwm = BUILTIN32_LoadLibraryExA(libname, flags)))
1213 pwm = ELF_LoadLibraryExA(libname, flags);
1214 break;
1216 case MODULE_LOADORDER_BI:
1217 TRACE("Trying built-in '%s'\n", libname);
1218 pwm = BUILTIN32_LoadLibraryExA(libname, flags);
1219 break;
1221 default:
1222 ERR("Got invalid loadorder type %d (%s index %d)\n", plo->loadorder[i], plo->modulename, i);
1223 /* Fall through */
1225 case MODULE_LOADORDER_INVALID: /* We ignore this as it is an empty entry */
1226 pwm = NULL;
1227 break;
1230 if(pwm)
1232 /* Initialize DLL just loaded */
1233 TRACE("Loaded module '%s' at 0x%08x, \n", libname, pwm->module);
1235 /* Set the refCount here so that an attach failure will */
1236 /* decrement the dependencies through the MODULE_FreeLibrary call. */
1237 pwm->refCount++;
1239 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1240 SetLastError( err ); /* restore last error */
1241 return pwm;
1244 if(GetLastError() != ERROR_FILE_NOT_FOUND)
1245 break;
1248 WARN("Failed to load module '%s'; error=0x%08lx, \n", libname, GetLastError());
1249 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1250 return NULL;
1253 /***********************************************************************
1254 * LoadLibraryA (KERNEL32)
1256 HMODULE WINAPI LoadLibraryA(LPCSTR libname) {
1257 return LoadLibraryExA(libname,0,0);
1260 /***********************************************************************
1261 * LoadLibraryW (KERNEL32)
1263 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
1265 return LoadLibraryExW(libnameW,0,0);
1268 /***********************************************************************
1269 * LoadLibrary32_16 (KERNEL.452)
1271 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
1273 HMODULE hModule;
1275 SYSLEVEL_ReleaseWin16Lock();
1276 hModule = LoadLibraryA( libname );
1277 SYSLEVEL_RestoreWin16Lock();
1279 return hModule;
1282 /***********************************************************************
1283 * LoadLibraryExW (KERNEL32)
1285 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW,HANDLE hfile,DWORD flags)
1287 LPSTR libnameA = HEAP_strdupWtoA( GetProcessHeap(), 0, libnameW );
1288 HMODULE ret = LoadLibraryExA( libnameA , hfile, flags );
1290 HeapFree( GetProcessHeap(), 0, libnameA );
1291 return ret;
1294 /***********************************************************************
1295 * MODULE_FlushModrefs
1297 * NOTE: Assumes that the process critical section is held!
1299 * Remove all unused modrefs and call the internal unloading routines
1300 * for the library type.
1302 static void MODULE_FlushModrefs(void)
1304 WINE_MODREF *wm, *next;
1306 for(wm = PROCESS_Current()->modref_list; wm; wm = next)
1308 next = wm->next;
1310 if(wm->refCount)
1311 continue;
1313 /* Unlink this modref from the chain */
1314 if(wm->next)
1315 wm->next->prev = wm->prev;
1316 if(wm->prev)
1317 wm->prev->next = wm->next;
1318 if(wm == PROCESS_Current()->modref_list)
1319 PROCESS_Current()->modref_list = wm->next;
1322 * The unloaders are also responsible for freeing the modref itself
1323 * because the loaders were responsible for allocating it.
1325 switch(wm->type)
1327 case MODULE32_PE: if ( !(wm->flags & WINE_MODREF_INTERNAL) )
1328 PE_UnloadLibrary(wm);
1329 else
1330 BUILTIN32_UnloadLibrary(wm);
1331 break;
1332 case MODULE32_ELF: ELF_UnloadLibrary(wm); break;
1333 case MODULE32_ELFDLL: ELFDLL_UnloadLibrary(wm); break;
1335 default:
1336 ERR("Invalid or unhandled MODREF type %d encountered (wm=%p)\n", wm->type, wm);
1341 /***********************************************************************
1342 * FreeLibrary
1344 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
1346 BOOL retv = FALSE;
1347 WINE_MODREF *wm;
1349 EnterCriticalSection( &PROCESS_Current()->crit_section );
1350 PROCESS_Current()->free_lib_count++;
1352 wm = MODULE32_LookupHMODULE( hLibModule );
1353 if ( !wm || !hLibModule )
1354 SetLastError( ERROR_INVALID_HANDLE );
1355 else
1356 retv = MODULE_FreeLibrary( wm );
1358 PROCESS_Current()->free_lib_count--;
1359 LeaveCriticalSection( &PROCESS_Current()->crit_section );
1361 return retv;
1364 /***********************************************************************
1365 * MODULE_DecRefCount
1367 * NOTE: Assumes that the process critical section is held!
1369 static void MODULE_DecRefCount( WINE_MODREF *wm )
1371 int i;
1373 if ( wm->flags & WINE_MODREF_MARKER )
1374 return;
1376 if ( wm->refCount <= 0 )
1377 return;
1379 --wm->refCount;
1380 TRACE("(%s) refCount: %d\n", wm->modname, wm->refCount );
1382 if ( wm->refCount == 0 )
1384 wm->flags |= WINE_MODREF_MARKER;
1386 for ( i = 0; i < wm->nDeps; i++ )
1387 if ( wm->deps[i] )
1388 MODULE_DecRefCount( wm->deps[i] );
1390 wm->flags &= ~WINE_MODREF_MARKER;
1394 /***********************************************************************
1395 * MODULE_FreeLibrary
1397 * NOTE: Assumes that the process critical section is held!
1399 BOOL MODULE_FreeLibrary( WINE_MODREF *wm )
1401 TRACE("(%s) - START\n", wm->modname );
1403 /* Recursively decrement reference counts */
1404 MODULE_DecRefCount( wm );
1406 /* Call process detach notifications */
1407 if ( PROCESS_Current()->free_lib_count <= 1 )
1409 struct unload_dll_request *req = get_req_buffer();
1411 MODULE_DllProcessDetach( FALSE, NULL );
1412 req->base = (void *)wm->module;
1413 server_call_noerr( REQ_UNLOAD_DLL );
1415 MODULE_FlushModrefs();
1418 TRACE("END\n");
1420 return TRUE;
1424 /***********************************************************************
1425 * FreeLibraryAndExitThread
1427 VOID WINAPI FreeLibraryAndExitThread(HINSTANCE hLibModule, DWORD dwExitCode)
1429 FreeLibrary(hLibModule);
1430 ExitThread(dwExitCode);
1433 /***********************************************************************
1434 * PrivateLoadLibrary (KERNEL32)
1436 * FIXME: rough guesswork, don't know what "Private" means
1438 HINSTANCE WINAPI PrivateLoadLibrary(LPCSTR libname)
1440 return (HINSTANCE)LoadLibrary16(libname);
1445 /***********************************************************************
1446 * PrivateFreeLibrary (KERNEL32)
1448 * FIXME: rough guesswork, don't know what "Private" means
1450 void WINAPI PrivateFreeLibrary(HINSTANCE handle)
1452 FreeLibrary16((HINSTANCE16)handle);
1456 /***********************************************************************
1457 * WIN32_GetProcAddress16 (KERNEL32.36)
1458 * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
1460 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
1462 WORD ordinal;
1463 FARPROC16 ret;
1465 if (!hModule) {
1466 WARN("hModule may not be 0!\n");
1467 return (FARPROC16)0;
1469 if (HIWORD(hModule))
1471 WARN("hModule is Win32 handle (%08x)\n", hModule );
1472 return (FARPROC16)0;
1474 hModule = GetExePtr( hModule );
1475 if (HIWORD(name)) {
1476 ordinal = NE_GetOrdinal( hModule, name );
1477 TRACE("%04x '%s'\n", hModule, name );
1478 } else {
1479 ordinal = LOWORD(name);
1480 TRACE("%04x %04x\n", hModule, ordinal );
1482 if (!ordinal) return (FARPROC16)0;
1483 ret = NE_GetEntryPoint( hModule, ordinal );
1484 TRACE("returning %08x\n",(UINT)ret);
1485 return ret;
1488 /***********************************************************************
1489 * GetProcAddress16 (KERNEL.50)
1491 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, SEGPTR name )
1493 WORD ordinal;
1494 FARPROC16 ret;
1496 if (!hModule) hModule = GetCurrentTask();
1497 hModule = GetExePtr( hModule );
1499 if (HIWORD(name) != 0)
1501 ordinal = NE_GetOrdinal( hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1502 TRACE("%04x '%s'\n", hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1504 else
1506 ordinal = LOWORD(name);
1507 TRACE("%04x %04x\n", hModule, ordinal );
1509 if (!ordinal) return (FARPROC16)0;
1511 ret = NE_GetEntryPoint( hModule, ordinal );
1513 TRACE("returning %08x\n", (UINT)ret );
1514 return ret;
1518 /***********************************************************************
1519 * GetProcAddress (KERNEL32.257)
1521 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1523 return MODULE_GetProcAddress( hModule, function, TRUE );
1526 /***********************************************************************
1527 * GetProcAddress32 (KERNEL.453)
1529 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
1531 return MODULE_GetProcAddress( hModule, function, FALSE );
1534 /***********************************************************************
1535 * MODULE_GetProcAddress (internal)
1537 FARPROC MODULE_GetProcAddress(
1538 HMODULE hModule, /* [in] current module handle */
1539 LPCSTR function, /* [in] function to be looked up */
1540 BOOL snoop )
1542 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1543 FARPROC retproc;
1545 if (HIWORD(function))
1546 TRACE_(win32)("(%08lx,%s)\n",(DWORD)hModule,function);
1547 else
1548 TRACE_(win32)("(%08lx,%p)\n",(DWORD)hModule,function);
1549 if (!wm) {
1550 SetLastError(ERROR_INVALID_HANDLE);
1551 return (FARPROC)0;
1553 switch (wm->type)
1555 case MODULE32_PE:
1556 retproc = PE_FindExportedFunction( wm, function, snoop );
1557 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1558 return retproc;
1559 case MODULE32_ELF:
1560 retproc = ELF_FindExportedFunction( wm, function);
1561 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1562 return retproc;
1563 default:
1564 ERR("wine_modref type %d not handled.\n",wm->type);
1565 SetLastError(ERROR_INVALID_HANDLE);
1566 return (FARPROC)0;
1571 /***********************************************************************
1572 * RtlImageNtHeader (NTDLL)
1574 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
1576 /* basically:
1577 * return hModule+(((IMAGE_DOS_HEADER*)hModule)->e_lfanew);
1578 * but we could get HMODULE16 or the like (think builtin modules)
1581 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1582 if (!wm || (wm->type != MODULE32_PE)) return (PIMAGE_NT_HEADERS)0;
1583 return PE_HEADER(wm->module);
1587 /***************************************************************************
1588 * HasGPHandler (KERNEL.338)
1591 #include "pshpack1.h"
1592 typedef struct _GPHANDLERDEF
1594 WORD selector;
1595 WORD rangeStart;
1596 WORD rangeEnd;
1597 WORD handler;
1598 } GPHANDLERDEF;
1599 #include "poppack.h"
1601 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1603 HMODULE16 hModule;
1604 int gpOrdinal;
1605 SEGPTR gpPtr;
1606 GPHANDLERDEF *gpHandler;
1608 if ( (hModule = FarGetOwner16( SELECTOROF(address) )) != 0
1609 && (gpOrdinal = NE_GetOrdinal( hModule, "__GP" )) != 0
1610 && (gpPtr = (SEGPTR)NE_GetEntryPointEx( hModule, gpOrdinal, FALSE )) != 0
1611 && !IsBadReadPtr16( gpPtr, sizeof(GPHANDLERDEF) )
1612 && (gpHandler = PTR_SEG_TO_LIN( gpPtr )) != NULL )
1614 while (gpHandler->selector)
1616 if ( SELECTOROF(address) == gpHandler->selector
1617 && OFFSETOF(address) >= gpHandler->rangeStart
1618 && OFFSETOF(address) < gpHandler->rangeEnd )
1619 return PTR_SEG_OFF_TO_SEGPTR( gpHandler->selector,
1620 gpHandler->handler );
1621 gpHandler++;
1625 return 0;