Replaced calls to HEADER_Refresh with InvalidateRect.
[wine.git] / loader / module.c
blob0b324ba2a0e14b411d6f5233143d1482a73c0bc0
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, 0,
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;
727 memset( &startup, 0, sizeof(startup) );
728 startup.cb = sizeof(startup);
729 startup.dwFlags = STARTF_USESHOWWINDOW;
730 startup.wShowWindow = nCmdShow;
732 if (CreateProcessA( NULL, (LPSTR)lpCmdLine, NULL, NULL, FALSE,
733 0, NULL, NULL, &startup, &info ))
735 /* Give 30 seconds to the app to come up */
736 if (Callout.WaitForInputIdle ( info.hProcess, 30000 ) == 0xFFFFFFFF)
737 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
738 hInstance = 33;
739 /* Close off the handles */
740 CloseHandle( info.hThread );
741 CloseHandle( info.hProcess );
743 else if ((hInstance = GetLastError()) >= 32)
745 FIXME("Strange error set by CreateProcess: %d\n", hInstance );
746 hInstance = 11;
749 return hInstance;
752 /**********************************************************************
753 * LoadModule (KERNEL32.499)
755 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
757 LOADPARAMS *params = (LOADPARAMS *)paramBlock;
758 PROCESS_INFORMATION info;
759 STARTUPINFOA startup;
760 HINSTANCE hInstance;
761 LPSTR cmdline, p;
762 char filename[MAX_PATH];
763 BYTE len;
765 if (!name) return ERROR_FILE_NOT_FOUND;
767 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
768 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
769 return GetLastError();
771 len = (BYTE)params->lpCmdLine[0];
772 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
773 return ERROR_NOT_ENOUGH_MEMORY;
775 strcpy( cmdline, filename );
776 p = cmdline + strlen(cmdline);
777 *p++ = ' ';
778 memcpy( p, params->lpCmdLine + 1, len );
779 p[len] = 0;
781 memset( &startup, 0, sizeof(startup) );
782 startup.cb = sizeof(startup);
783 if (params->lpCmdShow)
785 startup.dwFlags = STARTF_USESHOWWINDOW;
786 startup.wShowWindow = params->lpCmdShow[1];
789 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
790 params->lpEnvAddress, NULL, &startup, &info ))
792 /* Give 30 seconds to the app to come up */
793 if ( Callout.WaitForInputIdle ( info.hProcess, 30000 ) == 0xFFFFFFFF )
794 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
795 hInstance = 33;
796 /* Close off the handles */
797 CloseHandle( info.hThread );
798 CloseHandle( info.hProcess );
800 else if ((hInstance = GetLastError()) >= 32)
802 FIXME("Strange error set by CreateProcess: %d\n", hInstance );
803 hInstance = 11;
806 HeapFree( GetProcessHeap(), 0, cmdline );
807 return hInstance;
811 /*************************************************************************
812 * get_file_name
814 * Helper for CreateProcess: retrieve the file name to load from the
815 * app name and command line. Store the file name in buffer, and
816 * return a possibly modified command line.
818 static LPSTR get_file_name( LPCSTR appname, LPSTR cmdline, LPSTR buffer, int buflen )
820 char *name, *pos, *ret = NULL;
821 const char *p;
823 /* if we have an app name, everything is easy */
825 if (appname)
827 /* use the unmodified app name as file name */
828 lstrcpynA( buffer, appname, buflen );
829 if (!(ret = cmdline))
831 /* no command-line, create one */
832 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(appname) + 3 )))
833 sprintf( ret, "\"%s\"", appname );
835 return ret;
838 if (!cmdline)
840 SetLastError( ERROR_INVALID_PARAMETER );
841 return NULL;
844 /* first check for a quoted file name */
846 if ((cmdline[0] == '"') && ((p = strchr( cmdline + 1, '"' ))))
848 int len = p - cmdline - 1;
849 /* extract the quoted portion as file name */
850 if (!(name = HeapAlloc( GetProcessHeap(), 0, len + 1 ))) return NULL;
851 memcpy( name, cmdline + 1, len );
852 name[len] = 0;
854 if (SearchPathA( NULL, name, ".exe", buflen, buffer, NULL ) ||
855 SearchPathA( NULL, name, NULL, buflen, buffer, NULL ))
856 ret = cmdline; /* no change necessary */
857 goto done;
860 /* now try the command-line word by word */
862 if (!(name = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 1 ))) return NULL;
863 pos = name;
864 p = cmdline;
866 while (*p)
868 do *pos++ = *p++; while (*p && *p != ' ');
869 *pos = 0;
870 TRACE("trying '%s'\n", name );
871 if (SearchPathA( NULL, name, ".exe", buflen, buffer, NULL ) ||
872 SearchPathA( NULL, name, NULL, buflen, buffer, NULL ))
874 ret = cmdline;
875 break;
879 if (!ret || !strchr( name, ' ' )) goto done; /* no change necessary */
881 /* now build a new command-line with quotes */
883 if (!(ret = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 3 ))) goto done;
884 sprintf( ret, "\"%s\"%s", name, p );
886 done:
887 HeapFree( GetProcessHeap(), 0, name );
888 return ret;
892 /**********************************************************************
893 * CreateProcessA (KERNEL32.171)
895 BOOL WINAPI CreateProcessA( LPCSTR lpApplicationName, LPSTR lpCommandLine,
896 LPSECURITY_ATTRIBUTES lpProcessAttributes,
897 LPSECURITY_ATTRIBUTES lpThreadAttributes,
898 BOOL bInheritHandles, DWORD dwCreationFlags,
899 LPVOID lpEnvironment, LPCSTR lpCurrentDirectory,
900 LPSTARTUPINFOA lpStartupInfo,
901 LPPROCESS_INFORMATION lpProcessInfo )
903 BOOL retv = FALSE;
904 HANDLE hFile;
905 DWORD type;
906 char name[MAX_PATH];
907 LPSTR tidy_cmdline;
909 /* Process the AppName and/or CmdLine to get module name and path */
911 TRACE("app '%s' cmdline '%s'\n", lpApplicationName, lpCommandLine );
913 if (!(tidy_cmdline = get_file_name( lpApplicationName, lpCommandLine, name, sizeof(name) )))
914 return FALSE;
916 /* Warn if unsupported features are used */
918 if (dwCreationFlags & DETACHED_PROCESS)
919 FIXME("(%s,...): DETACHED_PROCESS ignored\n", name);
920 if (dwCreationFlags & CREATE_NEW_CONSOLE)
921 FIXME("(%s,...): CREATE_NEW_CONSOLE ignored\n", name);
922 if (dwCreationFlags & NORMAL_PRIORITY_CLASS)
923 FIXME("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
924 if (dwCreationFlags & IDLE_PRIORITY_CLASS)
925 FIXME("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
926 if (dwCreationFlags & HIGH_PRIORITY_CLASS)
927 FIXME("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
928 if (dwCreationFlags & REALTIME_PRIORITY_CLASS)
929 FIXME("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
930 if (dwCreationFlags & CREATE_NEW_PROCESS_GROUP)
931 FIXME("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
932 if (dwCreationFlags & CREATE_UNICODE_ENVIRONMENT)
933 FIXME("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
934 if (dwCreationFlags & CREATE_SEPARATE_WOW_VDM)
935 FIXME("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
936 if (dwCreationFlags & CREATE_SHARED_WOW_VDM)
937 FIXME("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
938 if (dwCreationFlags & CREATE_DEFAULT_ERROR_MODE)
939 FIXME("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
940 if (dwCreationFlags & CREATE_NO_WINDOW)
941 FIXME("(%s,...): CREATE_NO_WINDOW ignored\n", name);
942 if (dwCreationFlags & PROFILE_USER)
943 FIXME("(%s,...): PROFILE_USER ignored\n", name);
944 if (dwCreationFlags & PROFILE_KERNEL)
945 FIXME("(%s,...): PROFILE_KERNEL ignored\n", name);
946 if (dwCreationFlags & PROFILE_SERVER)
947 FIXME("(%s,...): PROFILE_SERVER ignored\n", name);
948 if (lpCurrentDirectory)
949 FIXME("(%s,...): lpCurrentDirectory %s ignored\n",
950 name, lpCurrentDirectory);
951 if (lpStartupInfo->lpDesktop)
952 FIXME("(%s,...): lpStartupInfo->lpDesktop %s ignored\n",
953 name, lpStartupInfo->lpDesktop);
954 if (lpStartupInfo->lpTitle)
955 FIXME("(%s,...): lpStartupInfo->lpTitle %s ignored\n",
956 name, lpStartupInfo->lpTitle);
957 if (lpStartupInfo->dwFlags & STARTF_USECOUNTCHARS)
958 FIXME("(%s,...): STARTF_USECOUNTCHARS (%ld,%ld) ignored\n",
959 name, lpStartupInfo->dwXCountChars, lpStartupInfo->dwYCountChars);
960 if (lpStartupInfo->dwFlags & STARTF_USEFILLATTRIBUTE)
961 FIXME("(%s,...): STARTF_USEFILLATTRIBUTE %lx ignored\n",
962 name, lpStartupInfo->dwFillAttribute);
963 if (lpStartupInfo->dwFlags & STARTF_RUNFULLSCREEN)
964 FIXME("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
965 if (lpStartupInfo->dwFlags & STARTF_FORCEONFEEDBACK)
966 FIXME("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
967 if (lpStartupInfo->dwFlags & STARTF_FORCEOFFFEEDBACK)
968 FIXME("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
969 if (lpStartupInfo->dwFlags & STARTF_USEHOTKEY)
970 FIXME("(%s,...): STARTF_USEHOTKEY ignored\n", name);
972 /* Open file and determine executable type */
974 hFile = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, -1 );
975 if (hFile == INVALID_HANDLE_VALUE) goto done;
977 if ( !MODULE_GetBinaryType( hFile, name, &type ) )
979 CloseHandle( hFile );
980 retv = PROCESS_Create( -1, name, tidy_cmdline, lpEnvironment,
981 lpProcessAttributes, lpThreadAttributes,
982 bInheritHandles, dwCreationFlags,
983 lpStartupInfo, lpProcessInfo );
984 goto done;
987 /* Create process */
989 switch ( type )
991 case SCS_32BIT_BINARY:
992 case SCS_WOW_BINARY:
993 case SCS_DOS_BINARY:
994 retv = PROCESS_Create( hFile, name, tidy_cmdline, lpEnvironment,
995 lpProcessAttributes, lpThreadAttributes,
996 bInheritHandles, dwCreationFlags,
997 lpStartupInfo, lpProcessInfo );
998 break;
1000 case SCS_PIF_BINARY:
1001 case SCS_POSIX_BINARY:
1002 case SCS_OS216_BINARY:
1003 FIXME("Unsupported executable type: %ld\n", type );
1004 /* fall through */
1006 default:
1007 SetLastError( ERROR_BAD_FORMAT );
1008 break;
1010 CloseHandle( hFile );
1012 done:
1013 if (tidy_cmdline != lpCommandLine) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1014 return retv;
1017 /**********************************************************************
1018 * CreateProcessW (KERNEL32.172)
1019 * NOTES
1020 * lpReserved is not converted
1022 BOOL WINAPI CreateProcessW( LPCWSTR lpApplicationName, LPWSTR lpCommandLine,
1023 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1024 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1025 BOOL bInheritHandles, DWORD dwCreationFlags,
1026 LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory,
1027 LPSTARTUPINFOW lpStartupInfo,
1028 LPPROCESS_INFORMATION lpProcessInfo )
1029 { BOOL ret;
1030 STARTUPINFOA StartupInfoA;
1032 LPSTR lpApplicationNameA = HEAP_strdupWtoA (GetProcessHeap(),0,lpApplicationName);
1033 LPSTR lpCommandLineA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCommandLine);
1034 LPSTR lpCurrentDirectoryA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCurrentDirectory);
1036 memcpy (&StartupInfoA, lpStartupInfo, sizeof(STARTUPINFOA));
1037 StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpDesktop);
1038 StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpTitle);
1040 TRACE_(win32)("(%s,%s,...)\n", debugstr_w(lpApplicationName), debugstr_w(lpCommandLine));
1042 if (lpStartupInfo->lpReserved)
1043 FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n", debugstr_w(lpStartupInfo->lpReserved));
1045 ret = CreateProcessA( lpApplicationNameA, lpCommandLineA,
1046 lpProcessAttributes, lpThreadAttributes,
1047 bInheritHandles, dwCreationFlags,
1048 lpEnvironment, lpCurrentDirectoryA,
1049 &StartupInfoA, lpProcessInfo );
1051 HeapFree( GetProcessHeap(), 0, lpCurrentDirectoryA );
1052 HeapFree( GetProcessHeap(), 0, lpCommandLineA );
1053 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1054 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1056 return ret;
1059 /***********************************************************************
1060 * GetModuleHandleA (KERNEL32.237)
1062 HMODULE WINAPI GetModuleHandleA(LPCSTR module)
1064 WINE_MODREF *wm;
1066 if ( module == NULL )
1067 wm = PROCESS_Current()->exe_modref;
1068 else
1069 wm = MODULE_FindModule( module );
1071 return wm? wm->module : 0;
1074 /***********************************************************************
1075 * GetModuleHandleW
1077 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
1079 HMODULE hModule;
1080 LPSTR modulea = HEAP_strdupWtoA( GetProcessHeap(), 0, module );
1081 hModule = GetModuleHandleA( modulea );
1082 HeapFree( GetProcessHeap(), 0, modulea );
1083 return hModule;
1087 /***********************************************************************
1088 * GetModuleFileNameA (KERNEL32.235)
1090 * GetModuleFileNameA seems to *always* return the long path;
1091 * it's only GetModuleFileName16 that decides between short/long path
1092 * by checking if exe version >= 4.0.
1093 * (SDK docu doesn't mention this)
1095 DWORD WINAPI GetModuleFileNameA(
1096 HMODULE hModule, /* [in] module handle (32bit) */
1097 LPSTR lpFileName, /* [out] filenamebuffer */
1098 DWORD size /* [in] size of filenamebuffer */
1099 ) {
1100 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1102 if (!wm) /* can happen on start up or the like */
1103 return 0;
1105 lstrcpynA( lpFileName, wm->filename, size );
1107 TRACE("%s\n", lpFileName );
1108 return strlen(lpFileName);
1112 /***********************************************************************
1113 * GetModuleFileNameW (KERNEL32.236)
1115 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName,
1116 DWORD size )
1118 LPSTR fnA = (char*)HeapAlloc( GetProcessHeap(), 0, size );
1119 DWORD res = GetModuleFileNameA( hModule, fnA, size );
1120 lstrcpynAtoW( lpFileName, fnA, size );
1121 HeapFree( GetProcessHeap(), 0, fnA );
1122 return res;
1126 /***********************************************************************
1127 * LoadLibraryExA (KERNEL32)
1129 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
1131 WINE_MODREF *wm;
1133 if(!libname)
1135 SetLastError(ERROR_INVALID_PARAMETER);
1136 return 0;
1139 EnterCriticalSection(&PROCESS_Current()->crit_section);
1141 wm = MODULE_LoadLibraryExA( libname, hfile, flags );
1142 if ( wm )
1144 if ( !MODULE_DllProcessAttach( wm, NULL ) )
1146 WARN_(module)("Attach failed for module '%s', \n", libname);
1147 MODULE_FreeLibrary(wm);
1148 SetLastError(ERROR_DLL_INIT_FAILED);
1149 wm = NULL;
1153 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1155 return wm ? wm->module : 0;
1158 /***********************************************************************
1159 * MODULE_LoadLibraryExA (internal)
1161 * Load a PE style module according to the load order.
1163 * The HFILE parameter is not used and marked reserved in the SDK. I can
1164 * only guess that it should force a file to be mapped, but I rather
1165 * ignore the parameter because it would be extremely difficult to
1166 * integrate this with different types of module represenations.
1169 WINE_MODREF *MODULE_LoadLibraryExA( LPCSTR libname, HFILE hfile, DWORD flags )
1171 DWORD err = GetLastError();
1172 WINE_MODREF *pwm;
1173 int i;
1174 module_loadorder_t *plo;
1176 EnterCriticalSection(&PROCESS_Current()->crit_section);
1178 /* Check for already loaded module */
1179 if((pwm = MODULE_FindModule(libname)))
1181 if(!(pwm->flags & WINE_MODREF_MARKER))
1182 pwm->refCount++;
1183 TRACE("Already loaded module '%s' at 0x%08x, count=%d, \n", libname, pwm->module, pwm->refCount);
1184 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1185 return pwm;
1188 plo = MODULE_GetLoadOrder(libname);
1190 for(i = 0; i < MODULE_LOADORDER_NTYPES; i++)
1192 SetLastError( ERROR_FILE_NOT_FOUND );
1193 switch(plo->loadorder[i])
1195 case MODULE_LOADORDER_DLL:
1196 TRACE("Trying native dll '%s'\n", libname);
1197 pwm = PE_LoadLibraryExA(libname, flags);
1198 break;
1200 case MODULE_LOADORDER_ELFDLL:
1201 TRACE("Trying elfdll '%s'\n", libname);
1202 if (!(pwm = BUILTIN32_LoadLibraryExA(libname, flags)))
1203 pwm = ELFDLL_LoadLibraryExA(libname, flags);
1204 break;
1206 case MODULE_LOADORDER_SO:
1207 TRACE("Trying so-library '%s'\n", libname);
1208 if (!(pwm = BUILTIN32_LoadLibraryExA(libname, flags)))
1209 pwm = ELF_LoadLibraryExA(libname, flags);
1210 break;
1212 case MODULE_LOADORDER_BI:
1213 TRACE("Trying built-in '%s'\n", libname);
1214 pwm = BUILTIN32_LoadLibraryExA(libname, flags);
1215 break;
1217 default:
1218 ERR("Got invalid loadorder type %d (%s index %d)\n", plo->loadorder[i], plo->modulename, i);
1219 /* Fall through */
1221 case MODULE_LOADORDER_INVALID: /* We ignore this as it is an empty entry */
1222 pwm = NULL;
1223 break;
1226 if(pwm)
1228 /* Initialize DLL just loaded */
1229 TRACE("Loaded module '%s' at 0x%08x, \n", libname, pwm->module);
1231 /* Set the refCount here so that an attach failure will */
1232 /* decrement the dependencies through the MODULE_FreeLibrary call. */
1233 pwm->refCount++;
1235 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1236 SetLastError( err ); /* restore last error */
1237 return pwm;
1240 if(GetLastError() != ERROR_FILE_NOT_FOUND)
1241 break;
1244 WARN("Failed to load module '%s'; error=0x%08lx, \n", libname, GetLastError());
1245 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1246 return NULL;
1249 /***********************************************************************
1250 * LoadLibraryA (KERNEL32)
1252 HMODULE WINAPI LoadLibraryA(LPCSTR libname) {
1253 return LoadLibraryExA(libname,0,0);
1256 /***********************************************************************
1257 * LoadLibraryW (KERNEL32)
1259 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
1261 return LoadLibraryExW(libnameW,0,0);
1264 /***********************************************************************
1265 * LoadLibrary32_16 (KERNEL.452)
1267 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
1269 HMODULE hModule;
1271 SYSLEVEL_ReleaseWin16Lock();
1272 hModule = LoadLibraryA( libname );
1273 SYSLEVEL_RestoreWin16Lock();
1275 return hModule;
1278 /***********************************************************************
1279 * LoadLibraryExW (KERNEL32)
1281 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW,HANDLE hfile,DWORD flags)
1283 LPSTR libnameA = HEAP_strdupWtoA( GetProcessHeap(), 0, libnameW );
1284 HMODULE ret = LoadLibraryExA( libnameA , hfile, flags );
1286 HeapFree( GetProcessHeap(), 0, libnameA );
1287 return ret;
1290 /***********************************************************************
1291 * MODULE_FlushModrefs
1293 * NOTE: Assumes that the process critical section is held!
1295 * Remove all unused modrefs and call the internal unloading routines
1296 * for the library type.
1298 static void MODULE_FlushModrefs(void)
1300 WINE_MODREF *wm, *next;
1302 for(wm = PROCESS_Current()->modref_list; wm; wm = next)
1304 next = wm->next;
1306 if(wm->refCount)
1307 continue;
1309 /* Unlink this modref from the chain */
1310 if(wm->next)
1311 wm->next->prev = wm->prev;
1312 if(wm->prev)
1313 wm->prev->next = wm->next;
1314 if(wm == PROCESS_Current()->modref_list)
1315 PROCESS_Current()->modref_list = wm->next;
1318 * The unloaders are also responsible for freeing the modref itself
1319 * because the loaders were responsible for allocating it.
1321 switch(wm->type)
1323 case MODULE32_PE: if ( !(wm->flags & WINE_MODREF_INTERNAL) )
1324 PE_UnloadLibrary(wm);
1325 else
1326 BUILTIN32_UnloadLibrary(wm);
1327 break;
1328 case MODULE32_ELF: ELF_UnloadLibrary(wm); break;
1329 case MODULE32_ELFDLL: ELFDLL_UnloadLibrary(wm); break;
1331 default:
1332 ERR("Invalid or unhandled MODREF type %d encountered (wm=%p)\n", wm->type, wm);
1337 /***********************************************************************
1338 * FreeLibrary
1340 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
1342 BOOL retv = FALSE;
1343 WINE_MODREF *wm;
1345 EnterCriticalSection( &PROCESS_Current()->crit_section );
1346 PROCESS_Current()->free_lib_count++;
1348 wm = MODULE32_LookupHMODULE( hLibModule );
1349 if ( !wm || !hLibModule )
1350 SetLastError( ERROR_INVALID_HANDLE );
1351 else
1352 retv = MODULE_FreeLibrary( wm );
1354 PROCESS_Current()->free_lib_count--;
1355 LeaveCriticalSection( &PROCESS_Current()->crit_section );
1357 return retv;
1360 /***********************************************************************
1361 * MODULE_DecRefCount
1363 * NOTE: Assumes that the process critical section is held!
1365 static void MODULE_DecRefCount( WINE_MODREF *wm )
1367 int i;
1369 if ( wm->flags & WINE_MODREF_MARKER )
1370 return;
1372 if ( wm->refCount <= 0 )
1373 return;
1375 --wm->refCount;
1376 TRACE("(%s) refCount: %d\n", wm->modname, wm->refCount );
1378 if ( wm->refCount == 0 )
1380 wm->flags |= WINE_MODREF_MARKER;
1382 for ( i = 0; i < wm->nDeps; i++ )
1383 if ( wm->deps[i] )
1384 MODULE_DecRefCount( wm->deps[i] );
1386 wm->flags &= ~WINE_MODREF_MARKER;
1390 /***********************************************************************
1391 * MODULE_FreeLibrary
1393 * NOTE: Assumes that the process critical section is held!
1395 BOOL MODULE_FreeLibrary( WINE_MODREF *wm )
1397 TRACE("(%s) - START\n", wm->modname );
1399 /* Recursively decrement reference counts */
1400 MODULE_DecRefCount( wm );
1402 /* Call process detach notifications */
1403 if ( PROCESS_Current()->free_lib_count <= 1 )
1405 struct unload_dll_request *req = get_req_buffer();
1407 MODULE_DllProcessDetach( FALSE, NULL );
1408 req->base = (void *)wm->module;
1409 server_call_noerr( REQ_UNLOAD_DLL );
1411 MODULE_FlushModrefs();
1414 TRACE("END\n");
1416 return TRUE;
1420 /***********************************************************************
1421 * FreeLibraryAndExitThread
1423 VOID WINAPI FreeLibraryAndExitThread(HINSTANCE hLibModule, DWORD dwExitCode)
1425 FreeLibrary(hLibModule);
1426 ExitThread(dwExitCode);
1429 /***********************************************************************
1430 * PrivateLoadLibrary (KERNEL32)
1432 * FIXME: rough guesswork, don't know what "Private" means
1434 HINSTANCE WINAPI PrivateLoadLibrary(LPCSTR libname)
1436 return (HINSTANCE)LoadLibrary16(libname);
1441 /***********************************************************************
1442 * PrivateFreeLibrary (KERNEL32)
1444 * FIXME: rough guesswork, don't know what "Private" means
1446 void WINAPI PrivateFreeLibrary(HINSTANCE handle)
1448 FreeLibrary16((HINSTANCE16)handle);
1452 /***********************************************************************
1453 * WIN32_GetProcAddress16 (KERNEL32.36)
1454 * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
1456 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
1458 WORD ordinal;
1459 FARPROC16 ret;
1461 if (!hModule) {
1462 WARN("hModule may not be 0!\n");
1463 return (FARPROC16)0;
1465 if (HIWORD(hModule))
1467 WARN("hModule is Win32 handle (%08x)\n", hModule );
1468 return (FARPROC16)0;
1470 hModule = GetExePtr( hModule );
1471 if (HIWORD(name)) {
1472 ordinal = NE_GetOrdinal( hModule, name );
1473 TRACE("%04x '%s'\n", hModule, name );
1474 } else {
1475 ordinal = LOWORD(name);
1476 TRACE("%04x %04x\n", hModule, ordinal );
1478 if (!ordinal) return (FARPROC16)0;
1479 ret = NE_GetEntryPoint( hModule, ordinal );
1480 TRACE("returning %08x\n",(UINT)ret);
1481 return ret;
1484 /***********************************************************************
1485 * GetProcAddress16 (KERNEL.50)
1487 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, SEGPTR name )
1489 WORD ordinal;
1490 FARPROC16 ret;
1492 if (!hModule) hModule = GetCurrentTask();
1493 hModule = GetExePtr( hModule );
1495 if (HIWORD(name) != 0)
1497 ordinal = NE_GetOrdinal( hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1498 TRACE("%04x '%s'\n", hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1500 else
1502 ordinal = LOWORD(name);
1503 TRACE("%04x %04x\n", hModule, ordinal );
1505 if (!ordinal) return (FARPROC16)0;
1507 ret = NE_GetEntryPoint( hModule, ordinal );
1509 TRACE("returning %08x\n", (UINT)ret );
1510 return ret;
1514 /***********************************************************************
1515 * GetProcAddress (KERNEL32.257)
1517 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1519 return MODULE_GetProcAddress( hModule, function, TRUE );
1522 /***********************************************************************
1523 * GetProcAddress32 (KERNEL.453)
1525 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
1527 return MODULE_GetProcAddress( hModule, function, FALSE );
1530 /***********************************************************************
1531 * MODULE_GetProcAddress (internal)
1533 FARPROC MODULE_GetProcAddress(
1534 HMODULE hModule, /* [in] current module handle */
1535 LPCSTR function, /* [in] function to be looked up */
1536 BOOL snoop )
1538 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1539 FARPROC retproc;
1541 if (HIWORD(function))
1542 TRACE_(win32)("(%08lx,%s)\n",(DWORD)hModule,function);
1543 else
1544 TRACE_(win32)("(%08lx,%p)\n",(DWORD)hModule,function);
1545 if (!wm) {
1546 SetLastError(ERROR_INVALID_HANDLE);
1547 return (FARPROC)0;
1549 switch (wm->type)
1551 case MODULE32_PE:
1552 retproc = PE_FindExportedFunction( wm, function, snoop );
1553 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1554 return retproc;
1555 case MODULE32_ELF:
1556 retproc = ELF_FindExportedFunction( wm, function);
1557 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1558 return retproc;
1559 default:
1560 ERR("wine_modref type %d not handled.\n",wm->type);
1561 SetLastError(ERROR_INVALID_HANDLE);
1562 return (FARPROC)0;
1567 /***********************************************************************
1568 * RtlImageNtHeader (NTDLL)
1570 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
1572 /* basically:
1573 * return hModule+(((IMAGE_DOS_HEADER*)hModule)->e_lfanew);
1574 * but we could get HMODULE16 or the like (think builtin modules)
1577 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1578 if (!wm || (wm->type != MODULE32_PE)) return (PIMAGE_NT_HEADERS)0;
1579 return PE_HEADER(wm->module);
1583 /***************************************************************************
1584 * HasGPHandler (KERNEL.338)
1587 #include "pshpack1.h"
1588 typedef struct _GPHANDLERDEF
1590 WORD selector;
1591 WORD rangeStart;
1592 WORD rangeEnd;
1593 WORD handler;
1594 } GPHANDLERDEF;
1595 #include "poppack.h"
1597 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1599 HMODULE16 hModule;
1600 int gpOrdinal;
1601 SEGPTR gpPtr;
1602 GPHANDLERDEF *gpHandler;
1604 if ( (hModule = FarGetOwner16( SELECTOROF(address) )) != 0
1605 && (gpOrdinal = NE_GetOrdinal( hModule, "__GP" )) != 0
1606 && (gpPtr = (SEGPTR)NE_GetEntryPointEx( hModule, gpOrdinal, FALSE )) != 0
1607 && !IsBadReadPtr16( gpPtr, sizeof(GPHANDLERDEF) )
1608 && (gpHandler = PTR_SEG_TO_LIN( gpPtr )) != NULL )
1610 while (gpHandler->selector)
1612 if ( SELECTOROF(address) == gpHandler->selector
1613 && OFFSETOF(address) >= gpHandler->rangeStart
1614 && OFFSETOF(address) < gpHandler->rangeEnd )
1615 return PTR_SEG_OFF_TO_SEGPTR( gpHandler->selector,
1616 gpHandler->handler );
1617 gpHandler++;
1621 return 0;