Added missing const to external tables definitions.
[wine/hacks.git] / loader / module.c
blob6fe61788ab5f7c1951f8bf1c553aa1e73786e2ce
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 "wine/winbase16.h"
15 #include "winerror.h"
16 #include "heap.h"
17 #include "neexe.h"
18 #include "process.h"
19 #include "syslevel.h"
20 #include "selectors.h"
21 #include "debugtools.h"
22 #include "callback.h"
23 #include "loadorder.h"
24 #include "elfdll.h"
25 #include "server.h"
27 DEFAULT_DEBUG_CHANNEL(module);
28 DECLARE_DEBUG_CHANNEL(win32);
31 /*************************************************************************
32 * MODULE32_LookupHMODULE
33 * looks for the referenced HMODULE in the current process
34 * NOTE: Assumes that the process critical section is held!
36 static WINE_MODREF *MODULE32_LookupHMODULE( HMODULE hmod )
38 WINE_MODREF *wm;
40 if (!hmod)
41 return PROCESS_Current()->exe_modref;
43 if (!HIWORD(hmod)) {
44 ERR("tried to lookup 0x%04x in win32 module handler!\n",hmod);
45 SetLastError( ERROR_INVALID_HANDLE );
46 return NULL;
48 for ( wm = PROCESS_Current()->modref_list; wm; wm=wm->next )
49 if (wm->module == hmod)
50 return wm;
51 SetLastError( ERROR_INVALID_HANDLE );
52 return NULL;
55 /*************************************************************************
56 * MODULE_AllocModRef
58 * Allocate a WINE_MODREF structure and add it to the process list
59 * NOTE: Assumes that the process critical section is held!
61 WINE_MODREF *MODULE_AllocModRef( HMODULE hModule, LPCSTR filename )
63 WINE_MODREF *wm;
64 DWORD len;
66 if ((wm = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*wm) )))
68 wm->module = hModule;
69 wm->tlsindex = -1;
71 wm->filename = HEAP_strdupA( GetProcessHeap(), 0, filename );
72 if ((wm->modname = strrchr( wm->filename, '\\' ))) wm->modname++;
73 else wm->modname = wm->filename;
75 len = GetShortPathNameA( wm->filename, NULL, 0 );
76 wm->short_filename = (char *)HeapAlloc( GetProcessHeap(), 0, len+1 );
77 GetShortPathNameA( wm->filename, wm->short_filename, len+1 );
78 if ((wm->short_modname = strrchr( wm->short_filename, '\\' ))) wm->short_modname++;
79 else wm->short_modname = wm->short_filename;
81 wm->next = PROCESS_Current()->modref_list;
82 if (wm->next) wm->next->prev = wm;
83 PROCESS_Current()->modref_list = wm;
85 return wm;
88 /*************************************************************************
89 * MODULE_InitDLL
91 static BOOL MODULE_InitDLL( WINE_MODREF *wm, DWORD type, LPVOID lpReserved )
93 BOOL retv = TRUE;
95 static LPCSTR typeName[] = { "PROCESS_DETACH", "PROCESS_ATTACH",
96 "THREAD_ATTACH", "THREAD_DETACH" };
97 assert( wm );
99 /* Skip calls for modules loaded with special load flags */
101 if (wm->flags & WINE_MODREF_DONT_RESOLVE_REFS) return TRUE;
103 TRACE("(%s,%s,%p) - CALL\n", wm->modname, typeName[type], lpReserved );
105 /* Call the initialization routine */
106 retv = PE_InitDLL( wm->module, type, lpReserved );
108 /* The state of the module list may have changed due to the call
109 to PE_InitDLL. We cannot assume that this module has not been
110 deleted. */
111 TRACE("(%p,%s,%p) - RETURN %d\n", wm, typeName[type], lpReserved, retv );
113 return retv;
116 /*************************************************************************
117 * MODULE_DllProcessAttach
119 * Send the process attach notification to all DLLs the given module
120 * depends on (recursively). This is somewhat complicated due to the fact that
122 * - we have to respect the module dependencies, i.e. modules implicitly
123 * referenced by another module have to be initialized before the module
124 * itself can be initialized
126 * - the initialization routine of a DLL can itself call LoadLibrary,
127 * thereby introducing a whole new set of dependencies (even involving
128 * the 'old' modules) at any time during the whole process
130 * (Note that this routine can be recursively entered not only directly
131 * from itself, but also via LoadLibrary from one of the called initialization
132 * routines.)
134 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
135 * the process *detach* notifications to be sent in the correct order.
136 * This must not only take into account module dependencies, but also
137 * 'hidden' dependencies created by modules calling LoadLibrary in their
138 * attach notification routine.
140 * The strategy is rather simple: we move a WINE_MODREF to the head of the
141 * list after the attach notification has returned. This implies that the
142 * detach notifications are called in the reverse of the sequence the attach
143 * notifications *returned*.
145 * NOTE: Assumes that the process critical section is held!
148 BOOL MODULE_DllProcessAttach( WINE_MODREF *wm, LPVOID lpReserved )
150 BOOL retv = TRUE;
151 int i;
152 assert( wm );
154 /* prevent infinite recursion in case of cyclical dependencies */
155 if ( ( wm->flags & WINE_MODREF_MARKER )
156 || ( wm->flags & WINE_MODREF_PROCESS_ATTACHED ) )
157 return retv;
159 TRACE("(%s,%p) - START\n", wm->modname, lpReserved );
161 /* Tag current MODREF to prevent recursive loop */
162 wm->flags |= WINE_MODREF_MARKER;
164 /* Recursively attach all DLLs this one depends on */
165 for ( i = 0; retv && i < wm->nDeps; i++ )
166 if ( wm->deps[i] )
167 retv = MODULE_DllProcessAttach( wm->deps[i], lpReserved );
169 /* Call DLL entry point */
170 if ( retv )
172 retv = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
173 if ( retv )
174 wm->flags |= WINE_MODREF_PROCESS_ATTACHED;
177 /* Re-insert MODREF at head of list */
178 if ( retv && wm->prev )
180 wm->prev->next = wm->next;
181 if ( wm->next ) wm->next->prev = wm->prev;
183 wm->prev = NULL;
184 wm->next = PROCESS_Current()->modref_list;
185 PROCESS_Current()->modref_list = wm->next->prev = wm;
188 /* Remove recursion flag */
189 wm->flags &= ~WINE_MODREF_MARKER;
191 TRACE("(%s,%p) - END\n", wm->modname, lpReserved );
193 return retv;
196 /*************************************************************************
197 * MODULE_DllProcessDetach
199 * Send DLL process detach notifications. See the comment about calling
200 * sequence at MODULE_DllProcessAttach. Unless the bForceDetach flag
201 * is set, only DLLs with zero refcount are notified.
203 void MODULE_DllProcessDetach( BOOL bForceDetach, LPVOID lpReserved )
205 WINE_MODREF *wm;
207 EnterCriticalSection( &PROCESS_Current()->crit_section );
211 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
213 /* Check whether to detach this DLL */
214 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
215 continue;
216 if ( wm->refCount > 0 && !bForceDetach )
217 continue;
219 /* Call detach notification */
220 wm->flags &= ~WINE_MODREF_PROCESS_ATTACHED;
221 MODULE_InitDLL( wm, DLL_PROCESS_DETACH, lpReserved );
223 /* Restart at head of WINE_MODREF list, as entries might have
224 been added and/or removed while performing the call ... */
225 break;
227 } while ( wm );
229 LeaveCriticalSection( &PROCESS_Current()->crit_section );
232 /*************************************************************************
233 * MODULE_DllThreadAttach
235 * Send DLL thread attach notifications. These are sent in the
236 * reverse sequence of process detach notification.
239 void MODULE_DllThreadAttach( LPVOID lpReserved )
241 WINE_MODREF *wm;
243 EnterCriticalSection( &PROCESS_Current()->crit_section );
245 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
246 if ( !wm->next )
247 break;
249 for ( ; wm; wm = wm->prev )
251 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
252 continue;
253 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
254 continue;
256 MODULE_InitDLL( wm, DLL_THREAD_ATTACH, lpReserved );
259 LeaveCriticalSection( &PROCESS_Current()->crit_section );
262 /*************************************************************************
263 * MODULE_DllThreadDetach
265 * Send DLL thread detach notifications. These are sent in the
266 * same sequence as process detach notification.
269 void MODULE_DllThreadDetach( LPVOID lpReserved )
271 WINE_MODREF *wm;
273 EnterCriticalSection( &PROCESS_Current()->crit_section );
275 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
277 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
278 continue;
279 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
280 continue;
282 MODULE_InitDLL( wm, DLL_THREAD_DETACH, lpReserved );
285 LeaveCriticalSection( &PROCESS_Current()->crit_section );
288 /****************************************************************************
289 * DisableThreadLibraryCalls (KERNEL32.74)
291 * Don't call DllEntryPoint for DLL_THREAD_{ATTACH,DETACH} if set.
293 BOOL WINAPI DisableThreadLibraryCalls( HMODULE hModule )
295 WINE_MODREF *wm;
296 BOOL retval = TRUE;
298 EnterCriticalSection( &PROCESS_Current()->crit_section );
300 wm = MODULE32_LookupHMODULE( hModule );
301 if ( !wm )
302 retval = FALSE;
303 else
304 wm->flags |= WINE_MODREF_NO_DLL_CALLS;
306 LeaveCriticalSection( &PROCESS_Current()->crit_section );
308 return retval;
312 /***********************************************************************
313 * MODULE_CreateDummyModule
315 * Create a dummy NE module for Win32 or Winelib.
317 HMODULE MODULE_CreateDummyModule( LPCSTR filename, HMODULE module32 )
319 HMODULE hModule;
320 NE_MODULE *pModule;
321 SEGTABLEENTRY *pSegment;
322 char *pStr,*s;
323 unsigned int len;
324 const char* basename;
325 OFSTRUCT *ofs;
326 int of_size, size;
328 /* Extract base filename */
329 basename = strrchr(filename, '\\');
330 if (!basename) basename = filename;
331 else basename++;
332 len = strlen(basename);
333 if ((s = strchr(basename, '.'))) len = s - basename;
335 /* Allocate module */
336 of_size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName)
337 + strlen(filename) + 1;
338 size = sizeof(NE_MODULE) +
339 /* loaded file info */
340 of_size +
341 /* segment table: DS,CS */
342 2 * sizeof(SEGTABLEENTRY) +
343 /* name table */
344 len + 2 +
345 /* several empty tables */
348 hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
349 if (!hModule) return (HMODULE)11; /* invalid exe */
351 FarSetOwner16( hModule, hModule );
352 pModule = (NE_MODULE *)GlobalLock16( hModule );
354 /* Set all used entries */
355 pModule->magic = IMAGE_OS2_SIGNATURE;
356 pModule->count = 1;
357 pModule->next = 0;
358 pModule->flags = 0;
359 pModule->dgroup = 0;
360 pModule->ss = 1;
361 pModule->cs = 2;
362 pModule->heap_size = 0;
363 pModule->stack_size = 0;
364 pModule->seg_count = 2;
365 pModule->modref_count = 0;
366 pModule->nrname_size = 0;
367 pModule->fileinfo = sizeof(NE_MODULE);
368 pModule->os_flags = NE_OSFLAGS_WINDOWS;
369 pModule->self = hModule;
370 pModule->module32 = module32;
372 /* Set version and flags */
373 if (module32)
375 pModule->expected_version =
376 ((PE_HEADER(module32)->OptionalHeader.MajorSubsystemVersion & 0xff) << 8 ) |
377 (PE_HEADER(module32)->OptionalHeader.MinorSubsystemVersion & 0xff);
378 pModule->flags |= NE_FFLAGS_WIN32;
379 if (PE_HEADER(module32)->FileHeader.Characteristics & IMAGE_FILE_DLL)
380 pModule->flags |= NE_FFLAGS_LIBMODULE | NE_FFLAGS_SINGLEDATA;
383 /* Set loaded file information */
384 ofs = (OFSTRUCT *)(pModule + 1);
385 memset( ofs, 0, of_size );
386 ofs->cBytes = of_size < 256 ? of_size : 255; /* FIXME */
387 strcpy( ofs->szPathName, filename );
389 pSegment = (SEGTABLEENTRY*)((char*)(pModule + 1) + of_size);
390 pModule->seg_table = (int)pSegment - (int)pModule;
391 /* Data segment */
392 pSegment->size = 0;
393 pSegment->flags = NE_SEGFLAGS_DATA;
394 pSegment->minsize = 0x1000;
395 pSegment++;
396 /* Code segment */
397 pSegment->flags = 0;
398 pSegment++;
400 /* Module name */
401 pStr = (char *)pSegment;
402 pModule->name_table = (int)pStr - (int)pModule;
403 assert(len<256);
404 *pStr = len;
405 lstrcpynA( pStr+1, basename, len+1 );
406 pStr += len+2;
408 /* All tables zero terminated */
409 pModule->res_table = pModule->import_table = pModule->entry_table =
410 (int)pStr - (int)pModule;
412 NE_RegisterModule( pModule );
413 return hModule;
417 /**********************************************************************
418 * MODULE_FindModule
420 * Find a (loaded) win32 module depending on path
422 * RETURNS
423 * the module handle if found
424 * 0 if not
426 WINE_MODREF *MODULE_FindModule(
427 LPCSTR path /* [in] pathname of module/library to be found */
429 WINE_MODREF *wm;
430 char dllname[260], *p;
432 /* Append .DLL to name if no extension present */
433 strcpy( dllname, path );
434 if (!(p = strrchr( dllname, '.')) || strchr( p, '/' ) || strchr( p, '\\'))
435 strcat( dllname, ".DLL" );
437 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
439 if ( !strcasecmp( dllname, wm->modname ) )
440 break;
441 if ( !strcasecmp( dllname, wm->filename ) )
442 break;
443 if ( !strcasecmp( dllname, wm->short_modname ) )
444 break;
445 if ( !strcasecmp( dllname, wm->short_filename ) )
446 break;
449 return wm;
453 /* Check whether a file is an OS/2 or a very old Windows executable
454 * by testing on import of KERNEL.
456 * FIXME: is reading the module imports the only way of discerning
457 * old Windows binaries from OS/2 ones ? At least it seems so...
459 static DWORD MODULE_Decide_OS2_OldWin(HANDLE hfile, IMAGE_DOS_HEADER *mz, IMAGE_OS2_HEADER *ne)
461 DWORD currpos = SetFilePointer( hfile, 0, NULL, SEEK_CUR);
462 DWORD type = SCS_OS216_BINARY;
463 LPWORD modtab = NULL;
464 LPSTR nametab = NULL;
465 DWORD len;
466 int i;
468 /* read modref table */
469 if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_modtab, NULL, SEEK_SET ) == -1)
470 || (!(modtab = HeapAlloc( GetProcessHeap(), 0, ne->ne_cmod*sizeof(WORD))))
471 || (!(ReadFile(hfile, modtab, ne->ne_cmod*sizeof(WORD), &len, NULL)))
472 || (len != ne->ne_cmod*sizeof(WORD)) )
473 goto broken;
475 /* read imported names table */
476 if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_imptab, NULL, SEEK_SET ) == -1)
477 || (!(nametab = HeapAlloc( GetProcessHeap(), 0, ne->ne_enttab - ne->ne_imptab)))
478 || (!(ReadFile(hfile, nametab, ne->ne_enttab - ne->ne_imptab, &len, NULL)))
479 || (len != ne->ne_enttab - ne->ne_imptab) )
480 goto broken;
482 for (i=0; i < ne->ne_cmod; i++)
484 LPSTR module = &nametab[modtab[i]];
485 TRACE("modref: %.*s\n", module[0], &module[1]);
486 if (!(strncmp(&module[1], "KERNEL", module[0])))
487 { /* very old Windows file */
488 MESSAGE("This seems to be a very old (pre-3.0) Windows executable. Expect crashes, especially if this is a real-mode binary !\n");
489 type = SCS_WOW_BINARY;
490 goto good;
494 broken:
495 ERR("Hmm, an error occurred. Is this binary file broken ?\n");
497 good:
498 HeapFree( GetProcessHeap(), 0, modtab);
499 HeapFree( GetProcessHeap(), 0, nametab);
500 SetFilePointer( hfile, currpos, NULL, SEEK_SET); /* restore filepos */
501 return type;
504 /***********************************************************************
505 * MODULE_GetBinaryType
507 * The GetBinaryType function determines whether a file is executable
508 * or not and if it is it returns what type of executable it is.
509 * The type of executable is a property that determines in which
510 * subsystem an executable file runs under.
512 * Binary types returned:
513 * SCS_32BIT_BINARY: A Win32 based application
514 * SCS_DOS_BINARY: An MS-Dos based application
515 * SCS_WOW_BINARY: A Win16 based application
516 * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
517 * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
518 * SCS_OS216_BINARY: A 16bit OS/2 based application
520 * Returns TRUE if the file is an executable in which case
521 * the value pointed by lpBinaryType is set.
522 * Returns FALSE if the file is not an executable or if the function fails.
524 * To do so it opens the file and reads in the header information
525 * if the extended header information is not present it will
526 * assume that the file is a DOS executable.
527 * If the extended header information is present it will
528 * determine if the file is a 16 or 32 bit Windows executable
529 * by check the flags in the header.
531 * Note that .COM and .PIF files are only recognized by their
532 * file name extension; but Windows does it the same way ...
534 BOOL MODULE_GetBinaryType( HANDLE hfile, LPCSTR filename, LPDWORD lpBinaryType )
536 IMAGE_DOS_HEADER mz_header;
537 char magic[4], *ptr;
538 DWORD len;
540 /* Seek to the start of the file and read the DOS header information.
542 if ( SetFilePointer( hfile, 0, NULL, SEEK_SET ) != -1
543 && ReadFile( hfile, &mz_header, sizeof(mz_header), &len, NULL )
544 && len == sizeof(mz_header) )
546 /* Now that we have the header check the e_magic field
547 * to see if this is a dos image.
549 if ( mz_header.e_magic == IMAGE_DOS_SIGNATURE )
551 BOOL lfanewValid = FALSE;
552 /* We do have a DOS image so we will now try to seek into
553 * the file by the amount indicated by the field
554 * "Offset to extended header" and read in the
555 * "magic" field information at that location.
556 * This will tell us if there is more header information
557 * to read or not.
559 /* But before we do we will make sure that header
560 * structure encompasses the "Offset to extended header"
561 * field.
563 if ( (mz_header.e_cparhdr<<4) >= sizeof(IMAGE_DOS_HEADER) )
564 if ( ( mz_header.e_crlc == 0 ) ||
565 ( mz_header.e_lfarlc >= sizeof(IMAGE_DOS_HEADER) ) )
566 if ( mz_header.e_lfanew >= sizeof(IMAGE_DOS_HEADER)
567 && SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET ) != -1
568 && ReadFile( hfile, magic, sizeof(magic), &len, NULL )
569 && len == sizeof(magic) )
570 lfanewValid = TRUE;
572 if ( !lfanewValid )
574 /* If we cannot read this "extended header" we will
575 * assume that we have a simple DOS executable.
577 *lpBinaryType = SCS_DOS_BINARY;
578 return TRUE;
580 else
582 /* Reading the magic field succeeded so
583 * we will try to determine what type it is.
585 if ( *(DWORD*)magic == IMAGE_NT_SIGNATURE )
587 /* This is an NT signature.
589 *lpBinaryType = SCS_32BIT_BINARY;
590 return TRUE;
592 else if ( *(WORD*)magic == IMAGE_OS2_SIGNATURE )
594 /* The IMAGE_OS2_SIGNATURE indicates that the
595 * "extended header is a Windows executable (NE)
596 * header." This can mean either a 16-bit OS/2
597 * or a 16-bit Windows or even a DOS program
598 * (running under a DOS extender). To decide
599 * which, we'll have to read the NE header.
602 IMAGE_OS2_HEADER ne;
603 if ( SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET ) != -1
604 && ReadFile( hfile, &ne, sizeof(ne), &len, NULL )
605 && len == sizeof(ne) )
607 switch ( ne.ne_exetyp )
609 case 2: *lpBinaryType = SCS_WOW_BINARY; return TRUE;
610 case 5: *lpBinaryType = SCS_DOS_BINARY; return TRUE;
611 default: *lpBinaryType =
612 MODULE_Decide_OS2_OldWin(hfile, &mz_header, &ne);
613 return TRUE;
616 /* Couldn't read header, so abort. */
617 return FALSE;
619 else
621 /* Unknown extended header, but this file is nonetheless
622 DOS-executable.
624 *lpBinaryType = SCS_DOS_BINARY;
625 return TRUE;
631 /* If we get here, we don't even have a correct MZ header.
632 * Try to check the file extension for known types ...
634 ptr = strrchr( filename, '.' );
635 if ( ptr && !strchr( ptr, '\\' ) && !strchr( ptr, '/' ) )
637 if ( !strcasecmp( ptr, ".COM" ) )
639 *lpBinaryType = SCS_DOS_BINARY;
640 return TRUE;
643 if ( !strcasecmp( ptr, ".PIF" ) )
645 *lpBinaryType = SCS_PIF_BINARY;
646 return TRUE;
650 return FALSE;
653 /***********************************************************************
654 * GetBinaryTypeA [KERNEL32.280]
656 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
658 BOOL ret = FALSE;
659 HANDLE hfile;
661 TRACE_(win32)("%s\n", lpApplicationName );
663 /* Sanity check.
665 if ( lpApplicationName == NULL || lpBinaryType == NULL )
666 return FALSE;
668 /* Open the file indicated by lpApplicationName for reading.
670 hfile = CreateFileA( lpApplicationName, GENERIC_READ, FILE_SHARE_READ,
671 NULL, OPEN_EXISTING, 0, -1 );
672 if ( hfile == INVALID_HANDLE_VALUE )
673 return FALSE;
675 /* Check binary type
677 ret = MODULE_GetBinaryType( hfile, lpApplicationName, lpBinaryType );
679 /* Close the file.
681 CloseHandle( hfile );
683 return ret;
686 /***********************************************************************
687 * GetBinaryTypeW [KERNEL32.281]
689 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
691 BOOL ret = FALSE;
692 LPSTR strNew = NULL;
694 TRACE_(win32)("%s\n", debugstr_w(lpApplicationName) );
696 /* Sanity check.
698 if ( lpApplicationName == NULL || lpBinaryType == NULL )
699 return FALSE;
701 /* Convert the wide string to a ascii string.
703 strNew = HEAP_strdupWtoA( GetProcessHeap(), 0, lpApplicationName );
705 if ( strNew != NULL )
707 ret = GetBinaryTypeA( strNew, lpBinaryType );
709 /* Free the allocated string.
711 HeapFree( GetProcessHeap(), 0, strNew );
714 return ret;
718 /***********************************************************************
719 * WinExec16 (KERNEL.166)
721 HINSTANCE16 WINAPI WinExec16( LPCSTR lpCmdLine, UINT16 nCmdShow )
723 LPCSTR p = NULL;
724 LPSTR name, cmdline;
725 int len;
726 HINSTANCE16 ret;
727 char buffer[MAX_PATH];
729 if ( ( *lpCmdLine == '"' ) && ( p = strchr ( lpCmdLine+1, '"' ) ) )
730 p = strchr ( p, ' ' );
731 else
732 p = strchr( lpCmdLine, ' ' );
733 if ( p )
735 if (!(name = HeapAlloc( GetProcessHeap(), 0, p - lpCmdLine + 1 )))
736 return ERROR_NOT_ENOUGH_MEMORY;
737 memcpy( name, lpCmdLine, p - lpCmdLine );
738 name[p - lpCmdLine] = 0;
739 p++;
740 len = strlen(p);
741 cmdline = SEGPTR_ALLOC( len + 2 );
742 cmdline[0] = (BYTE)len;
743 strcpy( cmdline + 1, p );
745 else
747 name = (LPSTR)lpCmdLine;
748 cmdline = SEGPTR_ALLOC(2);
749 cmdline[0] = cmdline[1] = 0;
752 if (SearchPathA( NULL, name, ".exe", sizeof(buffer), buffer, NULL ))
754 LOADPARAMS16 params;
755 WORD *showCmd = SEGPTR_ALLOC( 2*sizeof(WORD) );
756 showCmd[0] = 2;
757 showCmd[1] = nCmdShow;
759 params.hEnvironment = 0;
760 params.cmdLine = SEGPTR_GET(cmdline);
761 params.showCmd = SEGPTR_GET(showCmd);
762 params.reserved = 0;
764 ret = LoadModule16( buffer, &params );
766 SEGPTR_FREE( showCmd );
767 SEGPTR_FREE( cmdline );
769 else ret = GetLastError();
771 if (name != lpCmdLine) HeapFree( GetProcessHeap(), 0, name );
773 if (ret == 21) /* 32-bit module */
775 SYSLEVEL_ReleaseWin16Lock();
776 ret = WinExec( lpCmdLine, nCmdShow );
777 SYSLEVEL_RestoreWin16Lock();
779 return ret;
782 /***********************************************************************
783 * WinExec (KERNEL32.566)
785 HINSTANCE WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
787 PROCESS_INFORMATION info;
788 STARTUPINFOA startup;
789 HINSTANCE hInstance;
790 char *cmdline;
792 memset( &startup, 0, sizeof(startup) );
793 startup.cb = sizeof(startup);
794 startup.dwFlags = STARTF_USESHOWWINDOW;
795 startup.wShowWindow = nCmdShow;
797 /* cmdline needs to be writeable for CreateProcess */
798 if (!(cmdline = HEAP_strdupA( GetProcessHeap(), 0, lpCmdLine ))) return 0;
800 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
801 0, NULL, NULL, &startup, &info ))
803 /* Give 30 seconds to the app to come up */
804 if (Callout.WaitForInputIdle ( info.hProcess, 30000 ) == 0xFFFFFFFF)
805 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
806 hInstance = 33;
807 /* Close off the handles */
808 CloseHandle( info.hThread );
809 CloseHandle( info.hProcess );
811 else if ((hInstance = GetLastError()) >= 32)
813 FIXME("Strange error set by CreateProcess: %d\n", hInstance );
814 hInstance = 11;
816 HeapFree( GetProcessHeap(), 0, cmdline );
817 return hInstance;
820 /**********************************************************************
821 * LoadModule (KERNEL32.499)
823 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
825 LOADPARAMS *params = (LOADPARAMS *)paramBlock;
826 PROCESS_INFORMATION info;
827 STARTUPINFOA startup;
828 HINSTANCE hInstance;
829 LPSTR cmdline, p;
830 char filename[MAX_PATH];
831 BYTE len;
833 if (!name) return ERROR_FILE_NOT_FOUND;
835 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
836 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
837 return GetLastError();
839 len = (BYTE)params->lpCmdLine[0];
840 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
841 return ERROR_NOT_ENOUGH_MEMORY;
843 strcpy( cmdline, filename );
844 p = cmdline + strlen(cmdline);
845 *p++ = ' ';
846 memcpy( p, params->lpCmdLine + 1, len );
847 p[len] = 0;
849 memset( &startup, 0, sizeof(startup) );
850 startup.cb = sizeof(startup);
851 if (params->lpCmdShow)
853 startup.dwFlags = STARTF_USESHOWWINDOW;
854 startup.wShowWindow = params->lpCmdShow[1];
857 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
858 params->lpEnvAddress, NULL, &startup, &info ))
860 /* Give 30 seconds to the app to come up */
861 if ( Callout.WaitForInputIdle ( info.hProcess, 30000 ) == 0xFFFFFFFF )
862 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
863 hInstance = 33;
864 /* Close off the handles */
865 CloseHandle( info.hThread );
866 CloseHandle( info.hProcess );
868 else if ((hInstance = GetLastError()) >= 32)
870 FIXME("Strange error set by CreateProcess: %d\n", hInstance );
871 hInstance = 11;
874 HeapFree( GetProcessHeap(), 0, cmdline );
875 return hInstance;
879 /*************************************************************************
880 * get_file_name
882 * Helper for CreateProcess: retrieve the file name to load from the
883 * app name and command line. Store the file name in buffer, and
884 * return a possibly modified command line.
886 static LPSTR get_file_name( LPCSTR appname, LPSTR cmdline, LPSTR buffer, int buflen )
888 char *name, *pos, *ret = NULL;
889 const char *p;
891 /* if we have an app name, everything is easy */
893 if (appname)
895 /* use the unmodified app name as file name */
896 lstrcpynA( buffer, appname, buflen );
897 if (!(ret = cmdline))
899 /* no command-line, create one */
900 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(appname) + 3 )))
901 sprintf( ret, "\"%s\"", appname );
903 return ret;
906 if (!cmdline)
908 SetLastError( ERROR_INVALID_PARAMETER );
909 return NULL;
912 /* first check for a quoted file name */
914 if ((cmdline[0] == '"') && ((p = strchr( cmdline + 1, '"' ))))
916 int len = p - cmdline - 1;
917 /* extract the quoted portion as file name */
918 if (!(name = HeapAlloc( GetProcessHeap(), 0, len + 1 ))) return NULL;
919 memcpy( name, cmdline + 1, len );
920 name[len] = 0;
922 if (SearchPathA( NULL, name, ".exe", buflen, buffer, NULL ) ||
923 SearchPathA( NULL, name, NULL, buflen, buffer, NULL ))
924 ret = cmdline; /* no change necessary */
925 goto done;
928 /* now try the command-line word by word */
930 if (!(name = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 1 ))) return NULL;
931 pos = name;
932 p = cmdline;
934 while (*p)
936 do *pos++ = *p++; while (*p && *p != ' ');
937 *pos = 0;
938 TRACE("trying '%s'\n", name );
939 if (SearchPathA( NULL, name, ".exe", buflen, buffer, NULL ) ||
940 SearchPathA( NULL, name, NULL, buflen, buffer, NULL ))
942 ret = cmdline;
943 break;
947 if (!ret || !strchr( name, ' ' )) goto done; /* no change necessary */
949 /* now build a new command-line with quotes */
951 if (!(ret = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 3 ))) goto done;
952 sprintf( ret, "\"%s\"%s", name, p );
954 done:
955 HeapFree( GetProcessHeap(), 0, name );
956 return ret;
960 /**********************************************************************
961 * CreateProcessA (KERNEL32.171)
963 BOOL WINAPI CreateProcessA( LPCSTR lpApplicationName, LPSTR lpCommandLine,
964 LPSECURITY_ATTRIBUTES lpProcessAttributes,
965 LPSECURITY_ATTRIBUTES lpThreadAttributes,
966 BOOL bInheritHandles, DWORD dwCreationFlags,
967 LPVOID lpEnvironment, LPCSTR lpCurrentDirectory,
968 LPSTARTUPINFOA lpStartupInfo,
969 LPPROCESS_INFORMATION lpProcessInfo )
971 BOOL retv = FALSE;
972 HANDLE hFile;
973 DWORD type;
974 char name[MAX_PATH];
975 LPSTR tidy_cmdline;
977 /* Process the AppName and/or CmdLine to get module name and path */
979 TRACE("app '%s' cmdline '%s'\n", lpApplicationName, lpCommandLine );
981 if (!(tidy_cmdline = get_file_name( lpApplicationName, lpCommandLine, name, sizeof(name) )))
982 return FALSE;
984 /* Warn if unsupported features are used */
986 if (dwCreationFlags & DETACHED_PROCESS)
987 FIXME("(%s,...): DETACHED_PROCESS ignored\n", name);
988 if (dwCreationFlags & CREATE_NEW_CONSOLE)
989 FIXME("(%s,...): CREATE_NEW_CONSOLE ignored\n", name);
990 if (dwCreationFlags & NORMAL_PRIORITY_CLASS)
991 FIXME("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
992 if (dwCreationFlags & IDLE_PRIORITY_CLASS)
993 FIXME("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
994 if (dwCreationFlags & HIGH_PRIORITY_CLASS)
995 FIXME("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
996 if (dwCreationFlags & REALTIME_PRIORITY_CLASS)
997 FIXME("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
998 if (dwCreationFlags & CREATE_NEW_PROCESS_GROUP)
999 FIXME("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
1000 if (dwCreationFlags & CREATE_UNICODE_ENVIRONMENT)
1001 FIXME("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
1002 if (dwCreationFlags & CREATE_SEPARATE_WOW_VDM)
1003 FIXME("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
1004 if (dwCreationFlags & CREATE_SHARED_WOW_VDM)
1005 FIXME("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
1006 if (dwCreationFlags & CREATE_DEFAULT_ERROR_MODE)
1007 FIXME("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
1008 if (dwCreationFlags & CREATE_NO_WINDOW)
1009 FIXME("(%s,...): CREATE_NO_WINDOW ignored\n", name);
1010 if (dwCreationFlags & PROFILE_USER)
1011 FIXME("(%s,...): PROFILE_USER ignored\n", name);
1012 if (dwCreationFlags & PROFILE_KERNEL)
1013 FIXME("(%s,...): PROFILE_KERNEL ignored\n", name);
1014 if (dwCreationFlags & PROFILE_SERVER)
1015 FIXME("(%s,...): PROFILE_SERVER ignored\n", name);
1016 if (lpStartupInfo->lpDesktop)
1017 FIXME("(%s,...): lpStartupInfo->lpDesktop %s ignored\n",
1018 name, lpStartupInfo->lpDesktop);
1019 if (lpStartupInfo->lpTitle)
1020 FIXME("(%s,...): lpStartupInfo->lpTitle %s ignored\n",
1021 name, lpStartupInfo->lpTitle);
1022 if (lpStartupInfo->dwFlags & STARTF_USECOUNTCHARS)
1023 FIXME("(%s,...): STARTF_USECOUNTCHARS (%ld,%ld) ignored\n",
1024 name, lpStartupInfo->dwXCountChars, lpStartupInfo->dwYCountChars);
1025 if (lpStartupInfo->dwFlags & STARTF_USEFILLATTRIBUTE)
1026 FIXME("(%s,...): STARTF_USEFILLATTRIBUTE %lx ignored\n",
1027 name, lpStartupInfo->dwFillAttribute);
1028 if (lpStartupInfo->dwFlags & STARTF_RUNFULLSCREEN)
1029 FIXME("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
1030 if (lpStartupInfo->dwFlags & STARTF_FORCEONFEEDBACK)
1031 FIXME("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
1032 if (lpStartupInfo->dwFlags & STARTF_FORCEOFFFEEDBACK)
1033 FIXME("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
1034 if (lpStartupInfo->dwFlags & STARTF_USEHOTKEY)
1035 FIXME("(%s,...): STARTF_USEHOTKEY ignored\n", name);
1037 /* Open file and determine executable type */
1039 hFile = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, -1 );
1040 if (hFile == INVALID_HANDLE_VALUE) goto done;
1042 if ( !MODULE_GetBinaryType( hFile, name, &type ) )
1044 CloseHandle( hFile );
1045 retv = PROCESS_Create( -1, name, tidy_cmdline, lpEnvironment,
1046 lpProcessAttributes, lpThreadAttributes,
1047 bInheritHandles, dwCreationFlags,
1048 lpStartupInfo, lpProcessInfo, lpCurrentDirectory );
1049 goto done;
1052 /* Create process */
1054 switch ( type )
1056 case SCS_32BIT_BINARY:
1057 case SCS_WOW_BINARY:
1058 case SCS_DOS_BINARY:
1059 retv = PROCESS_Create( hFile, name, tidy_cmdline, lpEnvironment,
1060 lpProcessAttributes, lpThreadAttributes,
1061 bInheritHandles, dwCreationFlags,
1062 lpStartupInfo, lpProcessInfo, lpCurrentDirectory);
1063 break;
1065 case SCS_PIF_BINARY:
1066 case SCS_POSIX_BINARY:
1067 case SCS_OS216_BINARY:
1068 FIXME("Unsupported executable type: %ld\n", type );
1069 /* fall through */
1071 default:
1072 SetLastError( ERROR_BAD_FORMAT );
1073 break;
1075 CloseHandle( hFile );
1077 done:
1078 if (tidy_cmdline != lpCommandLine) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1079 return retv;
1082 /**********************************************************************
1083 * CreateProcessW (KERNEL32.172)
1084 * NOTES
1085 * lpReserved is not converted
1087 BOOL WINAPI CreateProcessW( LPCWSTR lpApplicationName, LPWSTR lpCommandLine,
1088 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1089 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1090 BOOL bInheritHandles, DWORD dwCreationFlags,
1091 LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory,
1092 LPSTARTUPINFOW lpStartupInfo,
1093 LPPROCESS_INFORMATION lpProcessInfo )
1094 { BOOL ret;
1095 STARTUPINFOA StartupInfoA;
1097 LPSTR lpApplicationNameA = HEAP_strdupWtoA (GetProcessHeap(),0,lpApplicationName);
1098 LPSTR lpCommandLineA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCommandLine);
1099 LPSTR lpCurrentDirectoryA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCurrentDirectory);
1101 memcpy (&StartupInfoA, lpStartupInfo, sizeof(STARTUPINFOA));
1102 StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpDesktop);
1103 StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpTitle);
1105 TRACE_(win32)("(%s,%s,...)\n", debugstr_w(lpApplicationName), debugstr_w(lpCommandLine));
1107 if (lpStartupInfo->lpReserved)
1108 FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n", debugstr_w(lpStartupInfo->lpReserved));
1110 ret = CreateProcessA( lpApplicationNameA, lpCommandLineA,
1111 lpProcessAttributes, lpThreadAttributes,
1112 bInheritHandles, dwCreationFlags,
1113 lpEnvironment, lpCurrentDirectoryA,
1114 &StartupInfoA, lpProcessInfo );
1116 HeapFree( GetProcessHeap(), 0, lpCurrentDirectoryA );
1117 HeapFree( GetProcessHeap(), 0, lpCommandLineA );
1118 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1119 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1121 return ret;
1124 /***********************************************************************
1125 * GetModuleHandleA (KERNEL32.237)
1127 HMODULE WINAPI GetModuleHandleA(LPCSTR module)
1129 WINE_MODREF *wm;
1131 if ( module == NULL )
1132 wm = PROCESS_Current()->exe_modref;
1133 else
1134 wm = MODULE_FindModule( module );
1136 return wm? wm->module : 0;
1139 /***********************************************************************
1140 * GetModuleHandleW
1142 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
1144 HMODULE hModule;
1145 LPSTR modulea = HEAP_strdupWtoA( GetProcessHeap(), 0, module );
1146 hModule = GetModuleHandleA( modulea );
1147 HeapFree( GetProcessHeap(), 0, modulea );
1148 return hModule;
1152 /***********************************************************************
1153 * GetModuleFileNameA (KERNEL32.235)
1155 * GetModuleFileNameA seems to *always* return the long path;
1156 * it's only GetModuleFileName16 that decides between short/long path
1157 * by checking if exe version >= 4.0.
1158 * (SDK docu doesn't mention this)
1160 DWORD WINAPI GetModuleFileNameA(
1161 HMODULE hModule, /* [in] module handle (32bit) */
1162 LPSTR lpFileName, /* [out] filenamebuffer */
1163 DWORD size ) /* [in] size of filenamebuffer */
1165 WINE_MODREF *wm;
1167 EnterCriticalSection( &PROCESS_Current()->crit_section );
1169 lpFileName[0] = 0;
1170 if ((wm = MODULE32_LookupHMODULE( hModule )))
1171 lstrcpynA( lpFileName, wm->filename, size );
1173 LeaveCriticalSection( &PROCESS_Current()->crit_section );
1174 TRACE("%s\n", lpFileName );
1175 return strlen(lpFileName);
1179 /***********************************************************************
1180 * GetModuleFileNameW (KERNEL32.236)
1182 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName,
1183 DWORD size )
1185 LPSTR fnA = (char*)HeapAlloc( GetProcessHeap(), 0, size );
1186 DWORD res = GetModuleFileNameA( hModule, fnA, size );
1187 lstrcpynAtoW( lpFileName, fnA, size );
1188 HeapFree( GetProcessHeap(), 0, fnA );
1189 return res;
1193 /***********************************************************************
1194 * LoadLibraryExA (KERNEL32)
1196 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
1198 WINE_MODREF *wm;
1200 if(!libname)
1202 SetLastError(ERROR_INVALID_PARAMETER);
1203 return 0;
1206 if (flags & LOAD_LIBRARY_AS_DATAFILE)
1208 char filename[256];
1209 HFILE hFile;
1210 HMODULE hmod = 0;
1212 if (!SearchPathA( NULL, libname, ".dll", sizeof(filename), filename, NULL ))
1213 return 0;
1214 /* FIXME: maybe we should use the hfile parameter instead */
1215 hFile = CreateFileA( filename, GENERIC_READ, FILE_SHARE_READ,
1216 NULL, OPEN_EXISTING, 0, -1 );
1217 if (hFile != INVALID_HANDLE_VALUE)
1219 hmod = PE_LoadImage( hFile, filename, flags );
1220 CloseHandle( hFile );
1222 return hmod;
1225 EnterCriticalSection(&PROCESS_Current()->crit_section);
1227 wm = MODULE_LoadLibraryExA( libname, hfile, flags );
1228 if ( wm )
1230 if ( !MODULE_DllProcessAttach( wm, NULL ) )
1232 WARN_(module)("Attach failed for module '%s', \n", libname);
1233 MODULE_FreeLibrary(wm);
1234 SetLastError(ERROR_DLL_INIT_FAILED);
1235 wm = NULL;
1239 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1241 return wm ? wm->module : 0;
1244 /***********************************************************************
1245 * MODULE_LoadLibraryExA (internal)
1247 * Load a PE style module according to the load order.
1249 * The HFILE parameter is not used and marked reserved in the SDK. I can
1250 * only guess that it should force a file to be mapped, but I rather
1251 * ignore the parameter because it would be extremely difficult to
1252 * integrate this with different types of module represenations.
1255 WINE_MODREF *MODULE_LoadLibraryExA( LPCSTR libname, HFILE hfile, DWORD flags )
1257 DWORD err = GetLastError();
1258 WINE_MODREF *pwm;
1259 int i;
1260 module_loadorder_t *plo;
1261 LPSTR filename, p;
1263 if ( !libname ) return NULL;
1265 filename = HeapAlloc ( GetProcessHeap(), 0, MAX_PATH + 1 );
1266 if ( !filename ) return NULL;
1268 /* build the modules filename */
1269 if (!SearchPathA( NULL, libname, ".dll", MAX_PATH, filename, NULL ))
1271 if ( ! GetSystemDirectoryA ( filename, MAX_PATH ) )
1272 goto error;
1274 /* if the library name contains a path and can not be found, return an error.
1275 exception: if the path is the system directory, proceed, so that modules,
1276 which are not PE-modules can be loaded
1278 if the library name does not contain a path and can not be found, assume the
1279 system directory is meant */
1281 if ( ! strncasecmp ( filename, libname, strlen ( filename ) ))
1282 strcpy ( filename, libname );
1283 else
1285 if ( strchr ( libname, '\\' ) || strchr ( libname, ':') || strchr ( libname, '/' ) )
1286 goto error;
1287 else
1289 strcat ( filename, "\\" );
1290 strcat ( filename, libname );
1294 /* if the filename doesn't have an extension append .DLL */
1295 if (!(p = strrchr( filename, '.')) || strchr( p, '/' ) || strchr( p, '\\'))
1296 strcat( filename, ".DLL" );
1299 EnterCriticalSection(&PROCESS_Current()->crit_section);
1301 /* Check for already loaded module */
1302 if((pwm = MODULE_FindModule(filename)))
1304 if(!(pwm->flags & WINE_MODREF_MARKER))
1305 pwm->refCount++;
1307 if ((pwm->flags & WINE_MODREF_DONT_RESOLVE_REFS) &&
1308 !(flags & DONT_RESOLVE_DLL_REFERENCES))
1310 extern DWORD fixup_imports(WINE_MODREF *wm); /*FIXME*/
1311 pwm->flags &= ~WINE_MODREF_DONT_RESOLVE_REFS;
1312 fixup_imports( pwm );
1314 TRACE("Already loaded module '%s' at 0x%08x, count=%d, \n", filename, pwm->module, pwm->refCount);
1315 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1316 HeapFree ( GetProcessHeap(), 0, filename );
1317 return pwm;
1320 plo = MODULE_GetLoadOrder(filename, TRUE);
1322 for(i = 0; i < MODULE_LOADORDER_NTYPES; i++)
1324 SetLastError( ERROR_FILE_NOT_FOUND );
1325 switch(plo->loadorder[i])
1327 case MODULE_LOADORDER_DLL:
1328 TRACE("Trying native dll '%s'\n", filename);
1329 pwm = PE_LoadLibraryExA(filename, flags);
1330 break;
1332 case MODULE_LOADORDER_ELFDLL:
1333 TRACE("Trying elfdll '%s'\n", filename);
1334 if (!(pwm = BUILTIN32_LoadLibraryExA(filename, flags)))
1335 pwm = ELFDLL_LoadLibraryExA(filename, flags);
1336 break;
1338 case MODULE_LOADORDER_SO:
1339 TRACE("Trying so-library '%s'\n", filename);
1340 if (!(pwm = BUILTIN32_LoadLibraryExA(filename, flags)))
1341 pwm = ELF_LoadLibraryExA(filename, flags);
1342 break;
1344 case MODULE_LOADORDER_BI:
1345 TRACE("Trying built-in '%s'\n", filename);
1346 pwm = BUILTIN32_LoadLibraryExA(filename, flags);
1347 break;
1349 default:
1350 ERR("Got invalid loadorder type %d (%s index %d)\n", plo->loadorder[i], plo->modulename, i);
1351 /* Fall through */
1353 case MODULE_LOADORDER_INVALID: /* We ignore this as it is an empty entry */
1354 pwm = NULL;
1355 break;
1358 if(pwm)
1360 /* Initialize DLL just loaded */
1361 TRACE("Loaded module '%s' at 0x%08x, \n", filename, pwm->module);
1363 /* Set the refCount here so that an attach failure will */
1364 /* decrement the dependencies through the MODULE_FreeLibrary call. */
1365 pwm->refCount++;
1367 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1368 SetLastError( err ); /* restore last error */
1369 HeapFree ( GetProcessHeap(), 0, filename );
1370 return pwm;
1373 if(GetLastError() != ERROR_FILE_NOT_FOUND)
1374 break;
1377 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1378 error:
1379 WARN("Failed to load module '%s'; error=0x%08lx, \n", filename, GetLastError());
1380 HeapFree ( GetProcessHeap(), 0, filename );
1381 return NULL;
1384 /***********************************************************************
1385 * LoadLibraryA (KERNEL32)
1387 HMODULE WINAPI LoadLibraryA(LPCSTR libname) {
1388 return LoadLibraryExA(libname,0,0);
1391 /***********************************************************************
1392 * LoadLibraryW (KERNEL32)
1394 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
1396 return LoadLibraryExW(libnameW,0,0);
1399 /***********************************************************************
1400 * LoadLibrary32_16 (KERNEL.452)
1402 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
1404 HMODULE hModule;
1406 SYSLEVEL_ReleaseWin16Lock();
1407 hModule = LoadLibraryA( libname );
1408 SYSLEVEL_RestoreWin16Lock();
1410 return hModule;
1413 /***********************************************************************
1414 * LoadLibraryExW (KERNEL32)
1416 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW,HANDLE hfile,DWORD flags)
1418 LPSTR libnameA = HEAP_strdupWtoA( GetProcessHeap(), 0, libnameW );
1419 HMODULE ret = LoadLibraryExA( libnameA , hfile, flags );
1421 HeapFree( GetProcessHeap(), 0, libnameA );
1422 return ret;
1425 /***********************************************************************
1426 * MODULE_FlushModrefs
1428 * NOTE: Assumes that the process critical section is held!
1430 * Remove all unused modrefs and call the internal unloading routines
1431 * for the library type.
1433 static void MODULE_FlushModrefs(void)
1435 WINE_MODREF *wm, *next;
1437 for(wm = PROCESS_Current()->modref_list; wm; wm = next)
1439 next = wm->next;
1441 if(wm->refCount)
1442 continue;
1444 /* Unlink this modref from the chain */
1445 if(wm->next)
1446 wm->next->prev = wm->prev;
1447 if(wm->prev)
1448 wm->prev->next = wm->next;
1449 if(wm == PROCESS_Current()->modref_list)
1450 PROCESS_Current()->modref_list = wm->next;
1452 TRACE(" unloading %s\n", wm->filename);
1453 /* VirtualFree( (LPVOID)wm->module, 0, MEM_RELEASE ); */ /* FIXME */
1454 /* if (wm->dlhandle) dlclose( wm->dlhandle ); */ /* FIXME */
1455 HeapFree( GetProcessHeap(), 0, wm->filename );
1456 HeapFree( GetProcessHeap(), 0, wm->short_filename );
1457 HeapFree( GetProcessHeap(), 0, wm );
1461 /***********************************************************************
1462 * FreeLibrary
1464 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
1466 BOOL retv = FALSE;
1467 WINE_MODREF *wm;
1469 EnterCriticalSection( &PROCESS_Current()->crit_section );
1470 PROCESS_Current()->free_lib_count++;
1472 wm = MODULE32_LookupHMODULE( hLibModule );
1473 if ( !wm || !hLibModule )
1474 SetLastError( ERROR_INVALID_HANDLE );
1475 else
1476 retv = MODULE_FreeLibrary( wm );
1478 PROCESS_Current()->free_lib_count--;
1479 LeaveCriticalSection( &PROCESS_Current()->crit_section );
1481 return retv;
1484 /***********************************************************************
1485 * MODULE_DecRefCount
1487 * NOTE: Assumes that the process critical section is held!
1489 static void MODULE_DecRefCount( WINE_MODREF *wm )
1491 int i;
1493 if ( wm->flags & WINE_MODREF_MARKER )
1494 return;
1496 if ( wm->refCount <= 0 )
1497 return;
1499 --wm->refCount;
1500 TRACE("(%s) refCount: %d\n", wm->modname, wm->refCount );
1502 if ( wm->refCount == 0 )
1504 wm->flags |= WINE_MODREF_MARKER;
1506 for ( i = 0; i < wm->nDeps; i++ )
1507 if ( wm->deps[i] )
1508 MODULE_DecRefCount( wm->deps[i] );
1510 wm->flags &= ~WINE_MODREF_MARKER;
1514 /***********************************************************************
1515 * MODULE_FreeLibrary
1517 * NOTE: Assumes that the process critical section is held!
1519 BOOL MODULE_FreeLibrary( WINE_MODREF *wm )
1521 TRACE("(%s) - START\n", wm->modname );
1523 /* Recursively decrement reference counts */
1524 MODULE_DecRefCount( wm );
1526 /* Call process detach notifications */
1527 if ( PROCESS_Current()->free_lib_count <= 1 )
1529 MODULE_DllProcessDetach( FALSE, NULL );
1530 SERVER_START_REQ
1532 struct unload_dll_request *req = server_alloc_req( sizeof(*req), 0 );
1533 req->base = (void *)wm->module;
1534 server_call_noerr( REQ_UNLOAD_DLL );
1536 SERVER_END_REQ;
1537 MODULE_FlushModrefs();
1540 TRACE("END\n");
1542 return TRUE;
1546 /***********************************************************************
1547 * FreeLibraryAndExitThread
1549 VOID WINAPI FreeLibraryAndExitThread(HINSTANCE hLibModule, DWORD dwExitCode)
1551 FreeLibrary(hLibModule);
1552 ExitThread(dwExitCode);
1555 /***********************************************************************
1556 * PrivateLoadLibrary (KERNEL32)
1558 * FIXME: rough guesswork, don't know what "Private" means
1560 HINSTANCE WINAPI PrivateLoadLibrary(LPCSTR libname)
1562 return (HINSTANCE)LoadLibrary16(libname);
1567 /***********************************************************************
1568 * PrivateFreeLibrary (KERNEL32)
1570 * FIXME: rough guesswork, don't know what "Private" means
1572 void WINAPI PrivateFreeLibrary(HINSTANCE handle)
1574 FreeLibrary16((HINSTANCE16)handle);
1578 /***********************************************************************
1579 * WIN32_GetProcAddress16 (KERNEL32.36)
1580 * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
1582 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
1584 WORD ordinal;
1585 FARPROC16 ret;
1587 if (!hModule) {
1588 WARN("hModule may not be 0!\n");
1589 return (FARPROC16)0;
1591 if (HIWORD(hModule))
1593 WARN("hModule is Win32 handle (%08x)\n", hModule );
1594 return (FARPROC16)0;
1596 hModule = GetExePtr( hModule );
1597 if (HIWORD(name)) {
1598 ordinal = NE_GetOrdinal( hModule, name );
1599 TRACE("%04x '%s'\n", hModule, name );
1600 } else {
1601 ordinal = LOWORD(name);
1602 TRACE("%04x %04x\n", hModule, ordinal );
1604 if (!ordinal) return (FARPROC16)0;
1605 ret = NE_GetEntryPoint( hModule, ordinal );
1606 TRACE("returning %08x\n",(UINT)ret);
1607 return ret;
1610 /***********************************************************************
1611 * GetProcAddress16 (KERNEL.50)
1613 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, SEGPTR name )
1615 WORD ordinal;
1616 FARPROC16 ret;
1618 if (!hModule) hModule = GetCurrentTask();
1619 hModule = GetExePtr( hModule );
1621 if (HIWORD(name) != 0)
1623 ordinal = NE_GetOrdinal( hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1624 TRACE("%04x '%s'\n", hModule, (LPSTR)PTR_SEG_TO_LIN(name) );
1626 else
1628 ordinal = LOWORD(name);
1629 TRACE("%04x %04x\n", hModule, ordinal );
1631 if (!ordinal) return (FARPROC16)0;
1633 ret = NE_GetEntryPoint( hModule, ordinal );
1635 TRACE("returning %08x\n", (UINT)ret );
1636 return ret;
1640 /***********************************************************************
1641 * GetProcAddress (KERNEL32.257)
1643 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1645 return MODULE_GetProcAddress( hModule, function, TRUE );
1648 /***********************************************************************
1649 * GetProcAddress32 (KERNEL.453)
1651 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
1653 return MODULE_GetProcAddress( hModule, function, FALSE );
1656 /***********************************************************************
1657 * MODULE_GetProcAddress (internal)
1659 FARPROC MODULE_GetProcAddress(
1660 HMODULE hModule, /* [in] current module handle */
1661 LPCSTR function, /* [in] function to be looked up */
1662 BOOL snoop )
1664 WINE_MODREF *wm;
1665 FARPROC retproc = 0;
1667 if (HIWORD(function))
1668 TRACE_(win32)("(%08lx,%s)\n",(DWORD)hModule,function);
1669 else
1670 TRACE_(win32)("(%08lx,%p)\n",(DWORD)hModule,function);
1672 EnterCriticalSection( &PROCESS_Current()->crit_section );
1673 if ((wm = MODULE32_LookupHMODULE( hModule )))
1675 retproc = wm->find_export( wm, function, snoop );
1676 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1678 LeaveCriticalSection( &PROCESS_Current()->crit_section );
1679 return retproc;
1683 /***************************************************************************
1684 * HasGPHandler (KERNEL.338)
1687 #include "pshpack1.h"
1688 typedef struct _GPHANDLERDEF
1690 WORD selector;
1691 WORD rangeStart;
1692 WORD rangeEnd;
1693 WORD handler;
1694 } GPHANDLERDEF;
1695 #include "poppack.h"
1697 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1699 HMODULE16 hModule;
1700 int gpOrdinal;
1701 SEGPTR gpPtr;
1702 GPHANDLERDEF *gpHandler;
1704 if ( (hModule = FarGetOwner16( SELECTOROF(address) )) != 0
1705 && (gpOrdinal = NE_GetOrdinal( hModule, "__GP" )) != 0
1706 && (gpPtr = (SEGPTR)NE_GetEntryPointEx( hModule, gpOrdinal, FALSE )) != 0
1707 && !IsBadReadPtr16( gpPtr, sizeof(GPHANDLERDEF) )
1708 && (gpHandler = PTR_SEG_TO_LIN( gpPtr )) != NULL )
1710 while (gpHandler->selector)
1712 if ( SELECTOROF(address) == gpHandler->selector
1713 && OFFSETOF(address) >= gpHandler->rangeStart
1714 && OFFSETOF(address) < gpHandler->rangeEnd )
1715 return PTR_SEG_OFF_TO_SEGPTR( gpHandler->selector,
1716 gpHandler->handler );
1717 gpHandler++;
1721 return 0;