Let CreateProcess launch unix executable without a .exe extension.
[wine.git] / loader / module.c
blob7bb56675be3c8c2c6de543088a0d17c0472ebe27
1 /*
2 * Modules
4 * Copyright 1995 Alexandre Julliard
5 */
7 #include <assert.h>
8 #include <fcntl.h>
9 #include <stdlib.h>
10 #include <stdio.h>
11 #include <string.h>
12 #include <sys/types.h>
13 #include <unistd.h>
14 #include "windef.h"
15 #include "wingdi.h"
16 #include "wine/winbase16.h"
17 #include "wine/winuser16.h"
18 #include "winerror.h"
19 #include "file.h"
20 #include "global.h"
21 #include "heap.h"
22 #include "module.h"
23 #include "snoop.h"
24 #include "neexe.h"
25 #include "pe_image.h"
26 #include "dosexe.h"
27 #include "process.h"
28 #include "syslevel.h"
29 #include "thread.h"
30 #include "selectors.h"
31 #include "stackframe.h"
32 #include "task.h"
33 #include "debugtools.h"
34 #include "callback.h"
35 #include "loadorder.h"
36 #include "elfdll.h"
37 #include "server.h"
39 DEFAULT_DEBUG_CHANNEL(module);
40 DECLARE_DEBUG_CHANNEL(win32);
42 /*************************************************************************
43 * MODULE_WalkModref
44 * Walk MODREFs for input process ID
46 void MODULE_WalkModref( DWORD id )
48 int i;
49 WINE_MODREF *zwm, *prev = NULL;
50 PDB *pdb = PROCESS_IdToPDB( id );
52 if (!pdb) {
53 MESSAGE("Invalid process id (pid)\n");
54 return;
57 MESSAGE("Modref list for process pdb=%p\n", pdb);
58 MESSAGE("Modref next prev handle deps flags name\n");
59 for ( zwm = pdb->modref_list; zwm; zwm = zwm->next) {
60 MESSAGE("%p %p %p %04x %5d %04x %s\n", zwm, zwm->next, zwm->prev,
61 zwm->module, zwm->nDeps, zwm->flags, zwm->modname);
62 for ( i = 0; i < zwm->nDeps; i++ ) {
63 if ( zwm->deps[i] )
64 MESSAGE(" %d %p %s\n", i, zwm->deps[i], zwm->deps[i]->modname);
66 if (prev != zwm->prev)
67 MESSAGE(" --> modref corrupt, previous pointer wrong!!\n");
68 prev = zwm;
72 /*************************************************************************
73 * MODULE32_LookupHMODULE
74 * looks for the referenced HMODULE in the current process
76 WINE_MODREF *MODULE32_LookupHMODULE( HMODULE hmod )
78 WINE_MODREF *wm;
80 if (!hmod)
81 return PROCESS_Current()->exe_modref;
83 if (!HIWORD(hmod)) {
84 ERR("tried to lookup 0x%04x in win32 module handler!\n",hmod);
85 return NULL;
87 for ( wm = PROCESS_Current()->modref_list; wm; wm=wm->next )
88 if (wm->module == hmod)
89 return wm;
90 return NULL;
93 /*************************************************************************
94 * MODULE_InitDll
96 static BOOL MODULE_InitDll( WINE_MODREF *wm, DWORD type, LPVOID lpReserved )
98 BOOL retv = TRUE;
100 static LPCSTR typeName[] = { "PROCESS_DETACH", "PROCESS_ATTACH",
101 "THREAD_ATTACH", "THREAD_DETACH" };
102 assert( wm );
105 /* Skip calls for modules loaded with special load flags */
107 if ( ( wm->flags & WINE_MODREF_DONT_RESOLVE_REFS )
108 || ( wm->flags & WINE_MODREF_LOAD_AS_DATAFILE ) )
109 return TRUE;
112 TRACE("(%s,%s,%p) - CALL\n",
113 wm->modname, typeName[type], lpReserved );
115 /* Call the initialization routine */
116 switch ( wm->type )
118 case MODULE32_PE:
119 retv = PE_InitDLL( wm, type, lpReserved );
120 break;
122 case MODULE32_ELF:
123 /* no need to do that, dlopen() already does */
124 break;
126 default:
127 ERR("wine_modref type %d not handled.\n", wm->type );
128 retv = FALSE;
129 break;
132 TRACE("(%s,%s,%p) - RETURN %d\n",
133 wm->modname, typeName[type], lpReserved, retv );
135 return retv;
138 /*************************************************************************
139 * MODULE_DllProcessAttach
141 * Send the process attach notification to all DLLs the given module
142 * depends on (recursively). This is somewhat complicated due to the fact that
144 * - we have to respect the module dependencies, i.e. modules implicitly
145 * referenced by another module have to be initialized before the module
146 * itself can be initialized
148 * - the initialization routine of a DLL can itself call LoadLibrary,
149 * thereby introducing a whole new set of dependencies (even involving
150 * the 'old' modules) at any time during the whole process
152 * (Note that this routine can be recursively entered not only directly
153 * from itself, but also via LoadLibrary from one of the called initialization
154 * routines.)
156 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
157 * the process *detach* notifications to be sent in the correct order.
158 * This must not only take into account module dependencies, but also
159 * 'hidden' dependencies created by modules calling LoadLibrary in their
160 * attach notification routine.
162 * The strategy is rather simple: we move a WINE_MODREF to the head of the
163 * list after the attach notification has returned. This implies that the
164 * detach notifications are called in the reverse of the sequence the attach
165 * notifications *returned*.
167 * NOTE: Assumes that the process critical section is held!
170 BOOL MODULE_DllProcessAttach( WINE_MODREF *wm, LPVOID lpReserved )
172 BOOL retv = TRUE;
173 int i;
174 assert( wm );
176 /* prevent infinite recursion in case of cyclical dependencies */
177 if ( ( wm->flags & WINE_MODREF_MARKER )
178 || ( wm->flags & WINE_MODREF_PROCESS_ATTACHED ) )
179 return retv;
181 TRACE("(%s,%p) - START\n", wm->modname, lpReserved );
183 /* Tag current MODREF to prevent recursive loop */
184 wm->flags |= WINE_MODREF_MARKER;
186 /* Recursively attach all DLLs this one depends on */
187 for ( i = 0; retv && i < wm->nDeps; i++ )
188 if ( wm->deps[i] )
189 retv = MODULE_DllProcessAttach( wm->deps[i], lpReserved );
191 /* Call DLL entry point */
192 if ( retv )
194 retv = MODULE_InitDll( wm, DLL_PROCESS_ATTACH, lpReserved );
195 if ( retv )
196 wm->flags |= WINE_MODREF_PROCESS_ATTACHED;
199 /* Re-insert MODREF at head of list */
200 if ( retv && wm->prev )
202 wm->prev->next = wm->next;
203 if ( wm->next ) wm->next->prev = wm->prev;
205 wm->prev = NULL;
206 wm->next = PROCESS_Current()->modref_list;
207 PROCESS_Current()->modref_list = wm->next->prev = wm;
210 /* Remove recursion flag */
211 wm->flags &= ~WINE_MODREF_MARKER;
213 TRACE("(%s,%p) - END\n", wm->modname, lpReserved );
215 return retv;
218 /*************************************************************************
219 * MODULE_DllProcessDetach
221 * Send DLL process detach notifications. See the comment about calling
222 * sequence at MODULE_DllProcessAttach. Unless the bForceDetach flag
223 * is set, only DLLs with zero refcount are notified.
225 void MODULE_DllProcessDetach( BOOL bForceDetach, LPVOID lpReserved )
227 WINE_MODREF *wm;
229 EnterCriticalSection( &PROCESS_Current()->crit_section );
233 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
235 /* Check whether to detach this DLL */
236 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
237 continue;
238 if ( wm->refCount > 0 && !bForceDetach )
239 continue;
241 /* Call detach notification */
242 wm->flags &= ~WINE_MODREF_PROCESS_ATTACHED;
243 MODULE_InitDll( wm, DLL_PROCESS_DETACH, lpReserved );
245 /* Restart at head of WINE_MODREF list, as entries might have
246 been added and/or removed while performing the call ... */
247 break;
249 } while ( wm );
251 LeaveCriticalSection( &PROCESS_Current()->crit_section );
254 /*************************************************************************
255 * MODULE_DllThreadAttach
257 * Send DLL thread attach notifications. These are sent in the
258 * reverse sequence of process detach notification.
261 void MODULE_DllThreadAttach( LPVOID lpReserved )
263 WINE_MODREF *wm;
265 EnterCriticalSection( &PROCESS_Current()->crit_section );
267 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
268 if ( !wm->next )
269 break;
271 for ( ; wm; wm = wm->prev )
273 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
274 continue;
275 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
276 continue;
278 MODULE_InitDll( wm, DLL_THREAD_ATTACH, lpReserved );
281 LeaveCriticalSection( &PROCESS_Current()->crit_section );
284 /*************************************************************************
285 * MODULE_DllThreadDetach
287 * Send DLL thread detach notifications. These are sent in the
288 * same sequence as process detach notification.
291 void MODULE_DllThreadDetach( LPVOID lpReserved )
293 WINE_MODREF *wm;
295 EnterCriticalSection( &PROCESS_Current()->crit_section );
297 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
299 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
300 continue;
301 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
302 continue;
304 MODULE_InitDll( wm, DLL_THREAD_DETACH, lpReserved );
307 LeaveCriticalSection( &PROCESS_Current()->crit_section );
310 /****************************************************************************
311 * DisableThreadLibraryCalls (KERNEL32.74)
313 * Don't call DllEntryPoint for DLL_THREAD_{ATTACH,DETACH} if set.
315 BOOL WINAPI DisableThreadLibraryCalls( HMODULE hModule )
317 WINE_MODREF *wm;
318 BOOL retval = TRUE;
320 EnterCriticalSection( &PROCESS_Current()->crit_section );
322 wm = MODULE32_LookupHMODULE( hModule );
323 if ( !wm )
324 retval = FALSE;
325 else
326 wm->flags |= WINE_MODREF_NO_DLL_CALLS;
328 LeaveCriticalSection( &PROCESS_Current()->crit_section );
330 return retval;
334 /***********************************************************************
335 * MODULE_CreateDummyModule
337 * Create a dummy NE module for Win32 or Winelib.
339 HMODULE MODULE_CreateDummyModule( LPCSTR filename, WORD version )
341 HMODULE hModule;
342 NE_MODULE *pModule;
343 SEGTABLEENTRY *pSegment;
344 char *pStr,*s;
345 unsigned int len;
346 const char* basename;
347 OFSTRUCT *ofs;
348 int of_size, size;
350 /* Extract base filename */
351 basename = strrchr(filename, '\\');
352 if (!basename) basename = filename;
353 else basename++;
354 len = strlen(basename);
355 if ((s = strchr(basename, '.'))) len = s - basename;
357 /* Allocate module */
358 of_size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName)
359 + strlen(filename) + 1;
360 size = sizeof(NE_MODULE) +
361 /* loaded file info */
362 of_size +
363 /* segment table: DS,CS */
364 2 * sizeof(SEGTABLEENTRY) +
365 /* name table */
366 len + 2 +
367 /* several empty tables */
370 hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
371 if (!hModule) return (HMODULE)11; /* invalid exe */
373 FarSetOwner16( hModule, hModule );
374 pModule = (NE_MODULE *)GlobalLock16( hModule );
376 /* Set all used entries */
377 pModule->magic = IMAGE_OS2_SIGNATURE;
378 pModule->count = 1;
379 pModule->next = 0;
380 pModule->flags = 0;
381 pModule->dgroup = 0;
382 pModule->ss = 1;
383 pModule->cs = 2;
384 pModule->heap_size = 0;
385 pModule->stack_size = 0;
386 pModule->seg_count = 2;
387 pModule->modref_count = 0;
388 pModule->nrname_size = 0;
389 pModule->fileinfo = sizeof(NE_MODULE);
390 pModule->os_flags = NE_OSFLAGS_WINDOWS;
391 pModule->expected_version = version;
392 pModule->self = hModule;
394 /* Set loaded file information */
395 ofs = (OFSTRUCT *)(pModule + 1);
396 memset( ofs, 0, of_size );
397 ofs->cBytes = of_size < 256 ? of_size : 255; /* FIXME */
398 strcpy( ofs->szPathName, filename );
400 pSegment = (SEGTABLEENTRY*)((char*)(pModule + 1) + of_size);
401 pModule->seg_table = (int)pSegment - (int)pModule;
402 /* Data segment */
403 pSegment->size = 0;
404 pSegment->flags = NE_SEGFLAGS_DATA;
405 pSegment->minsize = 0x1000;
406 pSegment++;
407 /* Code segment */
408 pSegment->flags = 0;
409 pSegment++;
411 /* Module name */
412 pStr = (char *)pSegment;
413 pModule->name_table = (int)pStr - (int)pModule;
414 assert(len<256);
415 *pStr = len;
416 lstrcpynA( pStr+1, basename, len+1 );
417 pStr += len+2;
419 /* All tables zero terminated */
420 pModule->res_table = pModule->import_table = pModule->entry_table =
421 (int)pStr - (int)pModule;
423 NE_RegisterModule( pModule );
424 return hModule;
428 /**********************************************************************
429 * MODULE_FindModule32
431 * Find a (loaded) win32 module depending on path
433 * RETURNS
434 * the module handle if found
435 * 0 if not
437 WINE_MODREF *MODULE_FindModule(
438 LPCSTR path /* [in] pathname of module/library to be found */
440 WINE_MODREF *wm;
441 char dllname[260], *p;
443 /* Append .DLL to name if no extension present */
444 strcpy( dllname, path );
445 if (!(p = strrchr( dllname, '.')) || strchr( p, '/' ) || strchr( p, '\\'))
446 strcat( dllname, ".DLL" );
448 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
450 if ( !strcasecmp( dllname, wm->modname ) )
451 break;
452 if ( !strcasecmp( dllname, wm->filename ) )
453 break;
454 if ( !strcasecmp( dllname, wm->short_modname ) )
455 break;
456 if ( !strcasecmp( dllname, wm->short_filename ) )
457 break;
460 return wm;
463 /***********************************************************************
464 * MODULE_GetBinaryType
466 * The GetBinaryType function determines whether a file is executable
467 * or not and if it is it returns what type of executable it is.
468 * The type of executable is a property that determines in which
469 * subsystem an executable file runs under.
471 * Binary types returned:
472 * SCS_32BIT_BINARY: A Win32 based application
473 * SCS_DOS_BINARY: An MS-Dos based application
474 * SCS_WOW_BINARY: A Win16 based application
475 * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
476 * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
477 * SCS_OS216_BINARY: A 16bit OS/2 based application
479 * Returns TRUE if the file is an executable in which case
480 * the value pointed by lpBinaryType is set.
481 * Returns FALSE if the file is not an executable or if the function fails.
483 * To do so it opens the file and reads in the header information
484 * if the extended header information is not present it will
485 * assume that the file is a DOS executable.
486 * If the extended header information is present it will
487 * determine if the file is a 16 or 32 bit Windows executable
488 * by check the flags in the header.
490 * Note that .COM and .PIF files are only recognized by their
491 * file name extension; but Windows does it the same way ...
493 static BOOL MODULE_GetBinaryType( HANDLE hfile, LPCSTR filename,
494 LPDWORD lpBinaryType )
496 IMAGE_DOS_HEADER mz_header;
497 char magic[4], *ptr;
498 DWORD len;
500 /* Seek to the start of the file and read the DOS header information.
502 if ( SetFilePointer( hfile, 0, NULL, SEEK_SET ) != -1
503 && ReadFile( hfile, &mz_header, sizeof(mz_header), &len, NULL )
504 && len == sizeof(mz_header) )
506 /* Now that we have the header check the e_magic field
507 * to see if this is a dos image.
509 if ( mz_header.e_magic == IMAGE_DOS_SIGNATURE )
511 BOOL lfanewValid = FALSE;
512 /* We do have a DOS image so we will now try to seek into
513 * the file by the amount indicated by the field
514 * "Offset to extended header" and read in the
515 * "magic" field information at that location.
516 * This will tell us if there is more header information
517 * to read or not.
519 /* But before we do we will make sure that header
520 * structure encompasses the "Offset to extended header"
521 * field.
523 if ( (mz_header.e_cparhdr<<4) >= sizeof(IMAGE_DOS_HEADER) )
524 if ( ( mz_header.e_crlc == 0 ) ||
525 ( mz_header.e_lfarlc >= sizeof(IMAGE_DOS_HEADER) ) )
526 if ( mz_header.e_lfanew >= sizeof(IMAGE_DOS_HEADER)
527 && SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET ) != -1
528 && ReadFile( hfile, magic, sizeof(magic), &len, NULL )
529 && len == sizeof(magic) )
530 lfanewValid = TRUE;
532 if ( !lfanewValid )
534 /* If we cannot read this "extended header" we will
535 * assume that we have a simple DOS executable.
537 *lpBinaryType = SCS_DOS_BINARY;
538 return TRUE;
540 else
542 /* Reading the magic field succeeded so
543 * we will try to determine what type it is.
545 if ( *(DWORD*)magic == IMAGE_NT_SIGNATURE )
547 /* This is an NT signature.
549 *lpBinaryType = SCS_32BIT_BINARY;
550 return TRUE;
552 else if ( *(WORD*)magic == IMAGE_OS2_SIGNATURE )
554 /* The IMAGE_OS2_SIGNATURE indicates that the
555 * "extended header is a Windows executable (NE)
556 * header." This can mean either a 16-bit OS/2
557 * or a 16-bit Windows or even a DOS program
558 * (running under a DOS extender). To decide
559 * which, we'll have to read the NE header.
562 IMAGE_OS2_HEADER ne;
563 if ( SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET ) != -1
564 && ReadFile( hfile, &ne, sizeof(ne), &len, NULL )
565 && len == sizeof(ne) )
567 switch ( ne.operating_system )
569 case 2: *lpBinaryType = SCS_WOW_BINARY; return TRUE;
570 case 5: *lpBinaryType = SCS_DOS_BINARY; return TRUE;
571 default: *lpBinaryType = SCS_OS216_BINARY; return TRUE;
574 /* Couldn't read header, so abort. */
575 return FALSE;
577 else
579 /* Unknown extended header, but this file is nonetheless
580 DOS-executable.
582 *lpBinaryType = SCS_DOS_BINARY;
583 return TRUE;
589 /* If we get here, we don't even have a correct MZ header.
590 * Try to check the file extension for known types ...
592 ptr = strrchr( filename, '.' );
593 if ( ptr && !strchr( ptr, '\\' ) && !strchr( ptr, '/' ) )
595 if ( !lstrcmpiA( ptr, ".COM" ) )
597 *lpBinaryType = SCS_DOS_BINARY;
598 return TRUE;
601 if ( !lstrcmpiA( ptr, ".PIF" ) )
603 *lpBinaryType = SCS_PIF_BINARY;
604 return TRUE;
608 return FALSE;
611 /***********************************************************************
612 * GetBinaryTypeA [KERNEL32.280]
614 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
616 BOOL ret = FALSE;
617 HANDLE hfile;
619 TRACE_(win32)("%s\n", lpApplicationName );
621 /* Sanity check.
623 if ( lpApplicationName == NULL || lpBinaryType == NULL )
624 return FALSE;
626 /* Open the file indicated by lpApplicationName for reading.
628 hfile = CreateFileA( lpApplicationName, GENERIC_READ, 0,
629 NULL, OPEN_EXISTING, 0, -1 );
630 if ( hfile == INVALID_HANDLE_VALUE )
631 return FALSE;
633 /* Check binary type
635 ret = MODULE_GetBinaryType( hfile, lpApplicationName, lpBinaryType );
637 /* Close the file.
639 CloseHandle( hfile );
641 return ret;
644 /***********************************************************************
645 * GetBinaryTypeW [KERNEL32.281]
647 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
649 BOOL ret = FALSE;
650 LPSTR strNew = NULL;
652 TRACE_(win32)("%s\n", debugstr_w(lpApplicationName) );
654 /* Sanity check.
656 if ( lpApplicationName == NULL || lpBinaryType == NULL )
657 return FALSE;
659 /* Convert the wide string to a ascii string.
661 strNew = HEAP_strdupWtoA( GetProcessHeap(), 0, lpApplicationName );
663 if ( strNew != NULL )
665 ret = GetBinaryTypeA( strNew, lpBinaryType );
667 /* Free the allocated string.
669 HeapFree( GetProcessHeap(), 0, strNew );
672 return ret;
675 /**********************************************************************
676 * MODULE_CreateUnixProcess
678 static BOOL MODULE_CreateUnixProcess( LPCSTR filename, LPCSTR lpCmdLine,
679 LPSTARTUPINFOA lpStartupInfo,
680 LPPROCESS_INFORMATION lpProcessInfo,
681 BOOL useWine )
683 const char *argv[256], **argptr;
684 char *cmdline = NULL;
685 BOOL iconic = FALSE;
687 /* Get Unix file name and iconic flag */
689 if ( lpStartupInfo->dwFlags & STARTF_USESHOWWINDOW )
690 if ( lpStartupInfo->wShowWindow == SW_SHOWMINIMIZED
691 || lpStartupInfo->wShowWindow == SW_SHOWMINNOACTIVE )
692 iconic = TRUE;
694 /* Build argument list */
695 argptr = argv;
696 if ( !useWine )
698 char *p;
699 const char *unixfilename = filename;
700 DOS_FULL_NAME full_name;
702 p = cmdline = strdup(lpCmdLine);
703 if (strchr(filename, '/') || strchr(filename, ':') || strchr(filename, '\\'))
705 if ( DOSFS_GetFullName( filename, TRUE, &full_name ) )
706 unixfilename = full_name.long_name;
708 if (iconic) *argptr++ = "-iconic";
709 while (1)
711 while (*p && (*p == ' ' || *p == '\t')) *p++ = '\0';
712 if (!*p) break;
713 *argptr++ = p;
714 while (*p && *p != ' ' && *p != '\t') p++;
716 /* overwrite program name gotten from tidy_cmd */
717 argv[0] = unixfilename;
719 else
721 *argptr++ = "wine";
722 if (iconic) *argptr++ = "-iconic";
723 *argptr++ = lpCmdLine;
725 *argptr++ = 0;
727 /* Fork and execute */
729 if ( !fork() )
731 /* Note: don't use Wine routines here, as this process
732 has not been correctly initialized! */
734 execvp( argv[0], (char**)argv );
736 /* Failed ! */
737 if ( useWine )
738 fprintf( stderr, "CreateProcess: can't exec 'wine %s'\n",
739 lpCmdLine );
740 exit( 1 );
743 /* Fake success return value */
745 memset( lpProcessInfo, '\0', sizeof( *lpProcessInfo ) );
746 lpProcessInfo->hProcess = INVALID_HANDLE_VALUE;
747 lpProcessInfo->hThread = INVALID_HANDLE_VALUE;
748 if (cmdline) free(cmdline);
750 SetLastError( ERROR_SUCCESS );
751 return TRUE;
754 /***********************************************************************
755 * WinExec16 (KERNEL.166)
757 HINSTANCE16 WINAPI WinExec16( LPCSTR lpCmdLine, UINT16 nCmdShow )
759 HINSTANCE16 hInst;
761 SYSLEVEL_ReleaseWin16Lock();
762 hInst = WinExec( lpCmdLine, nCmdShow );
763 SYSLEVEL_RestoreWin16Lock();
765 return hInst;
768 /***********************************************************************
769 * WinExec (KERNEL32.566)
771 HINSTANCE WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
773 LOADPARAMS params;
774 UINT16 paramCmdShow[2];
776 if (!lpCmdLine)
777 return 2; /* File not found */
779 /* Set up LOADPARAMS buffer for LoadModule */
781 memset( &params, '\0', sizeof(params) );
782 params.lpCmdLine = (LPSTR)lpCmdLine;
783 params.lpCmdShow = paramCmdShow;
784 params.lpCmdShow[0] = 2;
785 params.lpCmdShow[1] = nCmdShow;
787 /* Now load the executable file */
789 return LoadModule( NULL, &params );
792 /**********************************************************************
793 * LoadModule (KERNEL32.499)
795 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
797 LOADPARAMS *params = (LOADPARAMS *)paramBlock;
798 PROCESS_INFORMATION info;
799 STARTUPINFOA startup;
800 HINSTANCE hInstance;
801 PDB *pdb;
802 TDB *tdb;
804 memset( &startup, '\0', sizeof(startup) );
805 startup.cb = sizeof(startup);
806 startup.dwFlags = STARTF_USESHOWWINDOW;
807 startup.wShowWindow = params->lpCmdShow? params->lpCmdShow[1] : 0;
809 if ( !CreateProcessA( name, params->lpCmdLine,
810 NULL, NULL, FALSE, 0, params->lpEnvAddress,
811 NULL, &startup, &info ) )
813 hInstance = GetLastError();
814 if ( hInstance < 32 ) return hInstance;
816 FIXME("Strange error set by CreateProcess: %d\n", hInstance );
817 return 11;
820 /* Give 30 seconds to the app to come up */
821 if ( Callout.WaitForInputIdle ( info.hProcess, 30000 ) == 0xFFFFFFFF )
822 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
824 /* Get 16-bit hInstance/hTask from process */
825 pdb = PROCESS_IdToPDB( info.dwProcessId );
826 tdb = pdb? (TDB *)GlobalLock16( pdb->task ) : NULL;
827 hInstance = tdb && tdb->hInstance? tdb->hInstance : pdb? pdb->task : 0;
828 /* If there is no hInstance (32-bit process) return a dummy value
829 * that must be > 31
830 * FIXME: should do this in all cases and fix Win16 callers */
831 if (!hInstance) hInstance = 33;
833 /* Close off the handles */
834 CloseHandle( info.hThread );
835 CloseHandle( info.hProcess );
837 return hInstance;
840 /*************************************************************************
841 * get_makename_token
843 * Get next blank delimited token from input string. If quoted then
844 * process till matching quote and then till blank.
846 * Returns number of characters in token (not including \0). On
847 * end of string (EOS), returns a 0.
849 * from (IO) address of start of input string to scan, updated to
850 * next non-processed character.
851 * to (IO) address of start of output string (previous token \0
852 * char), updated to end of new output string (the \0
853 * char).
855 static int get_makename_token(LPCSTR *from, LPSTR *to )
857 int len = 0;
858 LPCSTR to_old = *to; /* only used for tracing */
860 while ( **from == ' ') {
861 /* Copy leading blanks (separators between previous */
862 /* token and this token). */
863 **to = **from;
864 (*from)++;
865 (*to)++;
866 len++;
868 do {
869 while ( (**from != 0) && (**from != ' ') && (**from != '"') ) {
870 **to = **from; (*from)++; (*to)++; len++;
872 if ( **from == '"' ) {
873 /* Handle quoted string. */
874 (*from)++;
875 if ( !strchr(*from, '"') ) {
876 /* fail - no closing quote. Return entire string */
877 while ( **from != 0 ) {
878 **to = **from; (*from)++; (*to)++; len++;
880 break;
882 while( **from != '"') {
883 **to = **from;
884 len++;
885 (*to)++;
886 (*from)++;
888 (*from)++;
889 continue;
892 /* either EOS or ' ' */
893 break;
895 } while (1);
897 **to = 0; /* terminate output string */
899 TRACE("returning token len=%d, string=%s\n", len, to_old);
901 return len;
904 /*************************************************************************
905 * make_lpCommandLine_name
907 * Try longer and longer strings from "line" to find an existing
908 * file name. Each attempt is delimited by a blank outside of quotes.
909 * Also will attempt to append ".exe" if requested and not already
910 * present. Returns the address of the remaining portion of the
911 * input line.
915 static BOOL make_lpCommandLine_name( LPCSTR line, LPSTR name, int namelen,
916 LPCSTR *after )
918 BOOL found = TRUE;
919 LPCSTR from;
920 char buffer[260];
921 DWORD retlen;
922 LPSTR to, lastpart;
924 from = line;
925 to = name;
927 /* scan over initial blanks if any */
928 while ( *from == ' ') from++;
930 /* get a token and append to previous data the check for existance */
931 do {
932 if ( !get_makename_token( &from, &to ) ) {
933 /* EOS has occured and not found - exit */
934 retlen = 0;
935 found = FALSE;
936 break;
938 TRACE("checking if file exists '%s'\n", name);
939 retlen = SearchPathA( NULL, name, ".exe", sizeof(buffer), buffer, &lastpart);
940 if (!retlen)
941 retlen = SearchPathA( NULL, name, NULL, sizeof(buffer), buffer, &lastpart);
943 if ( retlen && (retlen < sizeof(buffer)) ) break;
944 } while (1);
946 /* if we have a non-null full path name in buffer then move to output */
947 if ( retlen ) {
948 if ( strlen(buffer) <= namelen ) {
949 strcpy( name, buffer );
950 } else {
951 /* not enough space to return full path string */
952 FIXME("internal string not long enough, need %d\n",
953 strlen(buffer) );
957 /* all done, indicate end of module name and then trace and exit */
958 if (after) *after = from;
959 TRACE("%i, selected file name '%s'\n and cmdline as %s\n",
960 found, name, debugstr_a(from));
961 return found;
964 /*************************************************************************
965 * make_lpApplicationName_name
967 * Scan input string (the lpApplicationName) and remove any quotes
968 * if they are balanced.
972 static BOOL make_lpApplicationName_name( LPCSTR line, LPSTR name, int namelen)
974 LPCSTR from;
975 LPSTR to, to_end, to_old;
976 char buffer[260];
978 to = buffer;
979 to_end = to + sizeof(buffer) - 1;
980 to_old = to;
982 while ( *line == ' ' ) line++; /* point to beginning of string */
983 from = line;
984 do {
985 /* Copy all input till end, or quote */
986 while((*from != 0) && (*from != '"') && (to < to_end))
987 *to++ = *from++;
988 if (to >= to_end) { *to = 0; break; }
990 if (*from == '"')
992 /* Handle quoted string. If there is a closing quote, copy all */
993 /* that is inside. */
994 from++;
995 if (!strchr(from, '"'))
997 /* fail - no closing quote */
998 to = to_old; /* restore to previous attempt */
999 *to = 0; /* end string */
1000 break; /* exit with previous attempt */
1002 while((*from != '"') && (to < to_end)) *to++ = *from++;
1003 if (to >= to_end) { *to = 0; break; }
1004 from++;
1005 continue; /* past quoted string, so restart from top */
1008 *to = 0; /* terminate output string */
1009 to_old = to; /* save for possible use in unmatched quote case */
1011 /* loop around keeping the blank as part of file name */
1012 if (!*from)
1013 break; /* exit if out of input string */
1014 } while (1);
1016 if (!SearchPathA( NULL, buffer, ".exe", namelen, name, NULL ) &&
1017 !SearchPathA( NULL, buffer, NULL, namelen, name, NULL ) ) {
1018 TRACE("file not found '%s'\n", buffer );
1019 return FALSE;
1022 TRACE("selected as file name '%s'\n", name );
1023 return TRUE;
1026 /**********************************************************************
1027 * CreateProcessA (KERNEL32.171)
1029 BOOL WINAPI CreateProcessA( LPCSTR lpApplicationName, LPSTR lpCommandLine,
1030 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1031 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1032 BOOL bInheritHandles, DWORD dwCreationFlags,
1033 LPVOID lpEnvironment, LPCSTR lpCurrentDirectory,
1034 LPSTARTUPINFOA lpStartupInfo,
1035 LPPROCESS_INFORMATION lpProcessInfo )
1037 BOOL retv = FALSE;
1038 BOOL found_file = FALSE;
1039 HANDLE hFile;
1040 DWORD type;
1041 char name[256], dummy[256];
1042 LPCSTR cmdline = NULL;
1043 LPSTR tidy_cmdline;
1045 /* Get name and command line */
1047 if (!lpApplicationName && !lpCommandLine)
1049 SetLastError( ERROR_FILE_NOT_FOUND );
1050 return FALSE;
1053 /* Process the AppName and/or CmdLine to get module name and path */
1055 name[0] = '\0';
1057 if (lpApplicationName)
1059 found_file = make_lpApplicationName_name( lpApplicationName, name, sizeof(name) );
1060 if (lpCommandLine)
1061 make_lpCommandLine_name( lpCommandLine, dummy, sizeof ( dummy ), &cmdline );
1062 else
1063 cmdline = lpApplicationName;
1065 else
1067 if (lpCommandLine)
1068 found_file = make_lpCommandLine_name( lpCommandLine, name, sizeof ( name ), &cmdline );
1071 if ( !found_file ) {
1072 /* make an early exit if file not found - save second pass */
1073 SetLastError( ERROR_FILE_NOT_FOUND );
1074 return FALSE;
1077 if (!cmdline) cmdline = "";
1078 tidy_cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(name) + strlen(cmdline) + 3 );
1079 TRACE_(module)("tidy_cmdline: name '%s'[%d], cmdline '%s'[%d]\n",
1080 name, strlen(name), cmdline, strlen(cmdline));
1081 sprintf( tidy_cmdline, "\"%s\"%s", name, cmdline);
1083 /* Warn if unsupported features are used */
1085 if (dwCreationFlags & DETACHED_PROCESS)
1086 FIXME("(%s,...): DETACHED_PROCESS ignored\n", name);
1087 if (dwCreationFlags & CREATE_NEW_CONSOLE)
1088 FIXME("(%s,...): CREATE_NEW_CONSOLE ignored\n", name);
1089 if (dwCreationFlags & NORMAL_PRIORITY_CLASS)
1090 FIXME("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
1091 if (dwCreationFlags & IDLE_PRIORITY_CLASS)
1092 FIXME("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
1093 if (dwCreationFlags & HIGH_PRIORITY_CLASS)
1094 FIXME("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
1095 if (dwCreationFlags & REALTIME_PRIORITY_CLASS)
1096 FIXME("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
1097 if (dwCreationFlags & CREATE_NEW_PROCESS_GROUP)
1098 FIXME("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
1099 if (dwCreationFlags & CREATE_UNICODE_ENVIRONMENT)
1100 FIXME("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
1101 if (dwCreationFlags & CREATE_SEPARATE_WOW_VDM)
1102 FIXME("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
1103 if (dwCreationFlags & CREATE_SHARED_WOW_VDM)
1104 FIXME("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
1105 if (dwCreationFlags & CREATE_DEFAULT_ERROR_MODE)
1106 FIXME("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
1107 if (dwCreationFlags & CREATE_NO_WINDOW)
1108 FIXME("(%s,...): CREATE_NO_WINDOW ignored\n", name);
1109 if (dwCreationFlags & PROFILE_USER)
1110 FIXME("(%s,...): PROFILE_USER ignored\n", name);
1111 if (dwCreationFlags & PROFILE_KERNEL)
1112 FIXME("(%s,...): PROFILE_KERNEL ignored\n", name);
1113 if (dwCreationFlags & PROFILE_SERVER)
1114 FIXME("(%s,...): PROFILE_SERVER ignored\n", name);
1115 if (lpCurrentDirectory)
1116 FIXME("(%s,...): lpCurrentDirectory %s ignored\n",
1117 name, lpCurrentDirectory);
1118 if (lpStartupInfo->lpDesktop)
1119 FIXME("(%s,...): lpStartupInfo->lpDesktop %s ignored\n",
1120 name, lpStartupInfo->lpDesktop);
1121 if (lpStartupInfo->lpTitle)
1122 FIXME("(%s,...): lpStartupInfo->lpTitle %s ignored\n",
1123 name, lpStartupInfo->lpTitle);
1124 if (lpStartupInfo->dwFlags & STARTF_USECOUNTCHARS)
1125 FIXME("(%s,...): STARTF_USECOUNTCHARS (%ld,%ld) ignored\n",
1126 name, lpStartupInfo->dwXCountChars, lpStartupInfo->dwYCountChars);
1127 if (lpStartupInfo->dwFlags & STARTF_USEFILLATTRIBUTE)
1128 FIXME("(%s,...): STARTF_USEFILLATTRIBUTE %lx ignored\n",
1129 name, lpStartupInfo->dwFillAttribute);
1130 if (lpStartupInfo->dwFlags & STARTF_RUNFULLSCREEN)
1131 FIXME("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
1132 if (lpStartupInfo->dwFlags & STARTF_FORCEONFEEDBACK)
1133 FIXME("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
1134 if (lpStartupInfo->dwFlags & STARTF_FORCEOFFFEEDBACK)
1135 FIXME("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
1136 if (lpStartupInfo->dwFlags & STARTF_USEHOTKEY)
1137 FIXME("(%s,...): STARTF_USEHOTKEY ignored\n", name);
1140 /* Load file and create process */
1142 if ( !retv )
1144 /* Open file and determine executable type */
1146 hFile = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ,
1147 NULL, OPEN_EXISTING, 0, -1 );
1148 if ( hFile == INVALID_HANDLE_VALUE )
1150 SetLastError( ERROR_FILE_NOT_FOUND );
1151 HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1152 return FALSE;
1155 if ( !MODULE_GetBinaryType( hFile, name, &type ) )
1157 CloseHandle( hFile );
1159 /* FIXME: Try Unix executable only when appropriate! */
1160 if ( MODULE_CreateUnixProcess( name, tidy_cmdline,
1161 lpStartupInfo, lpProcessInfo, FALSE ) )
1163 HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1164 return TRUE;
1166 HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1167 SetLastError( ERROR_BAD_FORMAT );
1168 return FALSE;
1172 /* Create process */
1174 switch ( type )
1176 case SCS_32BIT_BINARY:
1177 retv = PE_CreateProcess( hFile, name, tidy_cmdline, lpEnvironment,
1178 lpProcessAttributes, lpThreadAttributes,
1179 bInheritHandles, dwCreationFlags,
1180 lpStartupInfo, lpProcessInfo );
1181 break;
1183 case SCS_DOS_BINARY:
1184 retv = MZ_CreateProcess( hFile, name, tidy_cmdline, lpEnvironment,
1185 lpProcessAttributes, lpThreadAttributes,
1186 bInheritHandles, dwCreationFlags,
1187 lpStartupInfo, lpProcessInfo );
1188 break;
1190 case SCS_WOW_BINARY:
1191 retv = NE_CreateProcess( hFile, name, tidy_cmdline, lpEnvironment,
1192 lpProcessAttributes, lpThreadAttributes,
1193 bInheritHandles, dwCreationFlags,
1194 lpStartupInfo, lpProcessInfo );
1195 break;
1197 case SCS_PIF_BINARY:
1198 case SCS_POSIX_BINARY:
1199 case SCS_OS216_BINARY:
1200 FIXME("Unsupported executable type: %ld\n", type );
1201 /* fall through */
1203 default:
1204 SetLastError( ERROR_BAD_FORMAT );
1205 retv = FALSE;
1206 break;
1209 CloseHandle( hFile );
1211 HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1212 return retv;
1215 /**********************************************************************
1216 * CreateProcessW (KERNEL32.172)
1217 * NOTES
1218 * lpReserved is not converted
1220 BOOL WINAPI CreateProcessW( LPCWSTR lpApplicationName, LPWSTR lpCommandLine,
1221 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1222 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1223 BOOL bInheritHandles, DWORD dwCreationFlags,
1224 LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory,
1225 LPSTARTUPINFOW lpStartupInfo,
1226 LPPROCESS_INFORMATION lpProcessInfo )
1227 { BOOL ret;
1228 STARTUPINFOA StartupInfoA;
1230 LPSTR lpApplicationNameA = HEAP_strdupWtoA (GetProcessHeap(),0,lpApplicationName);
1231 LPSTR lpCommandLineA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCommandLine);
1232 LPSTR lpCurrentDirectoryA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCurrentDirectory);
1234 memcpy (&StartupInfoA, lpStartupInfo, sizeof(STARTUPINFOA));
1235 StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpDesktop);
1236 StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpTitle);
1238 TRACE_(win32)("(%s,%s,...)\n", debugstr_w(lpApplicationName), debugstr_w(lpCommandLine));
1240 if (lpStartupInfo->lpReserved)
1241 FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n", debugstr_w(lpStartupInfo->lpReserved));
1243 ret = CreateProcessA( lpApplicationNameA, lpCommandLineA,
1244 lpProcessAttributes, lpThreadAttributes,
1245 bInheritHandles, dwCreationFlags,
1246 lpEnvironment, lpCurrentDirectoryA,
1247 &StartupInfoA, lpProcessInfo );
1249 HeapFree( GetProcessHeap(), 0, lpCurrentDirectoryA );
1250 HeapFree( GetProcessHeap(), 0, lpCommandLineA );
1251 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1252 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1254 return ret;
1257 /***********************************************************************
1258 * GetModuleHandleA (KERNEL32.237)
1260 HMODULE WINAPI GetModuleHandleA(LPCSTR module)
1262 WINE_MODREF *wm;
1264 if ( module == NULL )
1265 wm = PROCESS_Current()->exe_modref;
1266 else
1267 wm = MODULE_FindModule( module );
1269 return wm? wm->module : 0;
1272 /***********************************************************************
1273 * GetModuleHandleW
1275 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
1277 HMODULE hModule;
1278 LPSTR modulea = HEAP_strdupWtoA( GetProcessHeap(), 0, module );
1279 hModule = GetModuleHandleA( modulea );
1280 HeapFree( GetProcessHeap(), 0, modulea );
1281 return hModule;
1285 /***********************************************************************
1286 * GetModuleFileNameA (KERNEL32.235)
1288 * GetModuleFileNameA seems to *always* return the long path;
1289 * it's only GetModuleFileName16 that decides between short/long path
1290 * by checking if exe version >= 4.0.
1291 * (SDK docu doesn't mention this)
1293 DWORD WINAPI GetModuleFileNameA(
1294 HMODULE hModule, /* [in] module handle (32bit) */
1295 LPSTR lpFileName, /* [out] filenamebuffer */
1296 DWORD size /* [in] size of filenamebuffer */
1297 ) {
1298 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1300 if (!wm) /* can happen on start up or the like */
1301 return 0;
1303 lstrcpynA( lpFileName, wm->filename, size );
1305 TRACE("%s\n", lpFileName );
1306 return strlen(lpFileName);
1310 /***********************************************************************
1311 * GetModuleFileNameW (KERNEL32.236)
1313 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName,
1314 DWORD size )
1316 LPSTR fnA = (char*)HeapAlloc( GetProcessHeap(), 0, size );
1317 DWORD res = GetModuleFileNameA( hModule, fnA, size );
1318 lstrcpynAtoW( lpFileName, fnA, size );
1319 HeapFree( GetProcessHeap(), 0, fnA );
1320 return res;
1324 /***********************************************************************
1325 * LoadLibraryExA (KERNEL32)
1327 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
1329 WINE_MODREF *wm;
1331 if(!libname)
1333 SetLastError(ERROR_INVALID_PARAMETER);
1334 return 0;
1337 EnterCriticalSection(&PROCESS_Current()->crit_section);
1339 wm = MODULE_LoadLibraryExA( libname, hfile, flags );
1340 if ( wm )
1342 if ( !MODULE_DllProcessAttach( wm, NULL ) )
1344 WARN_(module)("Attach failed for module '%s', \n", libname);
1345 MODULE_FreeLibrary(wm);
1346 SetLastError(ERROR_DLL_INIT_FAILED);
1347 wm = NULL;
1351 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1353 return wm ? wm->module : 0;
1356 /***********************************************************************
1357 * MODULE_LoadLibraryExA (internal)
1359 * Load a PE style module according to the load order.
1361 * The HFILE parameter is not used and marked reserved in the SDK. I can
1362 * only guess that it should force a file to be mapped, but I rather
1363 * ignore the parameter because it would be extremely difficult to
1364 * integrate this with different types of module represenations.
1367 WINE_MODREF *MODULE_LoadLibraryExA( LPCSTR libname, HFILE hfile, DWORD flags )
1369 DWORD err = GetLastError();
1370 WINE_MODREF *pwm;
1371 int i;
1372 module_loadorder_t *plo;
1374 EnterCriticalSection(&PROCESS_Current()->crit_section);
1376 /* Check for already loaded module */
1377 if((pwm = MODULE_FindModule(libname)))
1379 if(!(pwm->flags & WINE_MODREF_MARKER))
1380 pwm->refCount++;
1381 TRACE("Already loaded module '%s' at 0x%08x, count=%d, \n", libname, pwm->module, pwm->refCount);
1382 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1383 return pwm;
1386 plo = MODULE_GetLoadOrder(libname);
1388 for(i = 0; i < MODULE_LOADORDER_NTYPES; i++)
1390 SetLastError( ERROR_FILE_NOT_FOUND );
1391 switch(plo->loadorder[i])
1393 case MODULE_LOADORDER_DLL:
1394 TRACE("Trying native dll '%s'\n", libname);
1395 pwm = PE_LoadLibraryExA(libname, flags);
1396 break;
1398 case MODULE_LOADORDER_ELFDLL:
1399 TRACE("Trying elfdll '%s'\n", libname);
1400 if (!(pwm = BUILTIN32_LoadLibraryExA(libname, flags)))
1401 pwm = ELFDLL_LoadLibraryExA(libname, flags);
1402 break;
1404 case MODULE_LOADORDER_SO:
1405 TRACE("Trying so-library '%s'\n", libname);
1406 if (!(pwm = BUILTIN32_LoadLibraryExA(libname, flags)))
1407 pwm = ELF_LoadLibraryExA(libname, flags);
1408 break;
1410 case MODULE_LOADORDER_BI:
1411 TRACE("Trying built-in '%s'\n", libname);
1412 pwm = BUILTIN32_LoadLibraryExA(libname, flags);
1413 break;
1415 default:
1416 ERR("Got invalid loadorder type %d (%s index %d)\n", plo->loadorder[i], plo->modulename, i);
1417 /* Fall through */
1419 case MODULE_LOADORDER_INVALID: /* We ignore this as it is an empty entry */
1420 pwm = NULL;
1421 break;
1424 if(pwm)
1426 /* Initialize DLL just loaded */
1427 TRACE("Loaded module '%s' at 0x%08x, \n", libname, pwm->module);
1429 /* Set the refCount here so that an attach failure will */
1430 /* decrement the dependencies through the MODULE_FreeLibrary call. */
1431 pwm->refCount++;
1433 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1434 SetLastError( err ); /* restore last error */
1435 return pwm;
1438 if(GetLastError() != ERROR_FILE_NOT_FOUND)
1439 break;
1442 WARN("Failed to load module '%s'; error=0x%08lx, \n", libname, GetLastError());
1443 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1444 return NULL;
1447 /***********************************************************************
1448 * LoadLibraryA (KERNEL32)
1450 HMODULE WINAPI LoadLibraryA(LPCSTR libname) {
1451 return LoadLibraryExA(libname,0,0);
1454 /***********************************************************************
1455 * LoadLibraryW (KERNEL32)
1457 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
1459 return LoadLibraryExW(libnameW,0,0);
1462 /***********************************************************************
1463 * LoadLibrary32_16 (KERNEL.452)
1465 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
1467 HMODULE hModule;
1469 SYSLEVEL_ReleaseWin16Lock();
1470 hModule = LoadLibraryA( libname );
1471 SYSLEVEL_RestoreWin16Lock();
1473 return hModule;
1476 /***********************************************************************
1477 * LoadLibraryExW (KERNEL32)
1479 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW,HANDLE hfile,DWORD flags)
1481 LPSTR libnameA = HEAP_strdupWtoA( GetProcessHeap(), 0, libnameW );
1482 HMODULE ret = LoadLibraryExA( libnameA , hfile, flags );
1484 HeapFree( GetProcessHeap(), 0, libnameA );
1485 return ret;
1488 /***********************************************************************
1489 * MODULE_FlushModrefs
1491 * NOTE: Assumes that the process critical section is held!
1493 * Remove all unused modrefs and call the internal unloading routines
1494 * for the library type.
1496 static void MODULE_FlushModrefs(void)
1498 WINE_MODREF *wm, *next;
1500 for(wm = PROCESS_Current()->modref_list; wm; wm = next)
1502 next = wm->next;
1504 if(wm->refCount)
1505 continue;
1507 /* Unlink this modref from the chain */
1508 if(wm->next)
1509 wm->next->prev = wm->prev;
1510 if(wm->prev)
1511 wm->prev->next = wm->next;
1512 if(wm == PROCESS_Current()->modref_list)
1513 PROCESS_Current()->modref_list = wm->next;
1516 * The unloaders are also responsible for freeing the modref itself
1517 * because the loaders were responsible for allocating it.
1519 switch(wm->type)
1521 case MODULE32_PE: PE_UnloadLibrary(wm); break;
1522 case MODULE32_ELF: ELF_UnloadLibrary(wm); break;
1523 case MODULE32_ELFDLL: ELFDLL_UnloadLibrary(wm); break;
1524 case MODULE32_BI: BUILTIN32_UnloadLibrary(wm); break;
1526 default:
1527 ERR("Invalid or unhandled MODREF type %d encountered (wm=%p)\n", wm->type, wm);
1532 /***********************************************************************
1533 * FreeLibrary
1535 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
1537 BOOL retv = FALSE;
1538 WINE_MODREF *wm;
1540 EnterCriticalSection( &PROCESS_Current()->crit_section );
1541 PROCESS_Current()->free_lib_count++;
1543 wm = MODULE32_LookupHMODULE( hLibModule );
1544 if ( !wm || !hLibModule )
1545 SetLastError( ERROR_INVALID_HANDLE );
1546 else
1547 retv = MODULE_FreeLibrary( wm );
1549 PROCESS_Current()->free_lib_count--;
1550 LeaveCriticalSection( &PROCESS_Current()->crit_section );
1552 return retv;
1555 /***********************************************************************
1556 * MODULE_DecRefCount
1558 * NOTE: Assumes that the process critical section is held!
1560 static void MODULE_DecRefCount( WINE_MODREF *wm )
1562 int i;
1564 if ( wm->flags & WINE_MODREF_MARKER )
1565 return;
1567 if ( wm->refCount <= 0 )
1568 return;
1570 --wm->refCount;
1571 TRACE("(%s) refCount: %d\n", wm->modname, wm->refCount );
1573 if ( wm->refCount == 0 )
1575 wm->flags |= WINE_MODREF_MARKER;
1577 for ( i = 0; i < wm->nDeps; i++ )
1578 if ( wm->deps[i] )
1579 MODULE_DecRefCount( wm->deps[i] );
1581 wm->flags &= ~WINE_MODREF_MARKER;
1585 /***********************************************************************
1586 * MODULE_FreeLibrary
1588 * NOTE: Assumes that the process critical section is held!
1590 BOOL MODULE_FreeLibrary( WINE_MODREF *wm )
1592 TRACE("(%s) - START\n", wm->modname );
1594 /* Recursively decrement reference counts */
1595 MODULE_DecRefCount( wm );
1597 /* Call process detach notifications */
1598 if ( PROCESS_Current()->free_lib_count <= 1 )
1600 struct unload_dll_request *req = get_req_buffer();
1602 MODULE_DllProcessDetach( FALSE, NULL );
1603 req->base = (void *)wm->module;
1604 server_call_noerr( REQ_UNLOAD_DLL );
1607 TRACE("END\n");
1609 MODULE_FlushModrefs();
1611 return TRUE;
1615 /***********************************************************************
1616 * FreeLibraryAndExitThread
1618 VOID WINAPI FreeLibraryAndExitThread(HINSTANCE hLibModule, DWORD dwExitCode)
1620 FreeLibrary(hLibModule);
1621 ExitThread(dwExitCode);
1624 /***********************************************************************
1625 * PrivateLoadLibrary (KERNEL32)
1627 * FIXME: rough guesswork, don't know what "Private" means
1629 HINSTANCE WINAPI PrivateLoadLibrary(LPCSTR libname)
1631 return (HINSTANCE)LoadLibrary16(libname);
1636 /***********************************************************************
1637 * PrivateFreeLibrary (KERNEL32)
1639 * FIXME: rough guesswork, don't know what "Private" means
1641 void WINAPI PrivateFreeLibrary(HINSTANCE handle)
1643 FreeLibrary16((HINSTANCE16)handle);
1647 /***********************************************************************
1648 * WIN32_GetProcAddress16 (KERNEL32.36)
1649 * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
1651 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
1653 WORD ordinal;
1654 FARPROC16 ret;
1656 if (!hModule) {
1657 WARN("hModule may not be 0!\n");
1658 return (FARPROC16)0;
1660 if (HIWORD(hModule))
1662 WARN("hModule is Win32 handle (%08x)\n", hModule );
1663 return (FARPROC16)0;
1665 hModule = GetExePtr( hModule );
1666 if (HIWORD(name)) {
1667 ordinal = NE_GetOrdinal( hModule, name );
1668 TRACE("%04x '%s'\n", hModule, name );
1669 } else {
1670 ordinal = LOWORD(name);
1671 TRACE("%04x %04x\n", hModule, ordinal );
1673 if (!ordinal) return (FARPROC16)0;
1674 ret = NE_GetEntryPoint( hModule, ordinal );
1675 TRACE("returning %08x\n",(UINT)ret);
1676 return ret;
1679 /***********************************************************************
1680 * GetProcAddress16 (KERNEL.50)
1682 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, SEGPTR name )
1684 WORD ordinal;
1685 FARPROC16 ret;
1687 if (!hModule) hModule = GetCurrentTask();
1688 hModule = GetExePtr( hModule );
1690 if (HIWORD(name) != 0)
1692 ordinal = NE_GetOrdinal( hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1693 TRACE("%04x '%s'\n", hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1695 else
1697 ordinal = LOWORD(name);
1698 TRACE("%04x %04x\n", hModule, ordinal );
1700 if (!ordinal) return (FARPROC16)0;
1702 ret = NE_GetEntryPoint( hModule, ordinal );
1704 TRACE("returning %08x\n", (UINT)ret );
1705 return ret;
1709 /***********************************************************************
1710 * GetProcAddress (KERNEL32.257)
1712 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1714 return MODULE_GetProcAddress( hModule, function, TRUE );
1717 /***********************************************************************
1718 * GetProcAddress32 (KERNEL.453)
1720 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
1722 return MODULE_GetProcAddress( hModule, function, FALSE );
1725 /***********************************************************************
1726 * MODULE_GetProcAddress (internal)
1728 FARPROC MODULE_GetProcAddress(
1729 HMODULE hModule, /* [in] current module handle */
1730 LPCSTR function, /* [in] function to be looked up */
1731 BOOL snoop )
1733 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1734 FARPROC retproc;
1736 if (HIWORD(function))
1737 TRACE_(win32)("(%08lx,%s)\n",(DWORD)hModule,function);
1738 else
1739 TRACE_(win32)("(%08lx,%p)\n",(DWORD)hModule,function);
1740 if (!wm) {
1741 SetLastError(ERROR_INVALID_HANDLE);
1742 return (FARPROC)0;
1744 switch (wm->type)
1746 case MODULE32_PE:
1747 retproc = PE_FindExportedFunction( wm, function, snoop );
1748 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1749 return retproc;
1750 case MODULE32_ELF:
1751 retproc = ELF_FindExportedFunction( wm, function);
1752 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1753 return retproc;
1754 default:
1755 ERR("wine_modref type %d not handled.\n",wm->type);
1756 SetLastError(ERROR_INVALID_HANDLE);
1757 return (FARPROC)0;
1762 /***********************************************************************
1763 * RtlImageNtHeader (NTDLL)
1765 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
1767 /* basically:
1768 * return hModule+(((IMAGE_DOS_HEADER*)hModule)->e_lfanew);
1769 * but we could get HMODULE16 or the like (think builtin modules)
1772 WINE_MODREF *wm = MODULE32_LookupHMODULE( hModule );
1773 if (!wm || (wm->type != MODULE32_PE)) return (PIMAGE_NT_HEADERS)0;
1774 return PE_HEADER(wm->module);
1778 /***************************************************************************
1779 * HasGPHandler (KERNEL.338)
1782 #include "pshpack1.h"
1783 typedef struct _GPHANDLERDEF
1785 WORD selector;
1786 WORD rangeStart;
1787 WORD rangeEnd;
1788 WORD handler;
1789 } GPHANDLERDEF;
1790 #include "poppack.h"
1792 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1794 HMODULE16 hModule;
1795 int gpOrdinal;
1796 SEGPTR gpPtr;
1797 GPHANDLERDEF *gpHandler;
1799 if ( (hModule = FarGetOwner16( SELECTOROF(address) )) != 0
1800 && (gpOrdinal = NE_GetOrdinal( hModule, "__GP" )) != 0
1801 && (gpPtr = (SEGPTR)NE_GetEntryPointEx( hModule, gpOrdinal, FALSE )) != 0
1802 && !IsBadReadPtr16( gpPtr, sizeof(GPHANDLERDEF) )
1803 && (gpHandler = PTR_SEG_TO_LIN( gpPtr )) != NULL )
1805 while (gpHandler->selector)
1807 if ( SELECTOROF(address) == gpHandler->selector
1808 && OFFSETOF(address) >= gpHandler->rangeStart
1809 && OFFSETOF(address) < gpHandler->rangeEnd )
1810 return PTR_SEG_OFF_TO_SEGPTR( gpHandler->selector,
1811 gpHandler->handler );
1812 gpHandler++;
1816 return 0;