Fixed a few problems.
[wine/hacks.git] / loader / module.c
blob44ceac5c58b1b2a990f5ab360e20836ce6b69788
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 "wine/winbase16.h"
16 #include "winerror.h"
17 #include "file.h"
18 #include "global.h"
19 #include "heap.h"
20 #include "module.h"
21 #include "snoop.h"
22 #include "neexe.h"
23 #include "pe_image.h"
24 #include "dosexe.h"
25 #include "process.h"
26 #include "syslevel.h"
27 #include "thread.h"
28 #include "selectors.h"
29 #include "stackframe.h"
30 #include "task.h"
31 #include "debugtools.h"
32 #include "callback.h"
33 #include "loadorder.h"
34 #include "elfdll.h"
35 #include "server.h"
37 DEFAULT_DEBUG_CHANNEL(module);
38 DECLARE_DEBUG_CHANNEL(win32);
41 /*************************************************************************
42 * MODULE32_LookupHMODULE
43 * looks for the referenced HMODULE in the current process
45 WINE_MODREF *MODULE32_LookupHMODULE( HMODULE hmod )
47 WINE_MODREF *wm;
49 if (!hmod)
50 return PROCESS_Current()->exe_modref;
52 if (!HIWORD(hmod)) {
53 ERR("tried to lookup 0x%04x in win32 module handler!\n",hmod);
54 return NULL;
56 for ( wm = PROCESS_Current()->modref_list; wm; wm=wm->next )
57 if (wm->module == hmod)
58 return wm;
59 return NULL;
62 /*************************************************************************
63 * MODULE_InitDLL
65 static BOOL MODULE_InitDLL( WINE_MODREF *wm, DWORD type, LPVOID lpReserved )
67 BOOL retv = TRUE;
69 static LPCSTR typeName[] = { "PROCESS_DETACH", "PROCESS_ATTACH",
70 "THREAD_ATTACH", "THREAD_DETACH" };
71 assert( wm );
74 /* Skip calls for modules loaded with special load flags */
76 if ( ( wm->flags & WINE_MODREF_DONT_RESOLVE_REFS )
77 || ( wm->flags & WINE_MODREF_LOAD_AS_DATAFILE ) )
78 return TRUE;
81 TRACE("(%s,%s,%p) - CALL\n", wm->modname, typeName[type], lpReserved );
83 /* Call the initialization routine */
84 switch ( wm->type )
86 case MODULE32_PE:
87 retv = PE_InitDLL( wm, type, lpReserved );
88 break;
90 case MODULE32_ELF:
91 /* no need to do that, dlopen() already does */
92 break;
94 default:
95 ERR("wine_modref type %d not handled.\n", wm->type );
96 retv = FALSE;
97 break;
100 /* The state of the module list may have changed due to the call
101 to PE_InitDLL. We cannot assume that this module has not been
102 deleted. */
103 TRACE("(%p,%s,%p) - RETURN %d\n", wm, typeName[type], lpReserved, retv );
105 return retv;
108 /*************************************************************************
109 * MODULE_DllProcessAttach
111 * Send the process attach notification to all DLLs the given module
112 * depends on (recursively). This is somewhat complicated due to the fact that
114 * - we have to respect the module dependencies, i.e. modules implicitly
115 * referenced by another module have to be initialized before the module
116 * itself can be initialized
118 * - the initialization routine of a DLL can itself call LoadLibrary,
119 * thereby introducing a whole new set of dependencies (even involving
120 * the 'old' modules) at any time during the whole process
122 * (Note that this routine can be recursively entered not only directly
123 * from itself, but also via LoadLibrary from one of the called initialization
124 * routines.)
126 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
127 * the process *detach* notifications to be sent in the correct order.
128 * This must not only take into account module dependencies, but also
129 * 'hidden' dependencies created by modules calling LoadLibrary in their
130 * attach notification routine.
132 * The strategy is rather simple: we move a WINE_MODREF to the head of the
133 * list after the attach notification has returned. This implies that the
134 * detach notifications are called in the reverse of the sequence the attach
135 * notifications *returned*.
137 * NOTE: Assumes that the process critical section is held!
140 BOOL MODULE_DllProcessAttach( WINE_MODREF *wm, LPVOID lpReserved )
142 BOOL retv = TRUE;
143 int i;
144 assert( wm );
146 /* prevent infinite recursion in case of cyclical dependencies */
147 if ( ( wm->flags & WINE_MODREF_MARKER )
148 || ( wm->flags & WINE_MODREF_PROCESS_ATTACHED ) )
149 return retv;
151 TRACE("(%s,%p) - START\n", wm->modname, lpReserved );
153 /* Tag current MODREF to prevent recursive loop */
154 wm->flags |= WINE_MODREF_MARKER;
156 /* Recursively attach all DLLs this one depends on */
157 for ( i = 0; retv && i < wm->nDeps; i++ )
158 if ( wm->deps[i] )
159 retv = MODULE_DllProcessAttach( wm->deps[i], lpReserved );
161 /* Call DLL entry point */
162 if ( retv )
164 retv = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
165 if ( retv )
166 wm->flags |= WINE_MODREF_PROCESS_ATTACHED;
169 /* Re-insert MODREF at head of list */
170 if ( retv && wm->prev )
172 wm->prev->next = wm->next;
173 if ( wm->next ) wm->next->prev = wm->prev;
175 wm->prev = NULL;
176 wm->next = PROCESS_Current()->modref_list;
177 PROCESS_Current()->modref_list = wm->next->prev = wm;
180 /* Remove recursion flag */
181 wm->flags &= ~WINE_MODREF_MARKER;
183 TRACE("(%s,%p) - END\n", wm->modname, lpReserved );
185 return retv;
188 /*************************************************************************
189 * MODULE_DllProcessDetach
191 * Send DLL process detach notifications. See the comment about calling
192 * sequence at MODULE_DllProcessAttach. Unless the bForceDetach flag
193 * is set, only DLLs with zero refcount are notified.
195 void MODULE_DllProcessDetach( BOOL bForceDetach, LPVOID lpReserved )
197 WINE_MODREF *wm;
199 EnterCriticalSection( &PROCESS_Current()->crit_section );
203 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
205 /* Check whether to detach this DLL */
206 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
207 continue;
208 if ( wm->refCount > 0 && !bForceDetach )
209 continue;
211 /* Call detach notification */
212 wm->flags &= ~WINE_MODREF_PROCESS_ATTACHED;
213 MODULE_InitDLL( wm, DLL_PROCESS_DETACH, lpReserved );
215 /* Restart at head of WINE_MODREF list, as entries might have
216 been added and/or removed while performing the call ... */
217 break;
219 } while ( wm );
221 LeaveCriticalSection( &PROCESS_Current()->crit_section );
224 /*************************************************************************
225 * MODULE_DllThreadAttach
227 * Send DLL thread attach notifications. These are sent in the
228 * reverse sequence of process detach notification.
231 void MODULE_DllThreadAttach( LPVOID lpReserved )
233 WINE_MODREF *wm;
235 EnterCriticalSection( &PROCESS_Current()->crit_section );
237 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
238 if ( !wm->next )
239 break;
241 for ( ; wm; wm = wm->prev )
243 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
244 continue;
245 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
246 continue;
248 MODULE_InitDLL( wm, DLL_THREAD_ATTACH, lpReserved );
251 LeaveCriticalSection( &PROCESS_Current()->crit_section );
254 /*************************************************************************
255 * MODULE_DllThreadDetach
257 * Send DLL thread detach notifications. These are sent in the
258 * same sequence as process detach notification.
261 void MODULE_DllThreadDetach( LPVOID lpReserved )
263 WINE_MODREF *wm;
265 EnterCriticalSection( &PROCESS_Current()->crit_section );
267 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
269 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
270 continue;
271 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
272 continue;
274 MODULE_InitDLL( wm, DLL_THREAD_DETACH, lpReserved );
277 LeaveCriticalSection( &PROCESS_Current()->crit_section );
280 /****************************************************************************
281 * DisableThreadLibraryCalls (KERNEL32.74)
283 * Don't call DllEntryPoint for DLL_THREAD_{ATTACH,DETACH} if set.
285 BOOL WINAPI DisableThreadLibraryCalls( HMODULE hModule )
287 WINE_MODREF *wm;
288 BOOL retval = TRUE;
290 EnterCriticalSection( &PROCESS_Current()->crit_section );
292 wm = MODULE32_LookupHMODULE( hModule );
293 if ( !wm )
294 retval = FALSE;
295 else
296 wm->flags |= WINE_MODREF_NO_DLL_CALLS;
298 LeaveCriticalSection( &PROCESS_Current()->crit_section );
300 return retval;
304 /***********************************************************************
305 * MODULE_CreateDummyModule
307 * Create a dummy NE module for Win32 or Winelib.
309 HMODULE MODULE_CreateDummyModule( LPCSTR filename, HMODULE module32 )
311 HMODULE hModule;
312 NE_MODULE *pModule;
313 SEGTABLEENTRY *pSegment;
314 char *pStr,*s;
315 unsigned int len;
316 const char* basename;
317 OFSTRUCT *ofs;
318 int of_size, size;
320 /* Extract base filename */
321 basename = strrchr(filename, '\\');
322 if (!basename) basename = filename;
323 else basename++;
324 len = strlen(basename);
325 if ((s = strchr(basename, '.'))) len = s - basename;
327 /* Allocate module */
328 of_size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName)
329 + strlen(filename) + 1;
330 size = sizeof(NE_MODULE) +
331 /* loaded file info */
332 of_size +
333 /* segment table: DS,CS */
334 2 * sizeof(SEGTABLEENTRY) +
335 /* name table */
336 len + 2 +
337 /* several empty tables */
340 hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
341 if (!hModule) return (HMODULE)11; /* invalid exe */
343 FarSetOwner16( hModule, hModule );
344 pModule = (NE_MODULE *)GlobalLock16( hModule );
346 /* Set all used entries */
347 pModule->magic = IMAGE_OS2_SIGNATURE;
348 pModule->count = 1;
349 pModule->next = 0;
350 pModule->flags = 0;
351 pModule->dgroup = 0;
352 pModule->ss = 1;
353 pModule->cs = 2;
354 pModule->heap_size = 0;
355 pModule->stack_size = 0;
356 pModule->seg_count = 2;
357 pModule->modref_count = 0;
358 pModule->nrname_size = 0;
359 pModule->fileinfo = sizeof(NE_MODULE);
360 pModule->os_flags = NE_OSFLAGS_WINDOWS;
361 pModule->self = hModule;
362 pModule->module32 = module32;
364 /* Set version and flags */
365 if (module32)
367 pModule->expected_version =
368 ((PE_HEADER(module32)->OptionalHeader.MajorSubsystemVersion & 0xff) << 8 ) |
369 (PE_HEADER(module32)->OptionalHeader.MinorSubsystemVersion & 0xff);
370 pModule->flags |= NE_FFLAGS_WIN32;
371 if (PE_HEADER(module32)->FileHeader.Characteristics & IMAGE_FILE_DLL)
372 pModule->flags |= NE_FFLAGS_LIBMODULE | NE_FFLAGS_SINGLEDATA;
375 /* Set loaded file information */
376 ofs = (OFSTRUCT *)(pModule + 1);
377 memset( ofs, 0, of_size );
378 ofs->cBytes = of_size < 256 ? of_size : 255; /* FIXME */
379 strcpy( ofs->szPathName, filename );
381 pSegment = (SEGTABLEENTRY*)((char*)(pModule + 1) + of_size);
382 pModule->seg_table = (int)pSegment - (int)pModule;
383 /* Data segment */
384 pSegment->size = 0;
385 pSegment->flags = NE_SEGFLAGS_DATA;
386 pSegment->minsize = 0x1000;
387 pSegment++;
388 /* Code segment */
389 pSegment->flags = 0;
390 pSegment++;
392 /* Module name */
393 pStr = (char *)pSegment;
394 pModule->name_table = (int)pStr - (int)pModule;
395 assert(len<256);
396 *pStr = len;
397 lstrcpynA( pStr+1, basename, len+1 );
398 pStr += len+2;
400 /* All tables zero terminated */
401 pModule->res_table = pModule->import_table = pModule->entry_table =
402 (int)pStr - (int)pModule;
404 NE_RegisterModule( pModule );
405 return hModule;
409 /**********************************************************************
410 * MODULE_FindModule32
412 * Find a (loaded) win32 module depending on path
414 * RETURNS
415 * the module handle if found
416 * 0 if not
418 WINE_MODREF *MODULE_FindModule(
419 LPCSTR path /* [in] pathname of module/library to be found */
421 WINE_MODREF *wm;
422 char dllname[260], *p;
424 /* Append .DLL to name if no extension present */
425 strcpy( dllname, path );
426 if (!(p = strrchr( dllname, '.')) || strchr( p, '/' ) || strchr( p, '\\'))
427 strcat( dllname, ".DLL" );
429 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
431 if ( !strcasecmp( dllname, wm->modname ) )
432 break;
433 if ( !strcasecmp( dllname, wm->filename ) )
434 break;
435 if ( !strcasecmp( dllname, wm->short_modname ) )
436 break;
437 if ( !strcasecmp( dllname, wm->short_filename ) )
438 break;
441 return wm;
445 /* Check whether a file is an OS/2 or a very old Windows executable
446 * by testing on import of KERNEL.
448 * FIXME: is reading the module imports the only way of discerning
449 * old Windows binaries from OS/2 ones ? At least it seems so...
451 static DWORD MODULE_Decide_OS2_OldWin(HANDLE hfile, IMAGE_DOS_HEADER *mz, IMAGE_OS2_HEADER *ne)
453 DWORD currpos = SetFilePointer( hfile, 0, NULL, SEEK_CUR);
454 DWORD type = SCS_OS216_BINARY;
455 LPWORD modtab = NULL;
456 LPSTR nametab = NULL;
457 DWORD len;
458 int i;
460 /* read modref table */
461 if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_modtab, NULL, SEEK_SET ) == -1)
462 || (!(modtab = HeapAlloc( GetProcessHeap(), 0, ne->ne_cmod*sizeof(WORD))))
463 || (!(ReadFile(hfile, modtab, ne->ne_cmod*sizeof(WORD), &len, NULL)))
464 || (len != ne->ne_cmod*sizeof(WORD)) )
465 goto broken;
467 /* read imported names table */
468 if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_imptab, NULL, SEEK_SET ) == -1)
469 || (!(nametab = HeapAlloc( GetProcessHeap(), 0, ne->ne_enttab - ne->ne_imptab)))
470 || (!(ReadFile(hfile, nametab, ne->ne_enttab - ne->ne_imptab, &len, NULL)))
471 || (len != ne->ne_enttab - ne->ne_imptab) )
472 goto broken;
474 for (i=0; i < ne->ne_cmod; i++)
476 LPSTR module = &nametab[modtab[i]];
477 TRACE("modref: %.*s\n", module[0], &module[1]);
478 if (!(strncmp(&module[1], "KERNEL", module[0])))
479 { /* very old Windows file */
480 MESSAGE("This seems to be a very old (pre-3.0) Windows executable. Expect crashes, especially if this is a real-mode binary !\n");
481 type = SCS_WOW_BINARY;
482 goto good;
486 broken:
487 ERR("Hmm, an error occurred. Is this binary file broken ?\n");
489 good:
490 HeapFree( GetProcessHeap(), 0, modtab);
491 HeapFree( GetProcessHeap(), 0, nametab);
492 SetFilePointer( hfile, currpos, NULL, SEEK_SET); /* restore filepos */
493 return type;
496 /***********************************************************************
497 * MODULE_GetBinaryType
499 * The GetBinaryType function determines whether a file is executable
500 * or not and if it is it returns what type of executable it is.
501 * The type of executable is a property that determines in which
502 * subsystem an executable file runs under.
504 * Binary types returned:
505 * SCS_32BIT_BINARY: A Win32 based application
506 * SCS_DOS_BINARY: An MS-Dos based application
507 * SCS_WOW_BINARY: A Win16 based application
508 * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
509 * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
510 * SCS_OS216_BINARY: A 16bit OS/2 based application
512 * Returns TRUE if the file is an executable in which case
513 * the value pointed by lpBinaryType is set.
514 * Returns FALSE if the file is not an executable or if the function fails.
516 * To do so it opens the file and reads in the header information
517 * if the extended header information is not present it will
518 * assume that the file is a DOS executable.
519 * If the extended header information is present it will
520 * determine if the file is a 16 or 32 bit Windows executable
521 * by check the flags in the header.
523 * Note that .COM and .PIF files are only recognized by their
524 * file name extension; but Windows does it the same way ...
526 BOOL MODULE_GetBinaryType( HANDLE hfile, LPCSTR filename, LPDWORD lpBinaryType )
528 IMAGE_DOS_HEADER mz_header;
529 char magic[4], *ptr;
530 DWORD len;
532 /* Seek to the start of the file and read the DOS header information.
534 if ( SetFilePointer( hfile, 0, NULL, SEEK_SET ) != -1
535 && ReadFile( hfile, &mz_header, sizeof(mz_header), &len, NULL )
536 && len == sizeof(mz_header) )
538 /* Now that we have the header check the e_magic field
539 * to see if this is a dos image.
541 if ( mz_header.e_magic == IMAGE_DOS_SIGNATURE )
543 BOOL lfanewValid = FALSE;
544 /* We do have a DOS image so we will now try to seek into
545 * the file by the amount indicated by the field
546 * "Offset to extended header" and read in the
547 * "magic" field information at that location.
548 * This will tell us if there is more header information
549 * to read or not.
551 /* But before we do we will make sure that header
552 * structure encompasses the "Offset to extended header"
553 * field.
555 if ( (mz_header.e_cparhdr<<4) >= sizeof(IMAGE_DOS_HEADER) )
556 if ( ( mz_header.e_crlc == 0 ) ||
557 ( mz_header.e_lfarlc >= sizeof(IMAGE_DOS_HEADER) ) )
558 if ( mz_header.e_lfanew >= sizeof(IMAGE_DOS_HEADER)
559 && SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET ) != -1
560 && ReadFile( hfile, magic, sizeof(magic), &len, NULL )
561 && len == sizeof(magic) )
562 lfanewValid = TRUE;
564 if ( !lfanewValid )
566 /* If we cannot read this "extended header" we will
567 * assume that we have a simple DOS executable.
569 *lpBinaryType = SCS_DOS_BINARY;
570 return TRUE;
572 else
574 /* Reading the magic field succeeded so
575 * we will try to determine what type it is.
577 if ( *(DWORD*)magic == IMAGE_NT_SIGNATURE )
579 /* This is an NT signature.
581 *lpBinaryType = SCS_32BIT_BINARY;
582 return TRUE;
584 else if ( *(WORD*)magic == IMAGE_OS2_SIGNATURE )
586 /* The IMAGE_OS2_SIGNATURE indicates that the
587 * "extended header is a Windows executable (NE)
588 * header." This can mean either a 16-bit OS/2
589 * or a 16-bit Windows or even a DOS program
590 * (running under a DOS extender). To decide
591 * which, we'll have to read the NE header.
594 IMAGE_OS2_HEADER ne;
595 if ( SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET ) != -1
596 && ReadFile( hfile, &ne, sizeof(ne), &len, NULL )
597 && len == sizeof(ne) )
599 switch ( ne.ne_exetyp )
601 case 2: *lpBinaryType = SCS_WOW_BINARY; return TRUE;
602 case 5: *lpBinaryType = SCS_DOS_BINARY; return TRUE;
603 default: *lpBinaryType =
604 MODULE_Decide_OS2_OldWin(hfile, &mz_header, &ne);
605 return TRUE;
608 /* Couldn't read header, so abort. */
609 return FALSE;
611 else
613 /* Unknown extended header, but this file is nonetheless
614 DOS-executable.
616 *lpBinaryType = SCS_DOS_BINARY;
617 return TRUE;
623 /* If we get here, we don't even have a correct MZ header.
624 * Try to check the file extension for known types ...
626 ptr = strrchr( filename, '.' );
627 if ( ptr && !strchr( ptr, '\\' ) && !strchr( ptr, '/' ) )
629 if ( !lstrcmpiA( ptr, ".COM" ) )
631 *lpBinaryType = SCS_DOS_BINARY;
632 return TRUE;
635 if ( !lstrcmpiA( ptr, ".PIF" ) )
637 *lpBinaryType = SCS_PIF_BINARY;
638 return TRUE;
642 return FALSE;
645 /***********************************************************************
646 * GetBinaryTypeA [KERNEL32.280]
648 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
650 BOOL ret = FALSE;
651 HANDLE hfile;
653 TRACE_(win32)("%s\n", lpApplicationName );
655 /* Sanity check.
657 if ( lpApplicationName == NULL || lpBinaryType == NULL )
658 return FALSE;
660 /* Open the file indicated by lpApplicationName for reading.
662 hfile = CreateFileA( lpApplicationName, GENERIC_READ, FILE_SHARE_READ,
663 NULL, OPEN_EXISTING, 0, -1 );
664 if ( hfile == INVALID_HANDLE_VALUE )
665 return FALSE;
667 /* Check binary type
669 ret = MODULE_GetBinaryType( hfile, lpApplicationName, lpBinaryType );
671 /* Close the file.
673 CloseHandle( hfile );
675 return ret;
678 /***********************************************************************
679 * GetBinaryTypeW [KERNEL32.281]
681 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
683 BOOL ret = FALSE;
684 LPSTR strNew = NULL;
686 TRACE_(win32)("%s\n", debugstr_w(lpApplicationName) );
688 /* Sanity check.
690 if ( lpApplicationName == NULL || lpBinaryType == NULL )
691 return FALSE;
693 /* Convert the wide string to a ascii string.
695 strNew = HEAP_strdupWtoA( GetProcessHeap(), 0, lpApplicationName );
697 if ( strNew != NULL )
699 ret = GetBinaryTypeA( strNew, lpBinaryType );
701 /* Free the allocated string.
703 HeapFree( GetProcessHeap(), 0, strNew );
706 return ret;
710 /***********************************************************************
711 * WinExec16 (KERNEL.166)
713 HINSTANCE16 WINAPI WinExec16( LPCSTR lpCmdLine, UINT16 nCmdShow )
715 LPCSTR p;
716 LPSTR name, cmdline;
717 int len;
718 HINSTANCE16 ret;
719 char buffer[MAX_PATH];
721 if ((p = strchr( lpCmdLine, ' ' )))
723 if (!(name = HeapAlloc( GetProcessHeap(), 0, p - lpCmdLine + 1 )))
724 return ERROR_NOT_ENOUGH_MEMORY;
725 memcpy( name, lpCmdLine, p - lpCmdLine );
726 name[p - lpCmdLine] = 0;
727 p++;
728 len = strlen(p);
729 cmdline = SEGPTR_ALLOC( len + 2 );
730 cmdline[0] = (BYTE)len;
731 strcpy( cmdline + 1, p );
733 else
735 name = (LPSTR)lpCmdLine;
736 cmdline = SEGPTR_ALLOC(2);
737 cmdline[0] = cmdline[1] = 0;
740 if (SearchPathA( NULL, name, ".exe", sizeof(buffer), buffer, NULL ))
742 LOADPARAMS16 params;
743 WORD *showCmd = SEGPTR_ALLOC( 2*sizeof(WORD) );
744 showCmd[0] = 2;
745 showCmd[1] = nCmdShow;
747 params.hEnvironment = 0;
748 params.cmdLine = SEGPTR_GET(cmdline);
749 params.showCmd = SEGPTR_GET(showCmd);
750 params.reserved = 0;
752 ret = LoadModule16( buffer, &params );
754 SEGPTR_FREE( showCmd );
755 SEGPTR_FREE( cmdline );
757 else ret = GetLastError();
759 if (name != lpCmdLine) HeapFree( GetProcessHeap(), 0, name );
761 if (ret == 21) /* 32-bit module */
763 SYSLEVEL_ReleaseWin16Lock();
764 ret = WinExec( lpCmdLine, nCmdShow );
765 SYSLEVEL_RestoreWin16Lock();
767 return ret;
770 /***********************************************************************
771 * WinExec (KERNEL32.566)
773 HINSTANCE WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
775 PROCESS_INFORMATION info;
776 STARTUPINFOA startup;
777 HINSTANCE hInstance;
778 char *cmdline;
780 memset( &startup, 0, sizeof(startup) );
781 startup.cb = sizeof(startup);
782 startup.dwFlags = STARTF_USESHOWWINDOW;
783 startup.wShowWindow = nCmdShow;
785 /* cmdline needs to be writeable for CreateProcess */
786 if (!(cmdline = HEAP_strdupA( GetProcessHeap(), 0, lpCmdLine ))) return 0;
788 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
789 0, NULL, NULL, &startup, &info ))
791 /* Give 30 seconds to the app to come up */
792 if (Callout.WaitForInputIdle ( info.hProcess, 30000 ) == 0xFFFFFFFF)
793 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
794 hInstance = 33;
795 /* Close off the handles */
796 CloseHandle( info.hThread );
797 CloseHandle( info.hProcess );
799 else if ((hInstance = GetLastError()) >= 32)
801 FIXME("Strange error set by CreateProcess: %d\n", hInstance );
802 hInstance = 11;
804 HeapFree( GetProcessHeap(), 0, cmdline );
805 return hInstance;
808 /**********************************************************************
809 * LoadModule (KERNEL32.499)
811 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
813 LOADPARAMS *params = (LOADPARAMS *)paramBlock;
814 PROCESS_INFORMATION info;
815 STARTUPINFOA startup;
816 HINSTANCE hInstance;
817 LPSTR cmdline, p;
818 char filename[MAX_PATH];
819 BYTE len;
821 if (!name) return ERROR_FILE_NOT_FOUND;
823 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
824 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
825 return GetLastError();
827 len = (BYTE)params->lpCmdLine[0];
828 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
829 return ERROR_NOT_ENOUGH_MEMORY;
831 strcpy( cmdline, filename );
832 p = cmdline + strlen(cmdline);
833 *p++ = ' ';
834 memcpy( p, params->lpCmdLine + 1, len );
835 p[len] = 0;
837 memset( &startup, 0, sizeof(startup) );
838 startup.cb = sizeof(startup);
839 if (params->lpCmdShow)
841 startup.dwFlags = STARTF_USESHOWWINDOW;
842 startup.wShowWindow = params->lpCmdShow[1];
845 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
846 params->lpEnvAddress, NULL, &startup, &info ))
848 /* Give 30 seconds to the app to come up */
849 if ( Callout.WaitForInputIdle ( info.hProcess, 30000 ) == 0xFFFFFFFF )
850 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
851 hInstance = 33;
852 /* Close off the handles */
853 CloseHandle( info.hThread );
854 CloseHandle( info.hProcess );
856 else if ((hInstance = GetLastError()) >= 32)
858 FIXME("Strange error set by CreateProcess: %d\n", hInstance );
859 hInstance = 11;
862 HeapFree( GetProcessHeap(), 0, cmdline );
863 return hInstance;
867 /*************************************************************************
868 * get_file_name
870 * Helper for CreateProcess: retrieve the file name to load from the
871 * app name and command line. Store the file name in buffer, and
872 * return a possibly modified command line.
874 static LPSTR get_file_name( LPCSTR appname, LPSTR cmdline, LPSTR buffer, int buflen )
876 char *name, *pos, *ret = NULL;
877 const char *p;
879 /* if we have an app name, everything is easy */
881 if (appname)
883 /* use the unmodified app name as file name */
884 lstrcpynA( buffer, appname, buflen );
885 if (!(ret = cmdline))
887 /* no command-line, create one */
888 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(appname) + 3 )))
889 sprintf( ret, "\"%s\"", appname );
891 return ret;
894 if (!cmdline)
896 SetLastError( ERROR_INVALID_PARAMETER );
897 return NULL;
900 /* first check for a quoted file name */
902 if ((cmdline[0] == '"') && ((p = strchr( cmdline + 1, '"' ))))
904 int len = p - cmdline - 1;
905 /* extract the quoted portion as file name */
906 if (!(name = HeapAlloc( GetProcessHeap(), 0, len + 1 ))) return NULL;
907 memcpy( name, cmdline + 1, len );
908 name[len] = 0;
910 if (SearchPathA( NULL, name, ".exe", buflen, buffer, NULL ) ||
911 SearchPathA( NULL, name, NULL, buflen, buffer, NULL ))
912 ret = cmdline; /* no change necessary */
913 goto done;
916 /* now try the command-line word by word */
918 if (!(name = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 1 ))) return NULL;
919 pos = name;
920 p = cmdline;
922 while (*p)
924 do *pos++ = *p++; while (*p && *p != ' ');
925 *pos = 0;
926 TRACE("trying '%s'\n", name );
927 if (SearchPathA( NULL, name, ".exe", buflen, buffer, NULL ) ||
928 SearchPathA( NULL, name, NULL, buflen, buffer, NULL ))
930 ret = cmdline;
931 break;
935 if (!ret || !strchr( name, ' ' )) goto done; /* no change necessary */
937 /* now build a new command-line with quotes */
939 if (!(ret = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 3 ))) goto done;
940 sprintf( ret, "\"%s\"%s", name, p );
942 done:
943 HeapFree( GetProcessHeap(), 0, name );
944 return ret;
948 /**********************************************************************
949 * CreateProcessA (KERNEL32.171)
951 BOOL WINAPI CreateProcessA( LPCSTR lpApplicationName, LPSTR lpCommandLine,
952 LPSECURITY_ATTRIBUTES lpProcessAttributes,
953 LPSECURITY_ATTRIBUTES lpThreadAttributes,
954 BOOL bInheritHandles, DWORD dwCreationFlags,
955 LPVOID lpEnvironment, LPCSTR lpCurrentDirectory,
956 LPSTARTUPINFOA lpStartupInfo,
957 LPPROCESS_INFORMATION lpProcessInfo )
959 BOOL retv = FALSE;
960 HANDLE hFile;
961 DWORD type;
962 char name[MAX_PATH];
963 LPSTR tidy_cmdline;
965 /* Process the AppName and/or CmdLine to get module name and path */
967 TRACE("app '%s' cmdline '%s'\n", lpApplicationName, lpCommandLine );
969 if (!(tidy_cmdline = get_file_name( lpApplicationName, lpCommandLine, name, sizeof(name) )))
970 return FALSE;
972 /* Warn if unsupported features are used */
974 if (dwCreationFlags & DETACHED_PROCESS)
975 FIXME("(%s,...): DETACHED_PROCESS ignored\n", name);
976 if (dwCreationFlags & CREATE_NEW_CONSOLE)
977 FIXME("(%s,...): CREATE_NEW_CONSOLE ignored\n", name);
978 if (dwCreationFlags & NORMAL_PRIORITY_CLASS)
979 FIXME("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
980 if (dwCreationFlags & IDLE_PRIORITY_CLASS)
981 FIXME("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
982 if (dwCreationFlags & HIGH_PRIORITY_CLASS)
983 FIXME("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
984 if (dwCreationFlags & REALTIME_PRIORITY_CLASS)
985 FIXME("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
986 if (dwCreationFlags & CREATE_NEW_PROCESS_GROUP)
987 FIXME("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
988 if (dwCreationFlags & CREATE_UNICODE_ENVIRONMENT)
989 FIXME("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
990 if (dwCreationFlags & CREATE_SEPARATE_WOW_VDM)
991 FIXME("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
992 if (dwCreationFlags & CREATE_SHARED_WOW_VDM)
993 FIXME("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
994 if (dwCreationFlags & CREATE_DEFAULT_ERROR_MODE)
995 FIXME("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
996 if (dwCreationFlags & CREATE_NO_WINDOW)
997 FIXME("(%s,...): CREATE_NO_WINDOW ignored\n", name);
998 if (dwCreationFlags & PROFILE_USER)
999 FIXME("(%s,...): PROFILE_USER ignored\n", name);
1000 if (dwCreationFlags & PROFILE_KERNEL)
1001 FIXME("(%s,...): PROFILE_KERNEL ignored\n", name);
1002 if (dwCreationFlags & PROFILE_SERVER)
1003 FIXME("(%s,...): PROFILE_SERVER ignored\n", name);
1004 if (lpStartupInfo->lpDesktop)
1005 FIXME("(%s,...): lpStartupInfo->lpDesktop %s ignored\n",
1006 name, lpStartupInfo->lpDesktop);
1007 if (lpStartupInfo->lpTitle)
1008 FIXME("(%s,...): lpStartupInfo->lpTitle %s ignored\n",
1009 name, lpStartupInfo->lpTitle);
1010 if (lpStartupInfo->dwFlags & STARTF_USECOUNTCHARS)
1011 FIXME("(%s,...): STARTF_USECOUNTCHARS (%ld,%ld) ignored\n",
1012 name, lpStartupInfo->dwXCountChars, lpStartupInfo->dwYCountChars);
1013 if (lpStartupInfo->dwFlags & STARTF_USEFILLATTRIBUTE)
1014 FIXME("(%s,...): STARTF_USEFILLATTRIBUTE %lx ignored\n",
1015 name, lpStartupInfo->dwFillAttribute);
1016 if (lpStartupInfo->dwFlags & STARTF_RUNFULLSCREEN)
1017 FIXME("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
1018 if (lpStartupInfo->dwFlags & STARTF_FORCEONFEEDBACK)
1019 FIXME("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
1020 if (lpStartupInfo->dwFlags & STARTF_FORCEOFFFEEDBACK)
1021 FIXME("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
1022 if (lpStartupInfo->dwFlags & STARTF_USEHOTKEY)
1023 FIXME("(%s,...): STARTF_USEHOTKEY ignored\n", name);
1025 /* Open file and determine executable type */
1027 hFile = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, -1 );
1028 if (hFile == INVALID_HANDLE_VALUE) goto done;
1030 if ( !MODULE_GetBinaryType( hFile, name, &type ) )
1032 CloseHandle( hFile );
1033 retv = PROCESS_Create( -1, name, tidy_cmdline, lpEnvironment,
1034 lpProcessAttributes, lpThreadAttributes,
1035 bInheritHandles, dwCreationFlags,
1036 lpStartupInfo, lpProcessInfo, lpCurrentDirectory );
1037 goto done;
1040 /* Create process */
1042 switch ( type )
1044 case SCS_32BIT_BINARY:
1045 case SCS_WOW_BINARY:
1046 case SCS_DOS_BINARY:
1047 retv = PROCESS_Create( hFile, name, tidy_cmdline, lpEnvironment,
1048 lpProcessAttributes, lpThreadAttributes,
1049 bInheritHandles, dwCreationFlags,
1050 lpStartupInfo, lpProcessInfo, lpCurrentDirectory);
1051 break;
1053 case SCS_PIF_BINARY:
1054 case SCS_POSIX_BINARY:
1055 case SCS_OS216_BINARY:
1056 FIXME("Unsupported executable type: %ld\n", type );
1057 /* fall through */
1059 default:
1060 SetLastError( ERROR_BAD_FORMAT );
1061 break;
1063 CloseHandle( hFile );
1065 done:
1066 if (tidy_cmdline != lpCommandLine) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1067 return retv;
1070 /**********************************************************************
1071 * CreateProcessW (KERNEL32.172)
1072 * NOTES
1073 * lpReserved is not converted
1075 BOOL WINAPI CreateProcessW( LPCWSTR lpApplicationName, LPWSTR lpCommandLine,
1076 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1077 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1078 BOOL bInheritHandles, DWORD dwCreationFlags,
1079 LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory,
1080 LPSTARTUPINFOW lpStartupInfo,
1081 LPPROCESS_INFORMATION lpProcessInfo )
1082 { BOOL ret;
1083 STARTUPINFOA StartupInfoA;
1085 LPSTR lpApplicationNameA = HEAP_strdupWtoA (GetProcessHeap(),0,lpApplicationName);
1086 LPSTR lpCommandLineA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCommandLine);
1087 LPSTR lpCurrentDirectoryA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCurrentDirectory);
1089 memcpy (&StartupInfoA, lpStartupInfo, sizeof(STARTUPINFOA));
1090 StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpDesktop);
1091 StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpTitle);
1093 TRACE_(win32)("(%s,%s,...)\n", debugstr_w(lpApplicationName), debugstr_w(lpCommandLine));
1095 if (lpStartupInfo->lpReserved)
1096 FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n", debugstr_w(lpStartupInfo->lpReserved));
1098 ret = CreateProcessA( lpApplicationNameA, lpCommandLineA,
1099 lpProcessAttributes, lpThreadAttributes,
1100 bInheritHandles, dwCreationFlags,
1101 lpEnvironment, lpCurrentDirectoryA,
1102 &StartupInfoA, lpProcessInfo );
1104 HeapFree( GetProcessHeap(), 0, lpCurrentDirectoryA );
1105 HeapFree( GetProcessHeap(), 0, lpCommandLineA );
1106 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1107 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1109 return ret;
1112 /***********************************************************************
1113 * GetModuleHandleA (KERNEL32.237)
1115 HMODULE WINAPI GetModuleHandleA(LPCSTR module)
1117 WINE_MODREF *wm;
1119 if ( module == NULL )
1120 wm = PROCESS_Current()->exe_modref;
1121 else
1122 wm = MODULE_FindModule( module );
1124 return wm? wm->module : 0;
1127 /***********************************************************************
1128 * GetModuleHandleW
1130 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
1132 HMODULE hModule;
1133 LPSTR modulea = HEAP_strdupWtoA( GetProcessHeap(), 0, module );
1134 hModule = GetModuleHandleA( modulea );
1135 HeapFree( GetProcessHeap(), 0, modulea );
1136 return hModule;
1140 /***********************************************************************
1141 * GetModuleFileNameA (KERNEL32.235)
1143 * GetModuleFileNameA seems to *always* return the long path;
1144 * it's only GetModuleFileName16 that decides between short/long path
1145 * by checking if exe version >= 4.0.
1146 * (SDK docu doesn't mention this)
1148 DWORD WINAPI GetModuleFileNameA(
1149 HMODULE hModule, /* [in] module handle (32bit) */
1150 LPSTR lpFileName, /* [out] filenamebuffer */
1151 DWORD size /* [in] size of filenamebuffer */
1152 ) {
1153 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1155 if (!wm) /* can happen on start up or the like */
1156 return 0;
1158 lstrcpynA( lpFileName, wm->filename, size );
1160 TRACE("%s\n", lpFileName );
1161 return strlen(lpFileName);
1165 /***********************************************************************
1166 * GetModuleFileNameW (KERNEL32.236)
1168 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName,
1169 DWORD size )
1171 LPSTR fnA = (char*)HeapAlloc( GetProcessHeap(), 0, size );
1172 DWORD res = GetModuleFileNameA( hModule, fnA, size );
1173 lstrcpynAtoW( lpFileName, fnA, size );
1174 HeapFree( GetProcessHeap(), 0, fnA );
1175 return res;
1179 /***********************************************************************
1180 * LoadLibraryExA (KERNEL32)
1182 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
1184 WINE_MODREF *wm;
1186 if(!libname)
1188 SetLastError(ERROR_INVALID_PARAMETER);
1189 return 0;
1192 EnterCriticalSection(&PROCESS_Current()->crit_section);
1194 wm = MODULE_LoadLibraryExA( libname, hfile, flags );
1195 if ( wm )
1197 if ( !MODULE_DllProcessAttach( wm, NULL ) )
1199 WARN_(module)("Attach failed for module '%s', \n", libname);
1200 MODULE_FreeLibrary(wm);
1201 SetLastError(ERROR_DLL_INIT_FAILED);
1202 wm = NULL;
1206 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1208 return wm ? wm->module : 0;
1211 /***********************************************************************
1212 * MODULE_LoadLibraryExA (internal)
1214 * Load a PE style module according to the load order.
1216 * The HFILE parameter is not used and marked reserved in the SDK. I can
1217 * only guess that it should force a file to be mapped, but I rather
1218 * ignore the parameter because it would be extremely difficult to
1219 * integrate this with different types of module represenations.
1222 WINE_MODREF *MODULE_LoadLibraryExA( LPCSTR libname, HFILE hfile, DWORD flags )
1224 DWORD err = GetLastError();
1225 WINE_MODREF *pwm;
1226 int i;
1227 module_loadorder_t *plo;
1229 EnterCriticalSection(&PROCESS_Current()->crit_section);
1231 /* Check for already loaded module */
1232 if((pwm = MODULE_FindModule(libname)))
1234 if(!(pwm->flags & WINE_MODREF_MARKER))
1235 pwm->refCount++;
1236 TRACE("Already loaded module '%s' at 0x%08x, count=%d, \n", libname, pwm->module, pwm->refCount);
1237 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1238 return pwm;
1241 plo = MODULE_GetLoadOrder(libname);
1243 for(i = 0; i < MODULE_LOADORDER_NTYPES; i++)
1245 SetLastError( ERROR_FILE_NOT_FOUND );
1246 switch(plo->loadorder[i])
1248 case MODULE_LOADORDER_DLL:
1249 TRACE("Trying native dll '%s'\n", libname);
1250 pwm = PE_LoadLibraryExA(libname, flags);
1251 break;
1253 case MODULE_LOADORDER_ELFDLL:
1254 TRACE("Trying elfdll '%s'\n", libname);
1255 if (!(pwm = BUILTIN32_LoadLibraryExA(libname, flags)))
1256 pwm = ELFDLL_LoadLibraryExA(libname, flags);
1257 break;
1259 case MODULE_LOADORDER_SO:
1260 TRACE("Trying so-library '%s'\n", libname);
1261 if (!(pwm = BUILTIN32_LoadLibraryExA(libname, flags)))
1262 pwm = ELF_LoadLibraryExA(libname, flags);
1263 break;
1265 case MODULE_LOADORDER_BI:
1266 TRACE("Trying built-in '%s'\n", libname);
1267 pwm = BUILTIN32_LoadLibraryExA(libname, flags);
1268 break;
1270 default:
1271 ERR("Got invalid loadorder type %d (%s index %d)\n", plo->loadorder[i], plo->modulename, i);
1272 /* Fall through */
1274 case MODULE_LOADORDER_INVALID: /* We ignore this as it is an empty entry */
1275 pwm = NULL;
1276 break;
1279 if(pwm)
1281 /* Initialize DLL just loaded */
1282 TRACE("Loaded module '%s' at 0x%08x, \n", libname, pwm->module);
1284 /* Set the refCount here so that an attach failure will */
1285 /* decrement the dependencies through the MODULE_FreeLibrary call. */
1286 pwm->refCount++;
1288 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1289 SetLastError( err ); /* restore last error */
1290 return pwm;
1293 if(GetLastError() != ERROR_FILE_NOT_FOUND)
1294 break;
1297 WARN("Failed to load module '%s'; error=0x%08lx, \n", libname, GetLastError());
1298 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1299 return NULL;
1302 /***********************************************************************
1303 * LoadLibraryA (KERNEL32)
1305 HMODULE WINAPI LoadLibraryA(LPCSTR libname) {
1306 return LoadLibraryExA(libname,0,0);
1309 /***********************************************************************
1310 * LoadLibraryW (KERNEL32)
1312 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
1314 return LoadLibraryExW(libnameW,0,0);
1317 /***********************************************************************
1318 * LoadLibrary32_16 (KERNEL.452)
1320 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
1322 HMODULE hModule;
1324 SYSLEVEL_ReleaseWin16Lock();
1325 hModule = LoadLibraryA( libname );
1326 SYSLEVEL_RestoreWin16Lock();
1328 return hModule;
1331 /***********************************************************************
1332 * LoadLibraryExW (KERNEL32)
1334 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW,HANDLE hfile,DWORD flags)
1336 LPSTR libnameA = HEAP_strdupWtoA( GetProcessHeap(), 0, libnameW );
1337 HMODULE ret = LoadLibraryExA( libnameA , hfile, flags );
1339 HeapFree( GetProcessHeap(), 0, libnameA );
1340 return ret;
1343 /***********************************************************************
1344 * MODULE_FlushModrefs
1346 * NOTE: Assumes that the process critical section is held!
1348 * Remove all unused modrefs and call the internal unloading routines
1349 * for the library type.
1351 static void MODULE_FlushModrefs(void)
1353 WINE_MODREF *wm, *next;
1355 for(wm = PROCESS_Current()->modref_list; wm; wm = next)
1357 next = wm->next;
1359 if(wm->refCount)
1360 continue;
1362 /* Unlink this modref from the chain */
1363 if(wm->next)
1364 wm->next->prev = wm->prev;
1365 if(wm->prev)
1366 wm->prev->next = wm->next;
1367 if(wm == PROCESS_Current()->modref_list)
1368 PROCESS_Current()->modref_list = wm->next;
1371 * The unloaders are also responsible for freeing the modref itself
1372 * because the loaders were responsible for allocating it.
1374 switch(wm->type)
1376 case MODULE32_PE: if ( !(wm->flags & WINE_MODREF_INTERNAL) )
1377 PE_UnloadLibrary(wm);
1378 else
1379 BUILTIN32_UnloadLibrary(wm);
1380 break;
1381 case MODULE32_ELF: ELF_UnloadLibrary(wm); break;
1382 case MODULE32_ELFDLL: ELFDLL_UnloadLibrary(wm); break;
1384 default:
1385 ERR("Invalid or unhandled MODREF type %d encountered (wm=%p)\n", wm->type, wm);
1390 /***********************************************************************
1391 * FreeLibrary
1393 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
1395 BOOL retv = FALSE;
1396 WINE_MODREF *wm;
1398 EnterCriticalSection( &PROCESS_Current()->crit_section );
1399 PROCESS_Current()->free_lib_count++;
1401 wm = MODULE32_LookupHMODULE( hLibModule );
1402 if ( !wm || !hLibModule )
1403 SetLastError( ERROR_INVALID_HANDLE );
1404 else
1405 retv = MODULE_FreeLibrary( wm );
1407 PROCESS_Current()->free_lib_count--;
1408 LeaveCriticalSection( &PROCESS_Current()->crit_section );
1410 return retv;
1413 /***********************************************************************
1414 * MODULE_DecRefCount
1416 * NOTE: Assumes that the process critical section is held!
1418 static void MODULE_DecRefCount( WINE_MODREF *wm )
1420 int i;
1422 if ( wm->flags & WINE_MODREF_MARKER )
1423 return;
1425 if ( wm->refCount <= 0 )
1426 return;
1428 --wm->refCount;
1429 TRACE("(%s) refCount: %d\n", wm->modname, wm->refCount );
1431 if ( wm->refCount == 0 )
1433 wm->flags |= WINE_MODREF_MARKER;
1435 for ( i = 0; i < wm->nDeps; i++ )
1436 if ( wm->deps[i] )
1437 MODULE_DecRefCount( wm->deps[i] );
1439 wm->flags &= ~WINE_MODREF_MARKER;
1443 /***********************************************************************
1444 * MODULE_FreeLibrary
1446 * NOTE: Assumes that the process critical section is held!
1448 BOOL MODULE_FreeLibrary( WINE_MODREF *wm )
1450 TRACE("(%s) - START\n", wm->modname );
1452 /* Recursively decrement reference counts */
1453 MODULE_DecRefCount( wm );
1455 /* Call process detach notifications */
1456 if ( PROCESS_Current()->free_lib_count <= 1 )
1458 struct unload_dll_request *req = get_req_buffer();
1460 MODULE_DllProcessDetach( FALSE, NULL );
1461 req->base = (void *)wm->module;
1462 server_call_noerr( REQ_UNLOAD_DLL );
1464 MODULE_FlushModrefs();
1467 TRACE("END\n");
1469 return TRUE;
1473 /***********************************************************************
1474 * FreeLibraryAndExitThread
1476 VOID WINAPI FreeLibraryAndExitThread(HINSTANCE hLibModule, DWORD dwExitCode)
1478 FreeLibrary(hLibModule);
1479 ExitThread(dwExitCode);
1482 /***********************************************************************
1483 * PrivateLoadLibrary (KERNEL32)
1485 * FIXME: rough guesswork, don't know what "Private" means
1487 HINSTANCE WINAPI PrivateLoadLibrary(LPCSTR libname)
1489 return (HINSTANCE)LoadLibrary16(libname);
1494 /***********************************************************************
1495 * PrivateFreeLibrary (KERNEL32)
1497 * FIXME: rough guesswork, don't know what "Private" means
1499 void WINAPI PrivateFreeLibrary(HINSTANCE handle)
1501 FreeLibrary16((HINSTANCE16)handle);
1505 /***********************************************************************
1506 * WIN32_GetProcAddress16 (KERNEL32.36)
1507 * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
1509 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
1511 WORD ordinal;
1512 FARPROC16 ret;
1514 if (!hModule) {
1515 WARN("hModule may not be 0!\n");
1516 return (FARPROC16)0;
1518 if (HIWORD(hModule))
1520 WARN("hModule is Win32 handle (%08x)\n", hModule );
1521 return (FARPROC16)0;
1523 hModule = GetExePtr( hModule );
1524 if (HIWORD(name)) {
1525 ordinal = NE_GetOrdinal( hModule, name );
1526 TRACE("%04x '%s'\n", hModule, name );
1527 } else {
1528 ordinal = LOWORD(name);
1529 TRACE("%04x %04x\n", hModule, ordinal );
1531 if (!ordinal) return (FARPROC16)0;
1532 ret = NE_GetEntryPoint( hModule, ordinal );
1533 TRACE("returning %08x\n",(UINT)ret);
1534 return ret;
1537 /***********************************************************************
1538 * GetProcAddress16 (KERNEL.50)
1540 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, SEGPTR name )
1542 WORD ordinal;
1543 FARPROC16 ret;
1545 if (!hModule) hModule = GetCurrentTask();
1546 hModule = GetExePtr( hModule );
1548 if (HIWORD(name) != 0)
1550 ordinal = NE_GetOrdinal( hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1551 TRACE("%04x '%s'\n", hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1553 else
1555 ordinal = LOWORD(name);
1556 TRACE("%04x %04x\n", hModule, ordinal );
1558 if (!ordinal) return (FARPROC16)0;
1560 ret = NE_GetEntryPoint( hModule, ordinal );
1562 TRACE("returning %08x\n", (UINT)ret );
1563 return ret;
1567 /***********************************************************************
1568 * GetProcAddress (KERNEL32.257)
1570 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1572 return MODULE_GetProcAddress( hModule, function, TRUE );
1575 /***********************************************************************
1576 * GetProcAddress32 (KERNEL.453)
1578 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
1580 return MODULE_GetProcAddress( hModule, function, FALSE );
1583 /***********************************************************************
1584 * MODULE_GetProcAddress (internal)
1586 FARPROC MODULE_GetProcAddress(
1587 HMODULE hModule, /* [in] current module handle */
1588 LPCSTR function, /* [in] function to be looked up */
1589 BOOL snoop )
1591 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1592 FARPROC retproc;
1594 if (HIWORD(function))
1595 TRACE_(win32)("(%08lx,%s)\n",(DWORD)hModule,function);
1596 else
1597 TRACE_(win32)("(%08lx,%p)\n",(DWORD)hModule,function);
1598 if (!wm) {
1599 SetLastError(ERROR_INVALID_HANDLE);
1600 return (FARPROC)0;
1602 switch (wm->type)
1604 case MODULE32_PE:
1605 retproc = PE_FindExportedFunction( wm, function, snoop );
1606 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1607 return retproc;
1608 case MODULE32_ELF:
1609 retproc = ELF_FindExportedFunction( wm, function);
1610 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1611 return retproc;
1612 default:
1613 ERR("wine_modref type %d not handled.\n",wm->type);
1614 SetLastError(ERROR_INVALID_HANDLE);
1615 return (FARPROC)0;
1620 /***************************************************************************
1621 * HasGPHandler (KERNEL.338)
1624 #include "pshpack1.h"
1625 typedef struct _GPHANDLERDEF
1627 WORD selector;
1628 WORD rangeStart;
1629 WORD rangeEnd;
1630 WORD handler;
1631 } GPHANDLERDEF;
1632 #include "poppack.h"
1634 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1636 HMODULE16 hModule;
1637 int gpOrdinal;
1638 SEGPTR gpPtr;
1639 GPHANDLERDEF *gpHandler;
1641 if ( (hModule = FarGetOwner16( SELECTOROF(address) )) != 0
1642 && (gpOrdinal = NE_GetOrdinal( hModule, "__GP" )) != 0
1643 && (gpPtr = (SEGPTR)NE_GetEntryPointEx( hModule, gpOrdinal, FALSE )) != 0
1644 && !IsBadReadPtr16( gpPtr, sizeof(GPHANDLERDEF) )
1645 && (gpHandler = PTR_SEG_TO_LIN( gpPtr )) != NULL )
1647 while (gpHandler->selector)
1649 if ( SELECTOROF(address) == gpHandler->selector
1650 && OFFSETOF(address) >= gpHandler->rangeStart
1651 && OFFSETOF(address) < gpHandler->rangeEnd )
1652 return PTR_SEG_OFF_TO_SEGPTR( gpHandler->selector,
1653 gpHandler->handler );
1654 gpHandler++;
1658 return 0;