Implemented AddPrinterA, AddPrinterDriverA and GetPrinterDriverDirectory
[wine.git] / loader / module.c
blob618ec5eb433e9f3d98c6ccde7cff3df98333e4cc
1 /*
2 * Modules
4 * Copyright 1995 Alexandre Julliard
5 */
7 #include <assert.h>
8 #include <fcntl.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <sys/types.h>
12 #include <unistd.h>
13 #include "wine/winuser16.h"
14 #include "wine/winbase16.h"
15 #include "windef.h"
16 #include "winerror.h"
17 #include "class.h"
18 #include "file.h"
19 #include "global.h"
20 #include "heap.h"
21 #include "module.h"
22 #include "neexe.h"
23 #include "pe_image.h"
24 #include "dosexe.h"
25 #include "process.h"
26 #include "thread.h"
27 #include "selectors.h"
28 #include "stackframe.h"
29 #include "task.h"
30 #include "debugtools.h"
31 #include "callback.h"
32 #include "loadorder.h"
33 #include "elfdll.h"
35 DECLARE_DEBUG_CHANNEL(module)
36 DECLARE_DEBUG_CHANNEL(win32)
39 /*************************************************************************
40 * MODULE32_LookupHMODULE
41 * looks for the referenced HMODULE in the current process
43 WINE_MODREF *MODULE32_LookupHMODULE( HMODULE hmod )
45 WINE_MODREF *wm;
47 if (!hmod)
48 return PROCESS_Current()->exe_modref;
50 if (!HIWORD(hmod)) {
51 ERR_(module)("tried to lookup 0x%04x in win32 module handler!\n",hmod);
52 return NULL;
54 for ( wm = PROCESS_Current()->modref_list; wm; wm=wm->next )
55 if (wm->module == hmod)
56 return wm;
57 return NULL;
60 /*************************************************************************
61 * MODULE_InitDll
63 static BOOL MODULE_InitDll( WINE_MODREF *wm, DWORD type, LPVOID lpReserved )
65 BOOL retv = TRUE;
67 static LPCSTR typeName[] = { "PROCESS_DETACH", "PROCESS_ATTACH",
68 "THREAD_ATTACH", "THREAD_DETACH" };
69 assert( wm );
72 /* Skip calls for modules loaded with special load flags */
74 if ( ( wm->flags & WINE_MODREF_DONT_RESOLVE_REFS )
75 || ( wm->flags & WINE_MODREF_LOAD_AS_DATAFILE ) )
76 return TRUE;
79 TRACE_(module)("(%s,%s,%p) - CALL\n",
80 wm->modname, typeName[type], lpReserved );
82 /* Call the initialization routine */
83 switch ( wm->type )
85 case MODULE32_PE:
86 retv = PE_InitDLL( wm, type, lpReserved );
87 break;
89 case MODULE32_ELF:
90 /* no need to do that, dlopen() already does */
91 break;
93 default:
94 ERR_(module)("wine_modref type %d not handled.\n", wm->type );
95 retv = FALSE;
96 break;
99 TRACE_(module)("(%s,%s,%p) - RETURN %d\n",
100 wm->modname, typeName[type], lpReserved, retv );
102 return retv;
105 /*************************************************************************
106 * MODULE_DllProcessAttach
108 * Send the process attach notification to all DLLs the given module
109 * depends on (recursively). This is somewhat complicated due to the fact that
111 * - we have to respect the module dependencies, i.e. modules implicitly
112 * referenced by another module have to be initialized before the module
113 * itself can be initialized
115 * - the initialization routine of a DLL can itself call LoadLibrary,
116 * thereby introducing a whole new set of dependencies (even involving
117 * the 'old' modules) at any time during the whole process
119 * (Note that this routine can be recursively entered not only directly
120 * from itself, but also via LoadLibrary from one of the called initialization
121 * routines.)
123 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
124 * the process *detach* notifications to be sent in the correct order.
125 * This must not only take into account module dependencies, but also
126 * 'hidden' dependencies created by modules calling LoadLibrary in their
127 * attach notification routine.
129 * The strategy is rather simple: we move a WINE_MODREF to the head of the
130 * list after the attach notification has returned. This implies that the
131 * detach notifications are called in the reverse of the sequence the attach
132 * notifications *returned*.
134 * NOTE: Assumes that the process critical section is held!
137 BOOL MODULE_DllProcessAttach( WINE_MODREF *wm, LPVOID lpReserved )
139 BOOL retv = TRUE;
140 int i;
141 assert( wm );
143 /* prevent infinite recursion in case of cyclical dependencies */
144 if ( ( wm->flags & WINE_MODREF_MARKER )
145 || ( wm->flags & WINE_MODREF_PROCESS_ATTACHED ) )
146 return retv;
148 TRACE_(module)("(%s,%p) - START\n",
149 wm->modname, lpReserved );
151 /* Tag current MODREF to prevent recursive loop */
152 wm->flags |= WINE_MODREF_MARKER;
154 /* Recursively attach all DLLs this one depends on */
155 for ( i = 0; retv && i < wm->nDeps; i++ )
156 if ( wm->deps[i] )
157 retv = MODULE_DllProcessAttach( wm->deps[i], lpReserved );
159 /* Call DLL entry point */
160 if ( retv )
162 retv = MODULE_InitDll( wm, DLL_PROCESS_ATTACH, lpReserved );
163 if ( retv )
164 wm->flags |= WINE_MODREF_PROCESS_ATTACHED;
167 /* Re-insert MODREF at head of list */
168 if ( retv && wm->prev )
170 wm->prev->next = wm->next;
171 if ( wm->next ) wm->next->prev = wm->prev;
173 wm->prev = NULL;
174 wm->next = PROCESS_Current()->modref_list;
175 PROCESS_Current()->modref_list = wm->next->prev = wm;
178 /* Remove recursion flag */
179 wm->flags &= ~WINE_MODREF_MARKER;
181 TRACE_(module)("(%s,%p) - END\n",
182 wm->modname, lpReserved );
184 return retv;
187 /*************************************************************************
188 * MODULE_DllProcessDetach
190 * Send DLL process detach notifications. See the comment about calling
191 * sequence at MODULE_DllProcessAttach. Unless the bForceDetach flag
192 * is set, only DLLs with zero refcount are notified.
194 * NOTE: Assumes that the process critical section is held!
197 void MODULE_DllProcessDetach( BOOL bForceDetach, LPVOID lpReserved )
199 WINE_MODREF *wm;
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 );
222 /*************************************************************************
223 * MODULE_DllThreadAttach
225 * Send DLL thread attach notifications. These are sent in the
226 * reverse sequence of process detach notification.
229 void MODULE_DllThreadAttach( LPVOID lpReserved )
231 WINE_MODREF *wm;
233 EnterCriticalSection( &PROCESS_Current()->crit_section );
235 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
236 if ( !wm->next )
237 break;
239 for ( ; wm; wm = wm->prev )
241 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
242 continue;
243 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
244 continue;
246 MODULE_InitDll( wm, DLL_THREAD_ATTACH, lpReserved );
249 LeaveCriticalSection( &PROCESS_Current()->crit_section );
252 /*************************************************************************
253 * MODULE_DllThreadDetach
255 * Send DLL thread detach notifications. These are sent in the
256 * same sequence as process detach notification.
259 void MODULE_DllThreadDetach( LPVOID lpReserved )
261 WINE_MODREF *wm;
263 EnterCriticalSection( &PROCESS_Current()->crit_section );
265 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
267 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
268 continue;
269 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
270 continue;
272 MODULE_InitDll( wm, DLL_THREAD_DETACH, lpReserved );
275 LeaveCriticalSection( &PROCESS_Current()->crit_section );
278 /****************************************************************************
279 * DisableThreadLibraryCalls (KERNEL32.74)
281 * Don't call DllEntryPoint for DLL_THREAD_{ATTACH,DETACH} if set.
283 BOOL WINAPI DisableThreadLibraryCalls( HMODULE hModule )
285 WINE_MODREF *wm;
286 BOOL retval = TRUE;
288 EnterCriticalSection( &PROCESS_Current()->crit_section );
290 wm = MODULE32_LookupHMODULE( hModule );
291 if ( !wm )
292 retval = FALSE;
293 else
294 wm->flags |= WINE_MODREF_NO_DLL_CALLS;
296 LeaveCriticalSection( &PROCESS_Current()->crit_section );
298 return retval;
302 /***********************************************************************
303 * MODULE_CreateDummyModule
305 * Create a dummy NE module for Win32 or Winelib.
307 HMODULE MODULE_CreateDummyModule( const OFSTRUCT *ofs, LPCSTR modName )
309 HMODULE hModule;
310 NE_MODULE *pModule;
311 SEGTABLEENTRY *pSegment;
312 char *pStr,*s;
313 int len;
314 const char* basename;
316 INT of_size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName)
317 + strlen(ofs->szPathName) + 1;
318 INT size = sizeof(NE_MODULE) +
319 /* loaded file info */
320 of_size +
321 /* segment table: DS,CS */
322 2 * sizeof(SEGTABLEENTRY) +
323 /* name table */
325 /* several empty tables */
328 hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
329 if (!hModule) return (HMODULE)11; /* invalid exe */
331 FarSetOwner16( hModule, hModule );
332 pModule = (NE_MODULE *)GlobalLock16( hModule );
334 /* Set all used entries */
335 pModule->magic = IMAGE_OS2_SIGNATURE;
336 pModule->count = 1;
337 pModule->next = 0;
338 pModule->flags = 0;
339 pModule->dgroup = 0;
340 pModule->ss = 1;
341 pModule->cs = 2;
342 pModule->heap_size = 0;
343 pModule->stack_size = 0;
344 pModule->seg_count = 2;
345 pModule->modref_count = 0;
346 pModule->nrname_size = 0;
347 pModule->fileinfo = sizeof(NE_MODULE);
348 pModule->os_flags = NE_OSFLAGS_WINDOWS;
349 pModule->expected_version = 0x030a;
350 pModule->self = hModule;
352 /* Set loaded file information */
353 memcpy( pModule + 1, ofs, of_size );
354 ((OFSTRUCT *)(pModule+1))->cBytes = of_size - 1;
356 pSegment = (SEGTABLEENTRY*)((char*)(pModule + 1) + of_size);
357 pModule->seg_table = (int)pSegment - (int)pModule;
358 /* Data segment */
359 pSegment->size = 0;
360 pSegment->flags = NE_SEGFLAGS_DATA;
361 pSegment->minsize = 0x1000;
362 pSegment++;
363 /* Code segment */
364 pSegment->flags = 0;
365 pSegment++;
367 /* Module name */
368 pStr = (char *)pSegment;
369 pModule->name_table = (int)pStr - (int)pModule;
370 if ( modName )
371 basename = modName;
372 else
374 basename = strrchr(ofs->szPathName,'\\');
375 if (!basename) basename = ofs->szPathName;
376 else basename++;
378 len = strlen(basename);
379 if ((s = strchr(basename,'.'))) len = s - basename;
380 if (len > 8) len = 8;
381 *pStr = len;
382 strncpy( pStr+1, basename, len );
383 if (len < 8) pStr[len+1] = 0;
384 pStr += 9;
386 /* All tables zero terminated */
387 pModule->res_table = pModule->import_table = pModule->entry_table =
388 (int)pStr - (int)pModule;
390 NE_RegisterModule( pModule );
391 return hModule;
395 /***********************************************************************
396 * MODULE_GetWndProcEntry16 (not a Windows API function)
398 * Return an entry point from the WPROCS dll.
400 FARPROC16 MODULE_GetWndProcEntry16( LPCSTR name )
402 FARPROC16 ret = NULL;
404 if (__winelib)
406 /* FIXME: hack for Winelib */
407 extern LRESULT ColorDlgProc16(HWND16,UINT16,WPARAM16,LPARAM);
408 extern LRESULT FileOpenDlgProc16(HWND16,UINT16,WPARAM16,LPARAM);
409 extern LRESULT FileSaveDlgProc16(HWND16,UINT16,WPARAM16,LPARAM);
410 extern LRESULT FindTextDlgProc16(HWND16,UINT16,WPARAM16,LPARAM);
411 extern LRESULT PrintDlgProc16(HWND16,UINT16,WPARAM16,LPARAM);
412 extern LRESULT PrintSetupDlgProc16(HWND16,UINT16,WPARAM16,LPARAM);
413 extern LRESULT ReplaceTextDlgProc16(HWND16,UINT16,WPARAM16,LPARAM);
415 if (!strcmp(name,"ColorDlgProc"))
416 return (FARPROC16)ColorDlgProc16;
417 if (!strcmp(name,"FileOpenDlgProc"))
418 return (FARPROC16)FileOpenDlgProc16;
419 if (!strcmp(name,"FileSaveDlgProc"))
420 return (FARPROC16)FileSaveDlgProc16;
421 if (!strcmp(name,"FindTextDlgProc"))
422 return (FARPROC16)FindTextDlgProc16;
423 if (!strcmp(name,"PrintDlgProc"))
424 return (FARPROC16)PrintDlgProc16;
425 if (!strcmp(name,"PrintSetupDlgProc"))
426 return (FARPROC16)PrintSetupDlgProc16;
427 if (!strcmp(name,"ReplaceTextDlgProc"))
428 return (FARPROC16)ReplaceTextDlgProc16;
429 FIXME_(module)("No mapping for %s(), add one in library/miscstubs.c\n",name);
430 assert( FALSE );
431 return NULL;
433 else
435 WORD ordinal;
436 static HMODULE hModule = 0;
438 if (!hModule) hModule = GetModuleHandle16( "WPROCS" );
439 ordinal = NE_GetOrdinal( hModule, name );
440 if (!(ret = NE_GetEntryPoint( hModule, ordinal )))
442 WARN_(module)("%s not found\n", name );
443 assert( FALSE );
446 return ret;
450 /**********************************************************************
451 * MODULE_FindModule32
453 * Find a (loaded) win32 module depending on path
454 * The handling of '.' is a bit weird, but we need it that way,
455 * for sometimes the programs use '<name>.exe' and '<name>.dll' and
456 * this is the only way to differentiate. (mainly hypertrm.exe)
458 * RETURNS
459 * the module handle if found
460 * 0 if not
462 WINE_MODREF *MODULE_FindModule(
463 LPCSTR path /* [in] pathname of module/library to be found */
465 LPSTR filename;
466 LPSTR dotptr;
467 WINE_MODREF *wm;
469 if (!(filename = strrchr( path, '\\' )))
470 filename = HEAP_strdupA( GetProcessHeap(), 0, path );
471 else
472 filename = HEAP_strdupA( GetProcessHeap(), 0, filename+1 );
473 dotptr=strrchr(filename,'.');
475 for ( wm = PROCESS_Current()->modref_list; wm; wm=wm->next ) {
476 LPSTR xmodname,xdotptr;
478 assert (wm->modname);
479 xmodname = HEAP_strdupA( GetProcessHeap(), 0, wm->modname );
480 xdotptr=strrchr(xmodname,'.');
481 if ( (xdotptr && !dotptr) ||
482 (!xdotptr && dotptr)
484 if (dotptr) *dotptr = '\0';
485 if (xdotptr) *xdotptr = '\0';
487 if (!strcasecmp( filename, xmodname)) {
488 HeapFree( GetProcessHeap(), 0, filename );
489 HeapFree( GetProcessHeap(), 0, xmodname );
490 return wm;
492 if (dotptr) *dotptr='.';
493 /* FIXME: add paths, shortname */
494 HeapFree( GetProcessHeap(), 0, xmodname );
496 /* if that fails, try looking for the filename... */
497 for ( wm = PROCESS_Current()->modref_list; wm; wm=wm->next ) {
498 LPSTR xlname,xdotptr;
500 assert (wm->longname);
501 xlname = strrchr(wm->longname,'\\');
502 if (!xlname)
503 xlname = wm->longname;
504 else
505 xlname++;
506 xlname = HEAP_strdupA( GetProcessHeap(), 0, xlname );
507 xdotptr=strrchr(xlname,'.');
508 if ( (xdotptr && !dotptr) ||
509 (!xdotptr && dotptr)
511 if (dotptr) *dotptr = '\0';
512 if (xdotptr) *xdotptr = '\0';
514 if (!strcasecmp( filename, xlname)) {
515 HeapFree( GetProcessHeap(), 0, filename );
516 HeapFree( GetProcessHeap(), 0, xlname );
517 return wm;
519 if (dotptr) *dotptr='.';
520 /* FIXME: add paths, shortname */
521 HeapFree( GetProcessHeap(), 0, xlname );
523 HeapFree( GetProcessHeap(), 0, filename );
524 return NULL;
527 /***********************************************************************
528 * MODULE_GetBinaryType
530 * The GetBinaryType function determines whether a file is executable
531 * or not and if it is it returns what type of executable it is.
532 * The type of executable is a property that determines in which
533 * subsystem an executable file runs under.
535 * Binary types returned:
536 * SCS_32BIT_BINARY: A Win32 based application
537 * SCS_DOS_BINARY: An MS-Dos based application
538 * SCS_WOW_BINARY: A Win16 based application
539 * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
540 * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
541 * SCS_OS216_BINARY: A 16bit OS/2 based application ( Not implemented )
543 * Returns TRUE if the file is an executable in which case
544 * the value pointed by lpBinaryType is set.
545 * Returns FALSE if the file is not an executable or if the function fails.
547 * To do so it opens the file and reads in the header information
548 * if the extended header information is not presend it will
549 * assume that that the file is a DOS executable.
550 * If the extended header information is present it will
551 * determine if the file is an 16 or 32 bit Windows executable
552 * by check the flags in the header.
554 * Note that .COM and .PIF files are only recognized by their
555 * file name extension; but Windows does it the same way ...
557 static BOOL MODULE_GetBinaryType( HFILE hfile, OFSTRUCT *ofs,
558 LPDWORD lpBinaryType )
560 IMAGE_DOS_HEADER mz_header;
561 char magic[4], *ptr;
563 /* Seek to the start of the file and read the DOS header information.
565 if ( _llseek( hfile, 0, SEEK_SET ) >= 0 &&
566 _lread( hfile, &mz_header, sizeof(mz_header) ) == sizeof(mz_header) )
568 /* Now that we have the header check the e_magic field
569 * to see if this is a dos image.
571 if ( mz_header.e_magic == IMAGE_DOS_SIGNATURE )
573 BOOL lfanewValid = FALSE;
574 /* We do have a DOS image so we will now try to seek into
575 * the file by the amount indicated by the field
576 * "Offset to extended header" and read in the
577 * "magic" field information at that location.
578 * This will tell us if there is more header information
579 * to read or not.
581 /* But before we do we will make sure that header
582 * structure encompasses the "Offset to extended header"
583 * field.
585 if ( (mz_header.e_cparhdr<<4) >= sizeof(IMAGE_DOS_HEADER) )
586 if ( ( mz_header.e_crlc == 0 && mz_header.e_lfarlc == 0 ) ||
587 ( mz_header.e_lfarlc >= sizeof(IMAGE_DOS_HEADER) ) )
588 if ( mz_header.e_lfanew >= sizeof(IMAGE_DOS_HEADER) &&
589 _llseek( hfile, mz_header.e_lfanew, SEEK_SET ) >= 0 &&
590 _lread( hfile, magic, sizeof(magic) ) == sizeof(magic) )
591 lfanewValid = TRUE;
593 if ( !lfanewValid )
595 /* If we cannot read this "extended header" we will
596 * assume that we have a simple DOS executable.
598 *lpBinaryType = SCS_DOS_BINARY;
599 return TRUE;
601 else
603 /* Reading the magic field succeeded so
604 * we will try to determine what type it is.
606 if ( *(DWORD*)magic == IMAGE_NT_SIGNATURE )
608 /* This is an NT signature.
610 *lpBinaryType = SCS_32BIT_BINARY;
611 return TRUE;
613 else if ( *(WORD*)magic == IMAGE_OS2_SIGNATURE )
615 /* The IMAGE_OS2_SIGNATURE indicates that the
616 * "extended header is a Windows executable (NE)
617 * header. This is a bit misleading, but it is
618 * documented in the SDK. ( for more details see
619 * the neexe.h file )
621 *lpBinaryType = SCS_WOW_BINARY;
622 return TRUE;
624 else
626 /* Unknown extended header, so abort.
628 return FALSE;
634 /* If we get here, we don't even have a correct MZ header.
635 * Try to check the file extension for known types ...
637 ptr = strrchr( ofs->szPathName, '.' );
638 if ( ptr && !strchr( ptr, '\\' ) && !strchr( ptr, '/' ) )
640 if ( !lstrcmpiA( ptr, ".COM" ) )
642 *lpBinaryType = SCS_DOS_BINARY;
643 return TRUE;
646 if ( !lstrcmpiA( ptr, ".PIF" ) )
648 *lpBinaryType = SCS_PIF_BINARY;
649 return TRUE;
653 return FALSE;
656 /***********************************************************************
657 * GetBinaryTypeA [KERNEL32.280]
659 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
661 BOOL ret = FALSE;
662 HFILE hfile;
663 OFSTRUCT ofs;
665 TRACE_(win32)("%s\n", lpApplicationName );
667 /* Sanity check.
669 if ( lpApplicationName == NULL || lpBinaryType == NULL )
670 return FALSE;
672 /* Open the file indicated by lpApplicationName for reading.
674 if ( (hfile = OpenFile( lpApplicationName, &ofs, OF_READ )) == HFILE_ERROR )
675 return FALSE;
677 /* Check binary type
679 ret = MODULE_GetBinaryType( hfile, &ofs, lpBinaryType );
681 /* Close the file.
683 CloseHandle( hfile );
685 return ret;
688 /***********************************************************************
689 * GetBinaryTypeW [KERNEL32.281]
691 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
693 BOOL ret = FALSE;
694 LPSTR strNew = NULL;
696 TRACE_(win32)("%s\n", debugstr_w(lpApplicationName) );
698 /* Sanity check.
700 if ( lpApplicationName == NULL || lpBinaryType == NULL )
701 return FALSE;
703 /* Convert the wide string to a ascii string.
705 strNew = HEAP_strdupWtoA( GetProcessHeap(), 0, lpApplicationName );
707 if ( strNew != NULL )
709 ret = GetBinaryTypeA( strNew, lpBinaryType );
711 /* Free the allocated string.
713 HeapFree( GetProcessHeap(), 0, strNew );
716 return ret;
719 /**********************************************************************
720 * MODULE_CreateUnixProcess
722 static BOOL MODULE_CreateUnixProcess( LPCSTR filename, LPCSTR lpCmdLine,
723 LPSTARTUPINFOA lpStartupInfo,
724 LPPROCESS_INFORMATION lpProcessInfo,
725 BOOL useWine )
727 DOS_FULL_NAME full_name;
728 const char *unixfilename = filename;
729 const char *argv[256], **argptr;
730 BOOL iconic = FALSE;
732 /* Get Unix file name and iconic flag */
734 if ( lpStartupInfo->dwFlags & STARTF_USESHOWWINDOW )
735 if ( lpStartupInfo->wShowWindow == SW_SHOWMINIMIZED
736 || lpStartupInfo->wShowWindow == SW_SHOWMINNOACTIVE )
737 iconic = TRUE;
739 if ( strchr(filename, '/')
740 || strchr(filename, ':')
741 || strchr(filename, '\\') )
743 if ( DOSFS_GetFullName( filename, TRUE, &full_name ) )
744 unixfilename = full_name.long_name;
747 if ( !unixfilename )
749 SetLastError( ERROR_FILE_NOT_FOUND );
750 return FALSE;
753 /* Build argument list */
755 argptr = argv;
756 if ( !useWine )
758 char *p = strdup(lpCmdLine);
759 *argptr++ = unixfilename;
760 if (iconic) *argptr++ = "-iconic";
761 while (1)
763 while (*p && (*p == ' ' || *p == '\t')) *p++ = '\0';
764 if (!*p) break;
765 *argptr++ = p;
766 while (*p && *p != ' ' && *p != '\t') p++;
769 else
771 *argptr++ = "wine";
772 if (iconic) *argptr++ = "-iconic";
773 *argptr++ = lpCmdLine;
775 *argptr++ = 0;
777 /* Fork and execute */
779 if ( !fork() )
781 /* Note: don't use Wine routines here, as this process
782 has not been correctly initialized! */
784 execvp( argv[0], (char**)argv );
786 /* Failed ! */
787 if ( useWine )
788 fprintf( stderr, "CreateProcess: can't exec 'wine %s'\n",
789 lpCmdLine );
790 exit( 1 );
793 /* Fake success return value */
795 memset( lpProcessInfo, '\0', sizeof( *lpProcessInfo ) );
796 lpProcessInfo->hProcess = INVALID_HANDLE_VALUE;
797 lpProcessInfo->hThread = INVALID_HANDLE_VALUE;
799 SetLastError( ERROR_SUCCESS );
800 return TRUE;
803 /***********************************************************************
804 * WinExec16 (KERNEL.166)
806 HINSTANCE16 WINAPI WinExec16( LPCSTR lpCmdLine, UINT16 nCmdShow )
808 HINSTANCE16 hInst;
810 SYSLEVEL_ReleaseWin16Lock();
811 hInst = WinExec( lpCmdLine, nCmdShow );
812 SYSLEVEL_RestoreWin16Lock();
814 return hInst;
817 /***********************************************************************
818 * WinExec (KERNEL32.566)
820 HINSTANCE WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
822 LOADPARAMS params;
823 UINT16 paramCmdShow[2];
825 if (!lpCmdLine)
826 return 2; /* File not found */
828 /* Set up LOADPARAMS buffer for LoadModule */
830 memset( &params, '\0', sizeof(params) );
831 params.lpCmdLine = (LPSTR)lpCmdLine;
832 params.lpCmdShow = paramCmdShow;
833 params.lpCmdShow[0] = 2;
834 params.lpCmdShow[1] = nCmdShow;
836 /* Now load the executable file */
838 return LoadModule( NULL, &params );
841 /**********************************************************************
842 * LoadModule (KERNEL32.499)
844 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
846 LOADPARAMS *params = (LOADPARAMS *)paramBlock;
847 PROCESS_INFORMATION info;
848 STARTUPINFOA startup;
849 HINSTANCE hInstance;
850 PDB *pdb;
851 TDB *tdb;
853 memset( &startup, '\0', sizeof(startup) );
854 startup.cb = sizeof(startup);
855 startup.dwFlags = STARTF_USESHOWWINDOW;
856 startup.wShowWindow = params->lpCmdShow? params->lpCmdShow[1] : 0;
858 if ( !CreateProcessA( name, params->lpCmdLine,
859 NULL, NULL, FALSE, 0, params->lpEnvAddress,
860 NULL, &startup, &info ) )
862 hInstance = GetLastError();
863 if ( hInstance < 32 ) return hInstance;
865 FIXME_(module)("Strange error set by CreateProcess: %d\n", hInstance );
866 return 11;
869 /* Get 16-bit hInstance/hTask from process */
870 pdb = PROCESS_IdToPDB( info.dwProcessId );
871 tdb = pdb? (TDB *)GlobalLock16( pdb->task ) : NULL;
872 hInstance = tdb && tdb->hInstance? tdb->hInstance : pdb? pdb->task : 0;
873 /* If there is no hInstance (32-bit process) return a dummy value
874 * that must be > 31
875 * FIXME: should do this in all cases and fix Win16 callers */
876 if (!hInstance) hInstance = 33;
878 /* Close off the handles */
879 CloseHandle( info.hThread );
880 CloseHandle( info.hProcess );
882 return hInstance;
885 /*************************************************************************
886 * get_executable_name
888 * Try longer and longer strings from "line" to find an existing
889 * file name. Each attempt is delimited by a blank outside of quotes.
890 * Also will attempt to append ".exe" if requested and not already
891 * present. Returns the address of the remaining portion of the
892 * input line.
896 static void get_executable_name( LPCSTR line, LPSTR name, int namelen,
897 LPCSTR *after, BOOL extension )
899 LPCSTR pcmd = NULL;
900 LPCSTR from;
901 LPSTR to, to_end, to_old;
902 HFILE hFile;
903 OFSTRUCT ofs;
905 to = name;
906 to_end = to + namelen - 1;
907 to_old = to;
909 while ( *line == ' ' ) line++; /* point to beginning of string */
910 from = line;
911 pcmd = from;
912 do {
913 /* Copy all input till end, blank, or quote */
914 while((*from != 0) && (*from != ' ') && (*from != '"') && (to < to_end))
915 *to++ = *from++;
916 if (to >= to_end) { *to = 0; pcmd = from; break; }
918 if (*from == '"')
920 /* Handle quoted string. If there is a closing quote, copy all */
921 /* that is inside. */
922 from++;
923 if (!strchr(from, '"'))
925 /* fail - no closing quote */
926 to = to_old; /* restore to previous attempt */
927 *to = 0; /* end string */
928 break; /* exit with previous attempt */
930 while((*from != '"') && (to < to_end)) *to++ = *from++;
931 if (to >= to_end) { *to = 0; pcmd = from; break; }
932 from++;
933 continue; /* past quoted string, so restart from top */
936 *to = 0; /* terminate output string */
937 to_old = to; /* save for possible use in unmatched quote case */
938 pcmd = from;
940 /* Input termination is a blank. Try this file name */
942 /* Append ".exe" if necessary and space permits */
943 if ( (to-name) < namelen-4)
945 if(extension && (strrchr(name, '.') <= strrchr(name, '\\')) )
946 strcat(name, ".exe");
949 TRACE_(module)("checking if file exists '%s'\n", name);
951 if ((hFile = OpenFile( name, &ofs, OF_READ )) != HFILE_ERROR)
953 CloseHandle( hFile );
954 break; /* if file exists then all done */
957 /* loop around keeping the blank as part of file name */
958 if (!*from)
959 break; /* exit if out of input string */
961 *to++ = *from++; /* move in blank and restart */
962 } while (1);
964 if (after) *after = pcmd;
965 TRACE_(module)("selected as file name '%s'\n and cmdline as %s\n",
966 name, debugstr_a(pcmd));
969 /*************************************************************************
970 * make_executable_name
972 * Scan input string (the lpApplicationName) and remove any quotes
973 * if they are balanced. Also will attempt to append ".exe" if requested
974 * and not already present.
978 static void make_executable_name( LPCSTR line, LPSTR name, int namelen,
979 BOOL extension )
981 LPCSTR from;
982 LPSTR to, to_end, to_old;
984 to = name;
985 to_end = to + namelen - 1;
986 to_old = to;
988 while ( *line == ' ' ) line++; /* point to beginning of string */
989 from = line;
990 do {
991 /* Copy all input till end, blank, or quote */
992 while((*from != 0) && (*from != '"') && (to < to_end))
993 *to++ = *from++;
994 if (to >= to_end) { *to = 0; break; }
996 if (*from == '"')
998 /* Handle quoted string. If there is a closing quote, copy all */
999 /* that is inside. */
1000 from++;
1001 if (!strchr(from, '"'))
1003 /* fail - no closing quote */
1004 to = to_old; /* restore to previous attempt */
1005 *to = 0; /* end string */
1006 break; /* exit with previous attempt */
1008 while((*from != '"') && (to < to_end)) *to++ = *from++;
1009 if (to >= to_end) { *to = 0; break; }
1010 from++;
1011 continue; /* past quoted string, so restart from top */
1014 *to = 0; /* terminate output string */
1015 to_old = to; /* save for possible use in unmatched quote case */
1017 /* loop around keeping the blank as part of file name */
1018 if (!*from)
1019 break; /* exit if out of input string */
1021 *to++ = *from++; /* move in blank and restart */
1022 } while (1);
1024 /* Append ".exe" if necessary and space permits */
1025 if ( (to-name) < namelen-4)
1027 if(extension && (strrchr(name, '.') <= strrchr(name, '\\')) )
1028 strcat(name, ".exe");
1031 TRACE_(module)("selected as file name '%s'\n", name );
1034 /**********************************************************************
1035 * CreateProcessA (KERNEL32.171)
1037 BOOL WINAPI CreateProcessA( LPCSTR lpApplicationName, LPSTR lpCommandLine,
1038 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1039 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1040 BOOL bInheritHandles, DWORD dwCreationFlags,
1041 LPVOID lpEnvironment, LPCSTR lpCurrentDirectory,
1042 LPSTARTUPINFOA lpStartupInfo,
1043 LPPROCESS_INFORMATION lpProcessInfo )
1045 BOOL retv = FALSE;
1046 HFILE hFile;
1047 OFSTRUCT ofs;
1048 DWORD type;
1049 char name[256];
1050 LPCSTR cmdline = NULL;
1052 /* Get name and command line */
1054 if (!lpApplicationName && !lpCommandLine)
1056 SetLastError( ERROR_FILE_NOT_FOUND );
1057 return FALSE;
1060 name[0] = '\0';
1062 if (lpApplicationName) {
1063 make_executable_name( lpApplicationName, name, sizeof(name), TRUE );
1064 cmdline = (lpCommandLine) ? lpCommandLine : lpApplicationName ;
1066 else {
1067 get_executable_name( lpCommandLine, name, sizeof ( name ), &cmdline, TRUE );
1070 /* Warn if unsupported features are used */
1072 if (dwCreationFlags & DEBUG_PROCESS)
1073 FIXME_(module)("(%s,...): DEBUG_PROCESS ignored\n", name);
1074 if (dwCreationFlags & DEBUG_ONLY_THIS_PROCESS)
1075 FIXME_(module)("(%s,...): DEBUG_ONLY_THIS_PROCESS ignored\n", name);
1076 if (dwCreationFlags & CREATE_SUSPENDED)
1077 FIXME_(module)("(%s,...): CREATE_SUSPENDED ignored\n", name);
1078 if (dwCreationFlags & DETACHED_PROCESS)
1079 FIXME_(module)("(%s,...): DETACHED_PROCESS ignored\n", name);
1080 if (dwCreationFlags & CREATE_NEW_CONSOLE)
1081 FIXME_(module)("(%s,...): CREATE_NEW_CONSOLE ignored\n", name);
1082 if (dwCreationFlags & NORMAL_PRIORITY_CLASS)
1083 FIXME_(module)("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
1084 if (dwCreationFlags & IDLE_PRIORITY_CLASS)
1085 FIXME_(module)("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
1086 if (dwCreationFlags & HIGH_PRIORITY_CLASS)
1087 FIXME_(module)("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
1088 if (dwCreationFlags & REALTIME_PRIORITY_CLASS)
1089 FIXME_(module)("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
1090 if (dwCreationFlags & CREATE_NEW_PROCESS_GROUP)
1091 FIXME_(module)("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
1092 if (dwCreationFlags & CREATE_UNICODE_ENVIRONMENT)
1093 FIXME_(module)("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
1094 if (dwCreationFlags & CREATE_SEPARATE_WOW_VDM)
1095 FIXME_(module)("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
1096 if (dwCreationFlags & CREATE_SHARED_WOW_VDM)
1097 FIXME_(module)("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
1098 if (dwCreationFlags & CREATE_DEFAULT_ERROR_MODE)
1099 FIXME_(module)("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
1100 if (dwCreationFlags & CREATE_NO_WINDOW)
1101 FIXME_(module)("(%s,...): CREATE_NO_WINDOW ignored\n", name);
1102 if (dwCreationFlags & PROFILE_USER)
1103 FIXME_(module)("(%s,...): PROFILE_USER ignored\n", name);
1104 if (dwCreationFlags & PROFILE_KERNEL)
1105 FIXME_(module)("(%s,...): PROFILE_KERNEL ignored\n", name);
1106 if (dwCreationFlags & PROFILE_SERVER)
1107 FIXME_(module)("(%s,...): PROFILE_SERVER ignored\n", name);
1108 if (lpCurrentDirectory)
1109 FIXME_(module)("(%s,...): lpCurrentDirectory %s ignored\n",
1110 name, lpCurrentDirectory);
1111 if (lpStartupInfo->lpDesktop)
1112 FIXME_(module)("(%s,...): lpStartupInfo->lpDesktop %s ignored\n",
1113 name, lpStartupInfo->lpDesktop);
1114 if (lpStartupInfo->lpTitle)
1115 FIXME_(module)("(%s,...): lpStartupInfo->lpTitle %s ignored\n",
1116 name, lpStartupInfo->lpTitle);
1117 if (lpStartupInfo->dwFlags & STARTF_USECOUNTCHARS)
1118 FIXME_(module)("(%s,...): STARTF_USECOUNTCHARS (%ld,%ld) ignored\n",
1119 name, lpStartupInfo->dwXCountChars, lpStartupInfo->dwYCountChars);
1120 if (lpStartupInfo->dwFlags & STARTF_USEFILLATTRIBUTE)
1121 FIXME_(module)("(%s,...): STARTF_USEFILLATTRIBUTE %lx ignored\n",
1122 name, lpStartupInfo->dwFillAttribute);
1123 if (lpStartupInfo->dwFlags & STARTF_RUNFULLSCREEN)
1124 FIXME_(module)("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
1125 if (lpStartupInfo->dwFlags & STARTF_FORCEONFEEDBACK)
1126 FIXME_(module)("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
1127 if (lpStartupInfo->dwFlags & STARTF_FORCEOFFFEEDBACK)
1128 FIXME_(module)("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
1129 if (lpStartupInfo->dwFlags & STARTF_USEHOTKEY)
1130 FIXME_(module)("(%s,...): STARTF_USEHOTKEY ignored\n", name);
1133 /* When in WineLib, always fork new Unix process */
1135 if ( __winelib )
1136 return MODULE_CreateUnixProcess( name, cmdline,
1137 lpStartupInfo, lpProcessInfo, TRUE );
1139 /* Check for special case: second instance of NE module */
1141 lstrcpynA( ofs.szPathName, name, sizeof( ofs.szPathName ) );
1142 retv = NE_CreateProcess( HFILE_ERROR, &ofs, cmdline, lpEnvironment,
1143 lpProcessAttributes, lpThreadAttributes,
1144 bInheritHandles, lpStartupInfo, lpProcessInfo );
1146 /* Load file and create process */
1148 if ( !retv )
1150 /* Open file and determine executable type */
1152 if ( (hFile = OpenFile( name, &ofs, OF_READ )) == HFILE_ERROR )
1154 SetLastError( ERROR_FILE_NOT_FOUND );
1155 return FALSE;
1158 if ( !MODULE_GetBinaryType( hFile, &ofs, &type ) )
1160 CloseHandle( hFile );
1162 /* FIXME: Try Unix executable only when appropriate! */
1163 if ( MODULE_CreateUnixProcess( name, cmdline,
1164 lpStartupInfo, lpProcessInfo, FALSE ) )
1165 return TRUE;
1167 SetLastError( ERROR_BAD_FORMAT );
1168 return FALSE;
1172 /* Create process */
1174 switch ( type )
1176 case SCS_32BIT_BINARY:
1177 retv = PE_CreateProcess( hFile, &ofs, cmdline, lpEnvironment,
1178 lpProcessAttributes, lpThreadAttributes,
1179 bInheritHandles, lpStartupInfo, lpProcessInfo );
1180 break;
1182 case SCS_DOS_BINARY:
1183 retv = MZ_CreateProcess( hFile, &ofs, cmdline, lpEnvironment,
1184 lpProcessAttributes, lpThreadAttributes,
1185 bInheritHandles, lpStartupInfo, lpProcessInfo );
1186 break;
1188 case SCS_WOW_BINARY:
1189 retv = NE_CreateProcess( hFile, &ofs, cmdline, lpEnvironment,
1190 lpProcessAttributes, lpThreadAttributes,
1191 bInheritHandles, lpStartupInfo, lpProcessInfo );
1192 break;
1194 case SCS_PIF_BINARY:
1195 case SCS_POSIX_BINARY:
1196 case SCS_OS216_BINARY:
1197 FIXME_(module)("Unsupported executable type: %ld\n", type );
1198 /* fall through */
1200 default:
1201 SetLastError( ERROR_BAD_FORMAT );
1202 retv = FALSE;
1203 break;
1206 CloseHandle( hFile );
1208 return retv;
1211 /**********************************************************************
1212 * CreateProcessW (KERNEL32.172)
1213 * NOTES
1214 * lpReserved is not converted
1216 BOOL WINAPI CreateProcessW( LPCWSTR lpApplicationName, LPWSTR lpCommandLine,
1217 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1218 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1219 BOOL bInheritHandles, DWORD dwCreationFlags,
1220 LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory,
1221 LPSTARTUPINFOW lpStartupInfo,
1222 LPPROCESS_INFORMATION lpProcessInfo )
1223 { BOOL ret;
1224 STARTUPINFOA StartupInfoA;
1226 LPSTR lpApplicationNameA = HEAP_strdupWtoA (GetProcessHeap(),0,lpApplicationName);
1227 LPSTR lpCommandLineA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCommandLine);
1228 LPSTR lpCurrentDirectoryA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCurrentDirectory);
1230 memcpy (&StartupInfoA, lpStartupInfo, sizeof(STARTUPINFOA));
1231 StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpDesktop);
1232 StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpTitle);
1234 TRACE_(win32)("(%s,%s,...)\n", debugstr_w(lpApplicationName), debugstr_w(lpCommandLine));
1236 if (lpStartupInfo->lpReserved)
1237 FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n", debugstr_w(lpStartupInfo->lpReserved));
1239 ret = CreateProcessA( lpApplicationNameA, lpCommandLineA,
1240 lpProcessAttributes, lpThreadAttributes,
1241 bInheritHandles, dwCreationFlags,
1242 lpEnvironment, lpCurrentDirectoryA,
1243 &StartupInfoA, lpProcessInfo );
1245 HeapFree( GetProcessHeap(), 0, lpCurrentDirectoryA );
1246 HeapFree( GetProcessHeap(), 0, lpCommandLineA );
1247 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1248 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1250 return ret;
1253 /***********************************************************************
1254 * GetModuleHandle (KERNEL32.237)
1256 HMODULE WINAPI GetModuleHandleA(LPCSTR module)
1258 WINE_MODREF *wm;
1260 if ( module == NULL )
1261 wm = PROCESS_Current()->exe_modref;
1262 else
1263 wm = MODULE_FindModule( module );
1265 return wm? wm->module : 0;
1268 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
1270 HMODULE hModule;
1271 LPSTR modulea = HEAP_strdupWtoA( GetProcessHeap(), 0, module );
1272 hModule = GetModuleHandleA( modulea );
1273 HeapFree( GetProcessHeap(), 0, modulea );
1274 return hModule;
1278 /***********************************************************************
1279 * GetModuleFileName32A (KERNEL32.235)
1281 DWORD WINAPI GetModuleFileNameA(
1282 HMODULE hModule, /* [in] module handle (32bit) */
1283 LPSTR lpFileName, /* [out] filenamebuffer */
1284 DWORD size /* [in] size of filenamebuffer */
1285 ) {
1286 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1288 if (!wm) /* can happen on start up or the like */
1289 return 0;
1291 if (PE_HEADER(wm->module)->OptionalHeader.MajorOperatingSystemVersion >= 4.0)
1292 lstrcpynA( lpFileName, wm->longname, size );
1293 else
1294 lstrcpynA( lpFileName, wm->shortname, size );
1296 TRACE_(module)("%s\n", lpFileName );
1297 return strlen(lpFileName);
1301 /***********************************************************************
1302 * GetModuleFileName32W (KERNEL32.236)
1304 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName,
1305 DWORD size )
1307 LPSTR fnA = (char*)HeapAlloc( GetProcessHeap(), 0, size );
1308 DWORD res = GetModuleFileNameA( hModule, fnA, size );
1309 lstrcpynAtoW( lpFileName, fnA, size );
1310 HeapFree( GetProcessHeap(), 0, fnA );
1311 return res;
1315 /***********************************************************************
1316 * LoadLibraryEx32W (KERNEL.513)
1318 HMODULE WINAPI LoadLibraryEx32W16( LPCSTR libname, HANDLE16 hf,
1319 DWORD flags )
1321 HMODULE hModule;
1323 SYSLEVEL_ReleaseWin16Lock();
1324 hModule = LoadLibraryExA( libname, hf, flags );
1325 SYSLEVEL_RestoreWin16Lock();
1327 return hModule;
1330 /***********************************************************************
1331 * LoadLibrary32_16 (KERNEL.452)
1333 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
1335 return LoadLibraryEx32W16( libname, 0, 0 );
1338 /***********************************************************************
1339 * LoadLibraryExA (KERNEL32)
1341 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HFILE hfile, DWORD flags)
1343 WINE_MODREF *wm;
1345 if(!libname)
1347 SetLastError(ERROR_INVALID_PARAMETER);
1348 return 0;
1351 EnterCriticalSection(&PROCESS_Current()->crit_section);
1353 wm = MODULE_LoadLibraryExA( libname, hfile, flags );
1355 if(wm && !MODULE_DllProcessAttach(wm, NULL))
1357 WARN_(module)("Attach failed for module '%s', \n", libname);
1358 MODULE_FreeLibrary(wm);
1359 SetLastError(ERROR_DLL_INIT_FAILED);
1360 wm = NULL;
1363 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1365 return wm ? wm->module : 0;
1368 /***********************************************************************
1369 * MODULE_LoadLibraryExA (internal)
1371 * Load a PE style module according to the load order.
1373 * The HFILE parameter is not used and marked reserved in the SDK. I can
1374 * only guess that it should force a file to be mapped, but I rather
1375 * ignore the parameter because it would be extremely difficult to
1376 * integrate this with different types of module represenations.
1379 WINE_MODREF *MODULE_LoadLibraryExA( LPCSTR libname, HFILE hfile, DWORD flags )
1381 DWORD err;
1382 WINE_MODREF *pwm;
1383 int i;
1384 module_loadorder_t *plo;
1386 EnterCriticalSection(&PROCESS_Current()->crit_section);
1388 /* Check for already loaded module */
1389 if((pwm = MODULE_FindModule(libname)))
1391 if(!(pwm->flags & WINE_MODREF_MARKER))
1392 pwm->refCount++;
1393 TRACE_(module)("Already loaded module '%s' at 0x%08x, count=%d, \n", libname, pwm->module, pwm->refCount);
1394 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1395 return pwm;
1398 plo = MODULE_GetLoadOrder(libname);
1400 for(i = 0; i < MODULE_LOADORDER_NTYPES; i++)
1402 switch(plo->loadorder[i])
1404 case MODULE_LOADORDER_DLL:
1405 TRACE_(module)("Trying native dll '%s'\n", libname);
1406 pwm = PE_LoadLibraryExA(libname, flags, &err);
1407 break;
1409 case MODULE_LOADORDER_ELFDLL:
1410 TRACE_(module)("Trying elfdll '%s'\n", libname);
1411 pwm = ELFDLL_LoadLibraryExA(libname, flags, &err);
1412 break;
1414 case MODULE_LOADORDER_SO:
1415 TRACE_(module)("Trying so-library '%s'\n", libname);
1416 pwm = ELF_LoadLibraryExA(libname, flags, &err);
1417 break;
1419 case MODULE_LOADORDER_BI:
1420 TRACE_(module)("Trying built-in '%s'\n", libname);
1421 pwm = BUILTIN32_LoadLibraryExA(libname, flags, &err);
1422 break;
1424 default:
1425 ERR_(module)("Got invalid loadorder type %d (%s index %d)\n", plo->loadorder[i], plo->modulename, i);
1426 /* Fall through */
1428 case MODULE_LOADORDER_INVALID: /* We ignore this as it is an empty entry */
1429 pwm = NULL;
1430 break;
1433 if(pwm)
1435 /* Initialize DLL just loaded */
1436 TRACE_(module)("Loaded module '%s' at 0x%08x, \n", libname, pwm->module);
1438 /* Set the refCount here so that an attach failure will */
1439 /* decrement the dependencies through the MODULE_FreeLibrary call. */
1440 pwm->refCount++;
1442 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1443 return pwm;
1446 if(err != ERROR_FILE_NOT_FOUND)
1447 break;
1450 ERR_(module)("Failed to load module '%s'; error=0x%08lx, \n", libname, err);
1451 SetLastError(err);
1452 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1453 return NULL;
1456 /***********************************************************************
1457 * LoadLibraryA (KERNEL32)
1459 HMODULE WINAPI LoadLibraryA(LPCSTR libname) {
1460 return LoadLibraryExA(libname,0,0);
1463 /***********************************************************************
1464 * LoadLibraryW (KERNEL32)
1466 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
1468 return LoadLibraryExW(libnameW,0,0);
1471 /***********************************************************************
1472 * LoadLibraryExW (KERNEL32)
1474 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW,HFILE hfile,DWORD flags)
1476 LPSTR libnameA = HEAP_strdupWtoA( GetProcessHeap(), 0, libnameW );
1477 HMODULE ret = LoadLibraryExA( libnameA , hfile, flags );
1479 HeapFree( GetProcessHeap(), 0, libnameA );
1480 return ret;
1483 /***********************************************************************
1484 * MODULE_FlushModrefs
1486 * NOTE: Assumes that the process critical section is held!
1488 * Remove all unused modrefs and call the internal unloading routines
1489 * for the library type.
1491 static void MODULE_FlushModrefs(void)
1493 WINE_MODREF *wm, *next;
1495 for(wm = PROCESS_Current()->modref_list; wm; wm = next)
1497 next = wm->next;
1499 if(wm->refCount)
1500 continue;
1502 /* Unlink this modref from the chain */
1503 if(wm->next)
1504 wm->next->prev = wm->prev;
1505 if(wm->prev)
1506 wm->prev->next = wm->next;
1507 if(wm == PROCESS_Current()->modref_list)
1508 PROCESS_Current()->modref_list = wm->next;
1511 * The unloaders are also responsible for freeing the modref itself
1512 * because the loaders were responsible for allocating it.
1514 switch(wm->type)
1516 case MODULE32_PE: PE_UnloadLibrary(wm); break;
1517 case MODULE32_ELF: ELF_UnloadLibrary(wm); break;
1518 case MODULE32_ELFDLL: ELFDLL_UnloadLibrary(wm); break;
1519 case MODULE32_BI: BUILTIN32_UnloadLibrary(wm); break;
1521 default:
1522 ERR_(module)("Invalid or unhandled MODREF type %d encountered (wm=%p)\n", wm->type, wm);
1527 /***********************************************************************
1528 * FreeLibrary
1530 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
1532 BOOL retv = FALSE;
1533 WINE_MODREF *wm;
1535 EnterCriticalSection( &PROCESS_Current()->crit_section );
1536 PROCESS_Current()->free_lib_count++;
1538 wm = MODULE32_LookupHMODULE( hLibModule );
1539 if ( !wm || !hLibModule )
1540 SetLastError( ERROR_INVALID_HANDLE );
1541 else
1542 retv = MODULE_FreeLibrary( wm );
1544 PROCESS_Current()->free_lib_count--;
1545 LeaveCriticalSection( &PROCESS_Current()->crit_section );
1547 return retv;
1550 /***********************************************************************
1551 * MODULE_DecRefCount
1553 * NOTE: Assumes that the process critical section is held!
1555 static void MODULE_DecRefCount( WINE_MODREF *wm )
1557 int i;
1559 if ( wm->flags & WINE_MODREF_MARKER )
1560 return;
1562 if ( wm->refCount <= 0 )
1563 return;
1565 --wm->refCount;
1566 TRACE_(module)("(%s) refCount: %d\n", wm->modname, wm->refCount );
1568 if ( wm->refCount == 0 )
1570 wm->flags |= WINE_MODREF_MARKER;
1572 for ( i = 0; i < wm->nDeps; i++ )
1573 if ( wm->deps[i] )
1574 MODULE_DecRefCount( wm->deps[i] );
1576 wm->flags &= ~WINE_MODREF_MARKER;
1580 /***********************************************************************
1581 * MODULE_FreeLibrary
1583 * NOTE: Assumes that the process critical section is held!
1585 BOOL MODULE_FreeLibrary( WINE_MODREF *wm )
1587 TRACE_(module)("(%s) - START\n", wm->modname );
1589 /* Recursively decrement reference counts */
1590 MODULE_DecRefCount( wm );
1592 /* Call process detach notifications */
1593 if ( PROCESS_Current()->free_lib_count <= 1 )
1594 MODULE_DllProcessDetach( FALSE, NULL );
1596 MODULE_FlushModrefs();
1598 TRACE_(module)("(%s) - END\n", wm->modname );
1600 return TRUE;
1604 /***********************************************************************
1605 * FreeLibraryAndExitThread
1607 VOID WINAPI FreeLibraryAndExitThread(HINSTANCE hLibModule, DWORD dwExitCode)
1609 FreeLibrary(hLibModule);
1610 ExitThread(dwExitCode);
1613 /***********************************************************************
1614 * PrivateLoadLibrary (KERNEL32)
1616 * FIXME: rough guesswork, don't know what "Private" means
1618 HINSTANCE WINAPI PrivateLoadLibrary(LPCSTR libname)
1620 return (HINSTANCE)LoadLibrary16(libname);
1625 /***********************************************************************
1626 * PrivateFreeLibrary (KERNEL32)
1628 * FIXME: rough guesswork, don't know what "Private" means
1630 void WINAPI PrivateFreeLibrary(HINSTANCE handle)
1632 FreeLibrary16((HINSTANCE16)handle);
1636 /***********************************************************************
1637 * WIN32_GetProcAddress16 (KERNEL32.36)
1638 * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
1640 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
1642 WORD ordinal;
1643 FARPROC16 ret;
1645 if (!hModule) {
1646 WARN_(module)("hModule may not be 0!\n");
1647 return (FARPROC16)0;
1649 if (HIWORD(hModule))
1651 WARN_(module)("hModule is Win32 handle (%08x)\n", hModule );
1652 return (FARPROC16)0;
1654 hModule = GetExePtr( hModule );
1655 if (HIWORD(name)) {
1656 ordinal = NE_GetOrdinal( hModule, name );
1657 TRACE_(module)("%04x '%s'\n",
1658 hModule, name );
1659 } else {
1660 ordinal = LOWORD(name);
1661 TRACE_(module)("%04x %04x\n",
1662 hModule, ordinal );
1664 if (!ordinal) return (FARPROC16)0;
1665 ret = NE_GetEntryPoint( hModule, ordinal );
1666 TRACE_(module)("returning %08x\n",(UINT)ret);
1667 return ret;
1670 /***********************************************************************
1671 * GetProcAddress16 (KERNEL.50)
1673 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, SEGPTR name )
1675 WORD ordinal;
1676 FARPROC16 ret;
1678 if (!hModule) hModule = GetCurrentTask();
1679 hModule = GetExePtr( hModule );
1681 if (HIWORD(name) != 0)
1683 ordinal = NE_GetOrdinal( hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1684 TRACE_(module)("%04x '%s'\n",
1685 hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1687 else
1689 ordinal = LOWORD(name);
1690 TRACE_(module)("%04x %04x\n",
1691 hModule, ordinal );
1693 if (!ordinal) return (FARPROC16)0;
1695 ret = NE_GetEntryPoint( hModule, ordinal );
1697 TRACE_(module)("returning %08x\n", (UINT)ret );
1698 return ret;
1702 /***********************************************************************
1703 * GetProcAddress32 (KERNEL32.257)
1705 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1707 return MODULE_GetProcAddress( hModule, function, TRUE );
1710 /***********************************************************************
1711 * WIN16_GetProcAddress32 (KERNEL.453)
1713 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
1715 return MODULE_GetProcAddress( hModule, function, FALSE );
1718 /***********************************************************************
1719 * MODULE_GetProcAddress32 (internal)
1721 FARPROC MODULE_GetProcAddress(
1722 HMODULE hModule, /* [in] current module handle */
1723 LPCSTR function, /* [in] function to be looked up */
1724 BOOL snoop )
1726 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1727 FARPROC retproc;
1729 if (HIWORD(function))
1730 TRACE_(win32)("(%08lx,%s)\n",(DWORD)hModule,function);
1731 else
1732 TRACE_(win32)("(%08lx,%p)\n",(DWORD)hModule,function);
1733 if (!wm) {
1734 SetLastError(ERROR_INVALID_HANDLE);
1735 return (FARPROC)0;
1737 switch (wm->type)
1739 case MODULE32_PE:
1740 retproc = PE_FindExportedFunction( wm, function, snoop );
1741 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1742 return retproc;
1743 case MODULE32_ELF:
1744 retproc = ELF_FindExportedFunction( wm, function);
1745 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1746 return retproc;
1747 default:
1748 ERR_(module)("wine_modref type %d not handled.\n",wm->type);
1749 SetLastError(ERROR_INVALID_HANDLE);
1750 return (FARPROC)0;
1755 /***********************************************************************
1756 * RtlImageNtHeaders (NTDLL)
1758 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
1760 /* basically:
1761 * return hModule+(((IMAGE_DOS_HEADER*)hModule)->e_lfanew);
1762 * but we could get HMODULE16 or the like (think builtin modules)
1765 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1766 if (!wm || (wm->type != MODULE32_PE)) return (PIMAGE_NT_HEADERS)0;
1767 return PE_HEADER(wm->module);
1771 /***************************************************************************
1772 * HasGPHandler (KERNEL.338)
1775 #include "pshpack1.h"
1776 typedef struct _GPHANDLERDEF
1778 WORD selector;
1779 WORD rangeStart;
1780 WORD rangeEnd;
1781 WORD handler;
1782 } GPHANDLERDEF;
1783 #include "poppack.h"
1785 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1787 HMODULE16 hModule;
1788 int gpOrdinal;
1789 SEGPTR gpPtr;
1790 GPHANDLERDEF *gpHandler;
1792 if ( (hModule = FarGetOwner16( SELECTOROF(address) )) != 0
1793 && (gpOrdinal = NE_GetOrdinal( hModule, "__GP" )) != 0
1794 && (gpPtr = (SEGPTR)NE_GetEntryPointEx( hModule, gpOrdinal, FALSE )) != 0
1795 && !IsBadReadPtr16( gpPtr, sizeof(GPHANDLERDEF) )
1796 && (gpHandler = PTR_SEG_TO_LIN( gpPtr )) != NULL )
1798 while (gpHandler->selector)
1800 if ( SELECTOROF(address) == gpHandler->selector
1801 && OFFSETOF(address) >= gpHandler->rangeStart
1802 && OFFSETOF(address) < gpHandler->rangeEnd )
1803 return PTR_SEG_OFF_TO_SEGPTR( gpHandler->selector,
1804 gpHandler->handler );
1805 gpHandler++;
1809 return 0;