4 * Copyright 1995 Alexandre Julliard
12 #include <sys/types.h>
14 #include "wine/winbase16.h"
19 #include "debugtools.h"
20 #include "wine/server.h"
22 DEFAULT_DEBUG_CHANNEL(module);
23 DECLARE_DEBUG_CHANNEL(win32);
24 DECLARE_DEBUG_CHANNEL(loaddll);
26 WINE_MODREF *MODULE_modref_list = NULL;
28 static WINE_MODREF *exe_modref;
29 static int free_lib_count; /* recursion depth of FreeLibrary calls */
30 static int process_detaching; /* set on process detach to avoid deadlocks with thread detach */
32 /***********************************************************************
35 * Wrapper to call WaitForInputIdle USER function
37 typedef DWORD (WINAPI *WaitForInputIdle_ptr)( HANDLE hProcess, DWORD dwTimeOut );
39 static DWORD wait_input_idle( HANDLE process, DWORD timeout )
41 HMODULE mod = GetModuleHandleA( "user32.dll" );
44 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
45 if (ptr) return ptr( process, timeout );
51 /*************************************************************************
52 * MODULE32_LookupHMODULE
53 * looks for the referenced HMODULE in the current process
54 * NOTE: Assumes that the process critical section is held!
56 static WINE_MODREF *MODULE32_LookupHMODULE( HMODULE hmod )
64 ERR("tried to lookup 0x%04x in win32 module handler!\n",hmod);
65 SetLastError( ERROR_INVALID_HANDLE );
68 for ( wm = MODULE_modref_list; wm; wm=wm->next )
69 if (wm->module == hmod)
71 SetLastError( ERROR_INVALID_HANDLE );
75 /*************************************************************************
78 * Allocate a WINE_MODREF structure and add it to the process list
79 * NOTE: Assumes that the process critical section is held!
81 WINE_MODREF *MODULE_AllocModRef( HMODULE hModule, LPCSTR filename )
85 DWORD long_len = strlen( filename );
86 DWORD short_len = GetShortPathNameA( filename, NULL, 0 );
88 if ((wm = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY,
89 sizeof(*wm) + long_len + short_len + 1 )))
94 wm->filename = wm->data;
95 memcpy( wm->filename, filename, long_len + 1 );
96 if ((wm->modname = strrchr( wm->filename, '\\' ))) wm->modname++;
97 else wm->modname = wm->filename;
99 wm->short_filename = wm->filename + long_len + 1;
100 GetShortPathNameA( wm->filename, wm->short_filename, short_len + 1 );
101 if ((wm->short_modname = strrchr( wm->short_filename, '\\' ))) wm->short_modname++;
102 else wm->short_modname = wm->short_filename;
104 wm->next = MODULE_modref_list;
105 if (wm->next) wm->next->prev = wm;
106 MODULE_modref_list = wm;
108 if (!(PE_HEADER(hModule)->FileHeader.Characteristics & IMAGE_FILE_DLL))
110 if (!exe_modref) exe_modref = wm;
111 else FIXME( "Trying to load second .EXE file: %s\n", filename );
117 /*************************************************************************
120 static BOOL MODULE_InitDLL( WINE_MODREF *wm, DWORD type, LPVOID lpReserved )
124 static LPCSTR typeName[] = { "PROCESS_DETACH", "PROCESS_ATTACH",
125 "THREAD_ATTACH", "THREAD_DETACH" };
128 /* Skip calls for modules loaded with special load flags */
130 if (wm->flags & WINE_MODREF_DONT_RESOLVE_REFS) return TRUE;
132 TRACE("(%s,%s,%p) - CALL\n", wm->modname, typeName[type], lpReserved );
134 /* Call the initialization routine */
135 retv = PE_InitDLL( wm->module, type, lpReserved );
137 /* The state of the module list may have changed due to the call
138 to PE_InitDLL. We cannot assume that this module has not been
140 TRACE("(%p,%s,%p) - RETURN %d\n", wm, typeName[type], lpReserved, retv );
145 /*************************************************************************
146 * MODULE_DllProcessAttach
148 * Send the process attach notification to all DLLs the given module
149 * depends on (recursively). This is somewhat complicated due to the fact that
151 * - we have to respect the module dependencies, i.e. modules implicitly
152 * referenced by another module have to be initialized before the module
153 * itself can be initialized
155 * - the initialization routine of a DLL can itself call LoadLibrary,
156 * thereby introducing a whole new set of dependencies (even involving
157 * the 'old' modules) at any time during the whole process
159 * (Note that this routine can be recursively entered not only directly
160 * from itself, but also via LoadLibrary from one of the called initialization
163 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
164 * the process *detach* notifications to be sent in the correct order.
165 * This must not only take into account module dependencies, but also
166 * 'hidden' dependencies created by modules calling LoadLibrary in their
167 * attach notification routine.
169 * The strategy is rather simple: we move a WINE_MODREF to the head of the
170 * list after the attach notification has returned. This implies that the
171 * detach notifications are called in the reverse of the sequence the attach
172 * notifications *returned*.
174 BOOL MODULE_DllProcessAttach( WINE_MODREF *wm, LPVOID lpReserved )
181 if (!wm) wm = exe_modref;
184 /* prevent infinite recursion in case of cyclical dependencies */
185 if ( ( wm->flags & WINE_MODREF_MARKER )
186 || ( wm->flags & WINE_MODREF_PROCESS_ATTACHED ) )
189 TRACE("(%s,%p) - START\n", wm->modname, lpReserved );
191 /* Tag current MODREF to prevent recursive loop */
192 wm->flags |= WINE_MODREF_MARKER;
194 /* Recursively attach all DLLs this one depends on */
195 for ( i = 0; retv && i < wm->nDeps; i++ )
197 retv = MODULE_DllProcessAttach( wm->deps[i], lpReserved );
199 /* Call DLL entry point */
202 retv = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
204 wm->flags |= WINE_MODREF_PROCESS_ATTACHED;
207 /* Re-insert MODREF at head of list */
208 if ( retv && wm->prev )
210 wm->prev->next = wm->next;
211 if ( wm->next ) wm->next->prev = wm->prev;
214 wm->next = MODULE_modref_list;
215 MODULE_modref_list = wm->next->prev = wm;
218 /* Remove recursion flag */
219 wm->flags &= ~WINE_MODREF_MARKER;
221 TRACE("(%s,%p) - END\n", wm->modname, lpReserved );
228 /*************************************************************************
229 * MODULE_DllProcessDetach
231 * Send DLL process detach notifications. See the comment about calling
232 * sequence at MODULE_DllProcessAttach. Unless the bForceDetach flag
233 * is set, only DLLs with zero refcount are notified.
235 void MODULE_DllProcessDetach( BOOL bForceDetach, LPVOID lpReserved )
240 if (bForceDetach) process_detaching = 1;
243 for ( wm = MODULE_modref_list; wm; wm = wm->next )
245 /* Check whether to detach this DLL */
246 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
248 if ( wm->refCount > 0 && !bForceDetach )
251 /* Call detach notification */
252 wm->flags &= ~WINE_MODREF_PROCESS_ATTACHED;
253 MODULE_InitDLL( wm, DLL_PROCESS_DETACH, lpReserved );
255 /* Restart at head of WINE_MODREF list, as entries might have
256 been added and/or removed while performing the call ... */
264 /*************************************************************************
265 * MODULE_DllThreadAttach
267 * Send DLL thread attach notifications. These are sent in the
268 * reverse sequence of process detach notification.
271 void MODULE_DllThreadAttach( LPVOID lpReserved )
275 /* don't do any attach calls if process is exiting */
276 if (process_detaching) return;
277 /* FIXME: there is still a race here */
281 for ( wm = MODULE_modref_list; wm; wm = wm->next )
285 for ( ; wm; wm = wm->prev )
287 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
289 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
292 MODULE_InitDLL( wm, DLL_THREAD_ATTACH, lpReserved );
298 /*************************************************************************
299 * MODULE_DllThreadDetach
301 * Send DLL thread detach notifications. These are sent in the
302 * same sequence as process detach notification.
305 void MODULE_DllThreadDetach( LPVOID lpReserved )
309 /* don't do any detach calls if process is exiting */
310 if (process_detaching) return;
311 /* FIXME: there is still a race here */
315 for ( wm = MODULE_modref_list; wm; wm = wm->next )
317 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
319 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
322 MODULE_InitDLL( wm, DLL_THREAD_DETACH, lpReserved );
328 /****************************************************************************
329 * DisableThreadLibraryCalls (KERNEL32.@)
331 * Don't call DllEntryPoint for DLL_THREAD_{ATTACH,DETACH} if set.
333 BOOL WINAPI DisableThreadLibraryCalls( HMODULE hModule )
340 wm = MODULE32_LookupHMODULE( hModule );
344 wm->flags |= WINE_MODREF_NO_DLL_CALLS;
352 /***********************************************************************
353 * MODULE_CreateDummyModule
355 * Create a dummy NE module for Win32 or Winelib.
357 HMODULE16 MODULE_CreateDummyModule( LPCSTR filename, HMODULE module32 )
361 SEGTABLEENTRY *pSegment;
364 const char* basename;
368 /* Extract base filename */
369 basename = strrchr(filename, '\\');
370 if (!basename) basename = filename;
372 len = strlen(basename);
373 if ((s = strchr(basename, '.'))) len = s - basename;
375 /* Allocate module */
376 of_size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName)
377 + strlen(filename) + 1;
378 size = sizeof(NE_MODULE) +
379 /* loaded file info */
380 ((of_size + 3) & ~3) +
381 /* segment table: DS,CS */
382 2 * sizeof(SEGTABLEENTRY) +
385 /* several empty tables */
388 hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
389 if (!hModule) return (HMODULE16)11; /* invalid exe */
391 FarSetOwner16( hModule, hModule );
392 pModule = (NE_MODULE *)GlobalLock16( hModule );
394 /* Set all used entries */
395 pModule->magic = IMAGE_OS2_SIGNATURE;
402 pModule->heap_size = 0;
403 pModule->stack_size = 0;
404 pModule->seg_count = 2;
405 pModule->modref_count = 0;
406 pModule->nrname_size = 0;
407 pModule->fileinfo = sizeof(NE_MODULE);
408 pModule->os_flags = NE_OSFLAGS_WINDOWS;
409 pModule->self = hModule;
410 pModule->module32 = module32;
412 /* Set version and flags */
415 pModule->expected_version =
416 ((PE_HEADER(module32)->OptionalHeader.MajorSubsystemVersion & 0xff) << 8 ) |
417 (PE_HEADER(module32)->OptionalHeader.MinorSubsystemVersion & 0xff);
418 pModule->flags |= NE_FFLAGS_WIN32;
419 if (PE_HEADER(module32)->FileHeader.Characteristics & IMAGE_FILE_DLL)
420 pModule->flags |= NE_FFLAGS_LIBMODULE | NE_FFLAGS_SINGLEDATA;
423 /* Set loaded file information */
424 ofs = (OFSTRUCT *)(pModule + 1);
425 memset( ofs, 0, of_size );
426 ofs->cBytes = of_size < 256 ? of_size : 255; /* FIXME */
427 strcpy( ofs->szPathName, filename );
429 pSegment = (SEGTABLEENTRY*)((char*)(pModule + 1) + ((of_size + 3) & ~3));
430 pModule->seg_table = (int)pSegment - (int)pModule;
433 pSegment->flags = NE_SEGFLAGS_DATA;
434 pSegment->minsize = 0x1000;
441 pStr = (char *)pSegment;
442 pModule->name_table = (int)pStr - (int)pModule;
445 lstrcpynA( pStr+1, basename, len+1 );
448 /* All tables zero terminated */
449 pModule->res_table = pModule->import_table = pModule->entry_table =
450 (int)pStr - (int)pModule;
452 NE_RegisterModule( pModule );
457 /**********************************************************************
460 * Find a (loaded) win32 module depending on path
463 * the module handle if found
466 WINE_MODREF *MODULE_FindModule(
467 LPCSTR path /* [in] pathname of module/library to be found */
470 char dllname[260], *p;
472 /* Append .DLL to name if no extension present */
473 strcpy( dllname, path );
474 if (!(p = strrchr( dllname, '.')) || strchr( p, '/' ) || strchr( p, '\\'))
475 strcat( dllname, ".DLL" );
477 for ( wm = MODULE_modref_list; wm; wm = wm->next )
479 if ( !FILE_strcasecmp( dllname, wm->modname ) )
481 if ( !FILE_strcasecmp( dllname, wm->filename ) )
483 if ( !FILE_strcasecmp( dllname, wm->short_modname ) )
485 if ( !FILE_strcasecmp( dllname, wm->short_filename ) )
493 /* Check whether a file is an OS/2 or a very old Windows executable
494 * by testing on import of KERNEL.
496 * FIXME: is reading the module imports the only way of discerning
497 * old Windows binaries from OS/2 ones ? At least it seems so...
499 static DWORD MODULE_Decide_OS2_OldWin(HANDLE hfile, IMAGE_DOS_HEADER *mz, IMAGE_OS2_HEADER *ne)
501 DWORD currpos = SetFilePointer( hfile, 0, NULL, SEEK_CUR);
502 DWORD type = SCS_OS216_BINARY;
503 LPWORD modtab = NULL;
504 LPSTR nametab = NULL;
508 /* read modref table */
509 if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_modtab, NULL, SEEK_SET ) == -1)
510 || (!(modtab = HeapAlloc( GetProcessHeap(), 0, ne->ne_cmod*sizeof(WORD))))
511 || (!(ReadFile(hfile, modtab, ne->ne_cmod*sizeof(WORD), &len, NULL)))
512 || (len != ne->ne_cmod*sizeof(WORD)) )
515 /* read imported names table */
516 if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_imptab, NULL, SEEK_SET ) == -1)
517 || (!(nametab = HeapAlloc( GetProcessHeap(), 0, ne->ne_enttab - ne->ne_imptab)))
518 || (!(ReadFile(hfile, nametab, ne->ne_enttab - ne->ne_imptab, &len, NULL)))
519 || (len != ne->ne_enttab - ne->ne_imptab) )
522 for (i=0; i < ne->ne_cmod; i++)
524 LPSTR module = &nametab[modtab[i]];
525 TRACE("modref: %.*s\n", module[0], &module[1]);
526 if (!(strncmp(&module[1], "KERNEL", module[0])))
527 { /* very old Windows file */
528 MESSAGE("This seems to be a very old (pre-3.0) Windows executable. Expect crashes, especially if this is a real-mode binary !\n");
529 type = SCS_WOW_BINARY;
535 ERR("Hmm, an error occurred. Is this binary file broken ?\n");
538 HeapFree( GetProcessHeap(), 0, modtab);
539 HeapFree( GetProcessHeap(), 0, nametab);
540 SetFilePointer( hfile, currpos, NULL, SEEK_SET); /* restore filepos */
544 /***********************************************************************
545 * MODULE_GetBinaryType
547 * The GetBinaryType function determines whether a file is executable
548 * or not and if it is it returns what type of executable it is.
549 * The type of executable is a property that determines in which
550 * subsystem an executable file runs under.
552 * Binary types returned:
553 * SCS_32BIT_BINARY: A Win32 based application
554 * SCS_DOS_BINARY: An MS-Dos based application
555 * SCS_WOW_BINARY: A Win16 based application
556 * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
557 * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
558 * SCS_OS216_BINARY: A 16bit OS/2 based application
560 * Returns TRUE if the file is an executable in which case
561 * the value pointed by lpBinaryType is set.
562 * Returns FALSE if the file is not an executable or if the function fails.
564 * To do so it opens the file and reads in the header information
565 * if the extended header information is not present it will
566 * assume that the file is a DOS executable.
567 * If the extended header information is present it will
568 * determine if the file is a 16 or 32 bit Windows executable
569 * by check the flags in the header.
571 * Note that .COM and .PIF files are only recognized by their
572 * file name extension; but Windows does it the same way ...
574 static BOOL MODULE_GetBinaryType( HANDLE hfile, LPCSTR filename, LPDWORD lpBinaryType )
576 IMAGE_DOS_HEADER mz_header;
580 /* Seek to the start of the file and read the DOS header information.
582 if ( SetFilePointer( hfile, 0, NULL, SEEK_SET ) != -1
583 && ReadFile( hfile, &mz_header, sizeof(mz_header), &len, NULL )
584 && len == sizeof(mz_header) )
586 /* Now that we have the header check the e_magic field
587 * to see if this is a dos image.
589 if ( mz_header.e_magic == IMAGE_DOS_SIGNATURE )
591 BOOL lfanewValid = FALSE;
592 /* We do have a DOS image so we will now try to seek into
593 * the file by the amount indicated by the field
594 * "Offset to extended header" and read in the
595 * "magic" field information at that location.
596 * This will tell us if there is more header information
599 /* But before we do we will make sure that header
600 * structure encompasses the "Offset to extended header"
603 if ( (mz_header.e_cparhdr<<4) >= sizeof(IMAGE_DOS_HEADER) )
604 if ( ( mz_header.e_crlc == 0 ) ||
605 ( mz_header.e_lfarlc >= sizeof(IMAGE_DOS_HEADER) ) )
606 if ( mz_header.e_lfanew >= sizeof(IMAGE_DOS_HEADER)
607 && SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET ) != -1
608 && ReadFile( hfile, magic, sizeof(magic), &len, NULL )
609 && len == sizeof(magic) )
614 /* If we cannot read this "extended header" we will
615 * assume that we have a simple DOS executable.
617 *lpBinaryType = SCS_DOS_BINARY;
622 /* Reading the magic field succeeded so
623 * we will try to determine what type it is.
625 if ( *(DWORD*)magic == IMAGE_NT_SIGNATURE )
627 /* This is an NT signature.
629 *lpBinaryType = SCS_32BIT_BINARY;
632 else if ( *(WORD*)magic == IMAGE_OS2_SIGNATURE )
634 /* The IMAGE_OS2_SIGNATURE indicates that the
635 * "extended header is a Windows executable (NE)
636 * header." This can mean either a 16-bit OS/2
637 * or a 16-bit Windows or even a DOS program
638 * (running under a DOS extender). To decide
639 * which, we'll have to read the NE header.
643 if ( SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET ) != -1
644 && ReadFile( hfile, &ne, sizeof(ne), &len, NULL )
645 && len == sizeof(ne) )
647 switch ( ne.ne_exetyp )
649 case 2: *lpBinaryType = SCS_WOW_BINARY; return TRUE;
650 case 5: *lpBinaryType = SCS_DOS_BINARY; return TRUE;
651 default: *lpBinaryType =
652 MODULE_Decide_OS2_OldWin(hfile, &mz_header, &ne);
656 /* Couldn't read header, so abort. */
661 /* Unknown extended header, but this file is nonetheless
664 *lpBinaryType = SCS_DOS_BINARY;
671 /* If we get here, we don't even have a correct MZ header.
672 * Try to check the file extension for known types ...
674 ptr = strrchr( filename, '.' );
675 if ( ptr && !strchr( ptr, '\\' ) && !strchr( ptr, '/' ) )
677 if ( !FILE_strcasecmp( ptr, ".COM" ) )
679 *lpBinaryType = SCS_DOS_BINARY;
683 if ( !FILE_strcasecmp( ptr, ".PIF" ) )
685 *lpBinaryType = SCS_PIF_BINARY;
693 /***********************************************************************
694 * GetBinaryTypeA [KERNEL32.@]
695 * GetBinaryType [KERNEL32.@]
697 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
702 TRACE_(win32)("%s\n", lpApplicationName );
706 if ( lpApplicationName == NULL || lpBinaryType == NULL )
709 /* Open the file indicated by lpApplicationName for reading.
711 hfile = CreateFileA( lpApplicationName, GENERIC_READ, FILE_SHARE_READ,
712 NULL, OPEN_EXISTING, 0, 0 );
713 if ( hfile == INVALID_HANDLE_VALUE )
718 ret = MODULE_GetBinaryType( hfile, lpApplicationName, lpBinaryType );
722 CloseHandle( hfile );
727 /***********************************************************************
728 * GetBinaryTypeW [KERNEL32.@]
730 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
735 TRACE_(win32)("%s\n", debugstr_w(lpApplicationName) );
739 if ( lpApplicationName == NULL || lpBinaryType == NULL )
742 /* Convert the wide string to a ascii string.
744 strNew = HEAP_strdupWtoA( GetProcessHeap(), 0, lpApplicationName );
746 if ( strNew != NULL )
748 ret = GetBinaryTypeA( strNew, lpBinaryType );
750 /* Free the allocated string.
752 HeapFree( GetProcessHeap(), 0, strNew );
759 /***********************************************************************
760 * WinExec (KERNEL.166)
761 * WinExec16 (KERNEL32.@)
763 HINSTANCE16 WINAPI WinExec16( LPCSTR lpCmdLine, UINT16 nCmdShow )
765 LPCSTR p, args = NULL;
766 LPCSTR name_beg, name_end;
770 char buffer[MAX_PATH];
772 if (*lpCmdLine == '"') /* has to be only one and only at beginning ! */
774 name_beg = lpCmdLine+1;
775 p = strchr ( lpCmdLine+1, '"' );
779 args = strchr ( p, ' ' );
781 else /* yes, even valid with trailing '"' missing */
782 name_end = lpCmdLine+strlen(lpCmdLine);
786 name_beg = lpCmdLine;
787 args = strchr( lpCmdLine, ' ' );
788 name_end = args ? args : lpCmdLine+strlen(lpCmdLine);
791 if ((name_beg == lpCmdLine) && (!args))
792 { /* just use the original cmdline string as file name */
793 name = (LPSTR)lpCmdLine;
797 if (!(name = HeapAlloc( GetProcessHeap(), 0, name_end - name_beg + 1 )))
798 return ERROR_NOT_ENOUGH_MEMORY;
799 memcpy( name, name_beg, name_end - name_beg );
800 name[name_end - name_beg] = '\0';
806 arglen = strlen(args);
807 cmdline = HeapAlloc( GetProcessHeap(), 0, 2 + arglen );
808 cmdline[0] = (BYTE)arglen;
809 strcpy( cmdline + 1, args );
813 cmdline = HeapAlloc( GetProcessHeap(), 0, 2 );
814 cmdline[0] = cmdline[1] = 0;
817 TRACE("name: '%s', cmdline: '%.*s'\n", name, cmdline[0], &cmdline[1]);
819 if (SearchPathA( NULL, name, ".exe", sizeof(buffer), buffer, NULL ))
824 showCmd[1] = nCmdShow;
826 params.hEnvironment = 0;
827 params.cmdLine = MapLS( cmdline );
828 params.showCmd = MapLS( showCmd );
831 ret = LoadModule16( buffer, ¶ms );
832 UnMapLS( params.cmdLine );
833 UnMapLS( params.showCmd );
835 else ret = GetLastError();
837 HeapFree( GetProcessHeap(), 0, cmdline );
838 if (name != lpCmdLine) HeapFree( GetProcessHeap(), 0, name );
840 if (ret == 21) /* 32-bit module */
843 ReleaseThunkLock( &count );
844 ret = LOWORD( WinExec( lpCmdLine, nCmdShow ) );
845 RestoreThunkLock( count );
850 /***********************************************************************
851 * WinExec (KERNEL32.@)
853 HINSTANCE WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
855 PROCESS_INFORMATION info;
856 STARTUPINFOA startup;
860 memset( &startup, 0, sizeof(startup) );
861 startup.cb = sizeof(startup);
862 startup.dwFlags = STARTF_USESHOWWINDOW;
863 startup.wShowWindow = nCmdShow;
865 /* cmdline needs to be writeable for CreateProcess */
866 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(lpCmdLine)+1 ))) return 0;
867 strcpy( cmdline, lpCmdLine );
869 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
870 0, NULL, NULL, &startup, &info ))
872 /* Give 30 seconds to the app to come up */
873 if (wait_input_idle( info.hProcess, 30000 ) == 0xFFFFFFFF)
874 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
875 hInstance = (HINSTANCE)33;
876 /* Close off the handles */
877 CloseHandle( info.hThread );
878 CloseHandle( info.hProcess );
880 else if ((hInstance = (HINSTANCE)GetLastError()) >= (HINSTANCE)32)
882 FIXME("Strange error set by CreateProcess: %d\n", hInstance );
883 hInstance = (HINSTANCE)11;
885 HeapFree( GetProcessHeap(), 0, cmdline );
889 /**********************************************************************
890 * LoadModule (KERNEL32.@)
892 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
894 LOADPARAMS *params = (LOADPARAMS *)paramBlock;
895 PROCESS_INFORMATION info;
896 STARTUPINFOA startup;
899 char filename[MAX_PATH];
902 if (!name) return (HINSTANCE)ERROR_FILE_NOT_FOUND;
904 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
905 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
906 return (HINSTANCE)GetLastError();
908 len = (BYTE)params->lpCmdLine[0];
909 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
910 return (HINSTANCE)ERROR_NOT_ENOUGH_MEMORY;
912 strcpy( cmdline, filename );
913 p = cmdline + strlen(cmdline);
915 memcpy( p, params->lpCmdLine + 1, len );
918 memset( &startup, 0, sizeof(startup) );
919 startup.cb = sizeof(startup);
920 if (params->lpCmdShow)
922 startup.dwFlags = STARTF_USESHOWWINDOW;
923 startup.wShowWindow = params->lpCmdShow[1];
926 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
927 params->lpEnvAddress, NULL, &startup, &info ))
929 /* Give 30 seconds to the app to come up */
930 if (wait_input_idle( info.hProcess, 30000 ) == 0xFFFFFFFF )
931 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
932 hInstance = (HINSTANCE)33;
933 /* Close off the handles */
934 CloseHandle( info.hThread );
935 CloseHandle( info.hProcess );
937 else if ((hInstance = (HINSTANCE)GetLastError()) >= (HINSTANCE)32)
939 FIXME("Strange error set by CreateProcess: %d\n", hInstance );
940 hInstance = (HINSTANCE)11;
943 HeapFree( GetProcessHeap(), 0, cmdline );
948 /*************************************************************************
951 * Helper for CreateProcess: retrieve the file name to load from the
952 * app name and command line. Store the file name in buffer, and
953 * return a possibly modified command line.
955 static LPSTR get_file_name( LPCSTR appname, LPSTR cmdline, LPSTR buffer, int buflen )
957 char *name, *pos, *ret = NULL;
960 /* if we have an app name, everything is easy */
964 /* use the unmodified app name as file name */
965 lstrcpynA( buffer, appname, buflen );
966 if (!(ret = cmdline))
968 /* no command-line, create one */
969 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(appname) + 3 )))
970 sprintf( ret, "\"%s\"", appname );
977 SetLastError( ERROR_INVALID_PARAMETER );
981 /* first check for a quoted file name */
983 if ((cmdline[0] == '"') && ((p = strchr( cmdline + 1, '"' ))))
985 int len = p - cmdline - 1;
986 /* extract the quoted portion as file name */
987 if (!(name = HeapAlloc( GetProcessHeap(), 0, len + 1 ))) return NULL;
988 memcpy( name, cmdline + 1, len );
991 if (SearchPathA( NULL, name, ".exe", buflen, buffer, NULL ) ||
992 SearchPathA( NULL, name, NULL, buflen, buffer, NULL ))
993 ret = cmdline; /* no change necessary */
997 /* now try the command-line word by word */
999 if (!(name = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 1 ))) return NULL;
1005 do *pos++ = *p++; while (*p && *p != ' ');
1007 TRACE("trying '%s'\n", name );
1008 if (SearchPathA( NULL, name, ".exe", buflen, buffer, NULL ) ||
1009 SearchPathA( NULL, name, NULL, buflen, buffer, NULL ))
1016 if (!ret || !strchr( name, ' ' )) goto done; /* no change necessary */
1018 /* now build a new command-line with quotes */
1020 if (!(ret = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 3 ))) goto done;
1021 sprintf( ret, "\"%s\"%s", name, p );
1024 HeapFree( GetProcessHeap(), 0, name );
1029 /**********************************************************************
1030 * CreateProcessA (KERNEL32.@)
1032 BOOL WINAPI CreateProcessA( LPCSTR lpApplicationName, LPSTR lpCommandLine,
1033 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1034 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1035 BOOL bInheritHandles, DWORD dwCreationFlags,
1036 LPVOID lpEnvironment, LPCSTR lpCurrentDirectory,
1037 LPSTARTUPINFOA lpStartupInfo,
1038 LPPROCESS_INFORMATION lpProcessInfo )
1043 char name[MAX_PATH];
1046 /* Process the AppName and/or CmdLine to get module name and path */
1048 TRACE("app %s cmdline %s\n", debugstr_a(lpApplicationName), debugstr_a(lpCommandLine) );
1050 if (!(tidy_cmdline = get_file_name( lpApplicationName, lpCommandLine, name, sizeof(name) )))
1053 /* Warn if unsupported features are used */
1055 if (dwCreationFlags & NORMAL_PRIORITY_CLASS)
1056 FIXME("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
1057 if (dwCreationFlags & IDLE_PRIORITY_CLASS)
1058 FIXME("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
1059 if (dwCreationFlags & HIGH_PRIORITY_CLASS)
1060 FIXME("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
1061 if (dwCreationFlags & REALTIME_PRIORITY_CLASS)
1062 FIXME("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
1063 if (dwCreationFlags & CREATE_NEW_PROCESS_GROUP)
1064 FIXME("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
1065 if (dwCreationFlags & CREATE_UNICODE_ENVIRONMENT)
1066 FIXME("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
1067 if (dwCreationFlags & CREATE_SEPARATE_WOW_VDM)
1068 FIXME("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
1069 if (dwCreationFlags & CREATE_SHARED_WOW_VDM)
1070 FIXME("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
1071 if (dwCreationFlags & CREATE_DEFAULT_ERROR_MODE)
1072 FIXME("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
1073 if (dwCreationFlags & CREATE_NO_WINDOW)
1074 FIXME("(%s,...): CREATE_NO_WINDOW ignored\n", name);
1075 if (dwCreationFlags & PROFILE_USER)
1076 FIXME("(%s,...): PROFILE_USER ignored\n", name);
1077 if (dwCreationFlags & PROFILE_KERNEL)
1078 FIXME("(%s,...): PROFILE_KERNEL ignored\n", name);
1079 if (dwCreationFlags & PROFILE_SERVER)
1080 FIXME("(%s,...): PROFILE_SERVER ignored\n", name);
1081 if (lpStartupInfo->lpDesktop)
1082 FIXME("(%s,...): lpStartupInfo->lpDesktop %s ignored\n",
1083 name, debugstr_a(lpStartupInfo->lpDesktop));
1084 if (lpStartupInfo->lpTitle)
1085 FIXME("(%s,...): lpStartupInfo->lpTitle %s ignored\n",
1086 name, lpStartupInfo->lpTitle);
1087 if (lpStartupInfo->dwFlags & STARTF_USECOUNTCHARS)
1088 FIXME("(%s,...): STARTF_USECOUNTCHARS (%ld,%ld) ignored\n",
1089 name, lpStartupInfo->dwXCountChars, lpStartupInfo->dwYCountChars);
1090 if (lpStartupInfo->dwFlags & STARTF_USEFILLATTRIBUTE)
1091 FIXME("(%s,...): STARTF_USEFILLATTRIBUTE %lx ignored\n",
1092 name, lpStartupInfo->dwFillAttribute);
1093 if (lpStartupInfo->dwFlags & STARTF_RUNFULLSCREEN)
1094 FIXME("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
1095 if (lpStartupInfo->dwFlags & STARTF_FORCEONFEEDBACK)
1096 FIXME("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
1097 if (lpStartupInfo->dwFlags & STARTF_FORCEOFFFEEDBACK)
1098 FIXME("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
1099 if (lpStartupInfo->dwFlags & STARTF_USEHOTKEY)
1100 FIXME("(%s,...): STARTF_USEHOTKEY ignored\n", name);
1102 /* Open file and determine executable type */
1104 hFile = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0 );
1105 if (hFile == INVALID_HANDLE_VALUE) goto done;
1107 if ( !MODULE_GetBinaryType( hFile, name, &type ) )
1109 CloseHandle( hFile );
1110 retv = PROCESS_Create( 0, name, tidy_cmdline, lpEnvironment,
1111 lpProcessAttributes, lpThreadAttributes,
1112 bInheritHandles, dwCreationFlags,
1113 lpStartupInfo, lpProcessInfo, lpCurrentDirectory );
1117 /* Create process */
1121 case SCS_32BIT_BINARY:
1122 case SCS_WOW_BINARY:
1123 case SCS_DOS_BINARY:
1124 retv = PROCESS_Create( hFile, name, tidy_cmdline, lpEnvironment,
1125 lpProcessAttributes, lpThreadAttributes,
1126 bInheritHandles, dwCreationFlags,
1127 lpStartupInfo, lpProcessInfo, lpCurrentDirectory);
1130 case SCS_PIF_BINARY:
1131 case SCS_POSIX_BINARY:
1132 case SCS_OS216_BINARY:
1133 FIXME("Unsupported executable type: %ld\n", type );
1137 SetLastError( ERROR_BAD_FORMAT );
1140 CloseHandle( hFile );
1143 if (tidy_cmdline != lpCommandLine) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1147 /**********************************************************************
1148 * CreateProcessW (KERNEL32.@)
1150 * lpReserved is not converted
1152 BOOL WINAPI CreateProcessW( LPCWSTR lpApplicationName, LPWSTR lpCommandLine,
1153 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1154 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1155 BOOL bInheritHandles, DWORD dwCreationFlags,
1156 LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory,
1157 LPSTARTUPINFOW lpStartupInfo,
1158 LPPROCESS_INFORMATION lpProcessInfo )
1160 STARTUPINFOA StartupInfoA;
1162 LPSTR lpApplicationNameA = HEAP_strdupWtoA (GetProcessHeap(),0,lpApplicationName);
1163 LPSTR lpCommandLineA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCommandLine);
1164 LPSTR lpCurrentDirectoryA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCurrentDirectory);
1166 memcpy (&StartupInfoA, lpStartupInfo, sizeof(STARTUPINFOA));
1167 StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpDesktop);
1168 StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpTitle);
1170 TRACE_(win32)("(%s,%s,...)\n", debugstr_w(lpApplicationName), debugstr_w(lpCommandLine));
1172 if (lpStartupInfo->lpReserved)
1173 FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n", debugstr_w(lpStartupInfo->lpReserved));
1175 ret = CreateProcessA( lpApplicationNameA, lpCommandLineA,
1176 lpProcessAttributes, lpThreadAttributes,
1177 bInheritHandles, dwCreationFlags,
1178 lpEnvironment, lpCurrentDirectoryA,
1179 &StartupInfoA, lpProcessInfo );
1181 HeapFree( GetProcessHeap(), 0, lpCurrentDirectoryA );
1182 HeapFree( GetProcessHeap(), 0, lpCommandLineA );
1183 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1184 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1189 /***********************************************************************
1190 * GetModuleHandleA (KERNEL32.@)
1191 * GetModuleHandle32 (KERNEL.488)
1193 HMODULE WINAPI GetModuleHandleA(LPCSTR module)
1197 if ( module == NULL )
1200 wm = MODULE_FindModule( module );
1202 return wm? wm->module : 0;
1205 /***********************************************************************
1206 * GetModuleHandleW (KERNEL32.@)
1208 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
1211 LPSTR modulea = HEAP_strdupWtoA( GetProcessHeap(), 0, module );
1212 hModule = GetModuleHandleA( modulea );
1213 HeapFree( GetProcessHeap(), 0, modulea );
1218 /***********************************************************************
1219 * GetModuleFileNameA (KERNEL32.@)
1220 * GetModuleFileName32 (KERNEL.487)
1222 * GetModuleFileNameA seems to *always* return the long path;
1223 * it's only GetModuleFileName16 that decides between short/long path
1224 * by checking if exe version >= 4.0.
1225 * (SDK docu doesn't mention this)
1227 DWORD WINAPI GetModuleFileNameA(
1228 HMODULE hModule, /* [in] module handle (32bit) */
1229 LPSTR lpFileName, /* [out] filenamebuffer */
1230 DWORD size ) /* [in] size of filenamebuffer */
1234 RtlAcquirePebLock();
1237 if ((wm = MODULE32_LookupHMODULE( hModule )))
1238 lstrcpynA( lpFileName, wm->filename, size );
1240 RtlReleasePebLock();
1241 TRACE("%s\n", lpFileName );
1242 return strlen(lpFileName);
1246 /***********************************************************************
1247 * GetModuleFileNameW (KERNEL32.@)
1249 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName,
1252 LPSTR fnA = (char*)HeapAlloc( GetProcessHeap(), 0, size );
1253 DWORD res = GetModuleFileNameA( hModule, fnA, size );
1254 if (size > 0 && !MultiByteToWideChar( CP_ACP, 0, fnA, -1, lpFileName, size ))
1255 lpFileName[size-1] = 0;
1256 HeapFree( GetProcessHeap(), 0, fnA );
1261 /***********************************************************************
1262 * LoadLibraryExA (KERNEL32.@)
1264 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
1270 SetLastError(ERROR_INVALID_PARAMETER);
1274 if (flags & LOAD_LIBRARY_AS_DATAFILE)
1279 /* This method allows searching for the 'native' libraries only */
1280 if (SearchPathA( NULL, libname, ".dll", sizeof(filename), filename, NULL ))
1282 /* FIXME: maybe we should use the hfile parameter instead */
1283 HANDLE hFile = CreateFileA( filename, GENERIC_READ, FILE_SHARE_READ,
1284 NULL, OPEN_EXISTING, 0, 0 );
1285 if (hFile != INVALID_HANDLE_VALUE)
1287 hmod = PE_LoadImage( hFile, filename, flags );
1288 CloseHandle( hFile );
1290 if (hmod) return (HMODULE)((ULONG_PTR)hmod + 1);
1292 flags |= DONT_RESOLVE_DLL_REFERENCES; /* Just in case */
1293 /* Fallback to normal behaviour */
1296 RtlAcquirePebLock();
1298 wm = MODULE_LoadLibraryExA( libname, hfile, flags );
1301 if ( !MODULE_DllProcessAttach( wm, NULL ) )
1303 WARN_(module)("Attach failed for module '%s', \n", libname);
1304 MODULE_FreeLibrary(wm);
1305 SetLastError(ERROR_DLL_INIT_FAILED);
1310 RtlReleasePebLock();
1311 return wm ? wm->module : 0;
1314 /***********************************************************************
1317 * helper for MODULE_LoadLibraryExA. Allocate space to hold the directory
1318 * portion of the provided name and put the name in it.
1321 static LPCSTR allocate_lib_dir(LPCSTR libname)
1328 if ((p = strrchr( pmax, '\\' ))) pmax = p + 1;
1329 if ((p = strrchr( pmax, '/' ))) pmax = p + 1; /* Naughty. MSDN says don't */
1330 if (pmax == libname && pmax[0] && pmax[1] == ':') pmax += 2;
1332 length = pmax - libname;
1334 result = HeapAlloc (GetProcessHeap(), 0, length+1);
1338 strncpy (result, libname, length);
1339 result [length] = '\0';
1345 /***********************************************************************
1346 * MODULE_LoadLibraryExA (internal)
1348 * Load a PE style module according to the load order.
1350 * The HFILE parameter is not used and marked reserved in the SDK. I can
1351 * only guess that it should force a file to be mapped, but I rather
1352 * ignore the parameter because it would be extremely difficult to
1353 * integrate this with different types of module represenations.
1355 * libdir is used to support LOAD_WITH_ALTERED_SEARCH_PATH during the recursion
1356 * on this function. When first called from LoadLibraryExA it will be
1357 * NULL but thereafter it may point to a buffer containing the path
1358 * portion of the library name. Note that the recursion all occurs
1359 * within a Critical section (see LoadLibraryExA) so the use of a
1360 * static is acceptable.
1361 * (We have to use a static variable at some point anyway, to pass the
1362 * information from BUILTIN32_dlopen through dlopen and the builtin's
1363 * init function into load_library).
1364 * allocated_libdir is TRUE in the stack frame that allocated libdir
1366 WINE_MODREF *MODULE_LoadLibraryExA( LPCSTR libname, HFILE hfile, DWORD flags )
1368 DWORD err = GetLastError();
1371 enum loadorder_type loadorder[LOADORDER_NTYPES];
1373 const char *filetype = "";
1375 BOOL allocated_libdir = FALSE;
1376 static LPCSTR libdir = NULL; /* See above */
1378 if ( !libname ) return NULL;
1380 filename = HeapAlloc ( GetProcessHeap(), 0, MAX_PATH + 1 );
1381 if ( !filename ) return NULL;
1383 RtlAcquirePebLock();
1385 if ((flags & LOAD_WITH_ALTERED_SEARCH_PATH) && FILE_contains_path(libname))
1387 if (!(libdir = allocate_lib_dir(libname))) goto error;
1388 allocated_libdir = TRUE;
1391 if (!libdir || allocated_libdir)
1392 found = SearchPathA(NULL, libname, ".dll", MAX_PATH, filename, NULL);
1394 found = DIR_SearchAlternatePath(libdir, libname, ".dll", MAX_PATH, filename, NULL);
1396 /* build the modules filename */
1399 if ( ! GetSystemDirectoryA ( filename, MAX_PATH ) )
1402 /* if the library name contains a path and can not be found, return an error.
1403 exception: if the path is the system directory, proceed, so that modules,
1404 which are not PE-modules can be loaded
1406 if the library name does not contain a path and can not be found, assume the
1407 system directory is meant */
1409 if ( ! FILE_strncasecmp ( filename, libname, strlen ( filename ) ))
1410 strcpy ( filename, libname );
1413 if (FILE_contains_path(libname)) goto error;
1414 strcat ( filename, "\\" );
1415 strcat ( filename, libname );
1418 /* if the filename doesn't have an extension append .DLL */
1419 if (!(p = strrchr( filename, '.')) || strchr( p, '/' ) || strchr( p, '\\'))
1420 strcat( filename, ".dll" );
1423 /* Check for already loaded module */
1424 if (!(pwm = MODULE_FindModule(filename)) && !FILE_contains_path(libname))
1426 LPSTR fn = HeapAlloc ( GetProcessHeap(), 0, MAX_PATH + 1 );
1429 /* since the default loading mechanism uses a more detailed algorithm
1430 * than SearchPath (like using PATH, which can even be modified between
1431 * two attempts of loading the same DLL), the look-up above (with
1432 * SearchPath) can have put the file in system directory, whereas it
1433 * has already been loaded but with a different path. So do a specific
1434 * look-up with filename (without any path)
1436 strcpy ( fn, libname );
1437 /* if the filename doesn't have an extension append .DLL */
1438 if (!strrchr( fn, '.')) strcat( fn, ".dll" );
1439 if ((pwm = MODULE_FindModule( fn )) != NULL)
1440 strcpy( filename, fn );
1441 HeapFree( GetProcessHeap(), 0, fn );
1446 if(!(pwm->flags & WINE_MODREF_MARKER))
1449 if ((pwm->flags & WINE_MODREF_DONT_RESOLVE_REFS) &&
1450 !(flags & DONT_RESOLVE_DLL_REFERENCES))
1452 pwm->flags &= ~WINE_MODREF_DONT_RESOLVE_REFS;
1453 PE_fixup_imports( pwm );
1455 TRACE("Already loaded module '%s' at 0x%08x, count=%d\n", filename, pwm->module, pwm->refCount);
1456 if (allocated_libdir)
1458 HeapFree ( GetProcessHeap(), 0, (LPSTR)libdir );
1461 RtlReleasePebLock();
1462 HeapFree ( GetProcessHeap(), 0, filename );
1466 MODULE_GetLoadOrder( loadorder, filename, TRUE);
1468 for(i = 0; i < LOADORDER_NTYPES; i++)
1470 if (loadorder[i] == LOADORDER_INVALID) break;
1471 SetLastError( ERROR_FILE_NOT_FOUND );
1473 switch(loadorder[i])
1476 TRACE("Trying native dll '%s'\n", filename);
1477 pwm = PE_LoadLibraryExA(filename, flags);
1478 filetype = "native";
1482 TRACE("Trying so-library '%s'\n", filename);
1483 pwm = ELF_LoadLibraryExA(filename, flags);
1488 TRACE("Trying built-in '%s'\n", filename);
1489 pwm = BUILTIN32_LoadLibraryExA(filename, flags);
1490 filetype = "builtin";
1500 /* Initialize DLL just loaded */
1501 TRACE("Loaded module '%s' at 0x%08x\n", filename, pwm->module);
1502 if (!TRACE_ON(module))
1503 TRACE_(loaddll)("Loaded module '%s' : %s\n", filename, filetype);
1504 /* Set the refCount here so that an attach failure will */
1505 /* decrement the dependencies through the MODULE_FreeLibrary call. */
1508 if (allocated_libdir)
1510 HeapFree ( GetProcessHeap(), 0, (LPSTR)libdir );
1513 RtlReleasePebLock();
1514 SetLastError( err ); /* restore last error */
1515 HeapFree ( GetProcessHeap(), 0, filename );
1519 if(GetLastError() != ERROR_FILE_NOT_FOUND)
1524 if (allocated_libdir)
1526 HeapFree ( GetProcessHeap(), 0, (LPSTR)libdir );
1529 RtlReleasePebLock();
1530 WARN("Failed to load module '%s'; error=0x%08lx\n", filename, GetLastError());
1531 HeapFree ( GetProcessHeap(), 0, filename );
1535 /***********************************************************************
1536 * LoadLibraryA (KERNEL32.@)
1538 HMODULE WINAPI LoadLibraryA(LPCSTR libname) {
1539 return LoadLibraryExA(libname,0,0);
1542 /***********************************************************************
1543 * LoadLibraryW (KERNEL32.@)
1545 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
1547 return LoadLibraryExW(libnameW,0,0);
1550 /***********************************************************************
1551 * LoadLibrary32 (KERNEL.452)
1552 * LoadSystemLibrary32 (KERNEL.482)
1554 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
1559 ReleaseThunkLock( &count );
1560 hModule = LoadLibraryA( libname );
1561 RestoreThunkLock( count );
1565 /***********************************************************************
1566 * LoadLibraryExW (KERNEL32.@)
1568 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW,HANDLE hfile,DWORD flags)
1570 LPSTR libnameA = HEAP_strdupWtoA( GetProcessHeap(), 0, libnameW );
1571 HMODULE ret = LoadLibraryExA( libnameA , hfile, flags );
1573 HeapFree( GetProcessHeap(), 0, libnameA );
1577 /***********************************************************************
1578 * MODULE_FlushModrefs
1580 * NOTE: Assumes that the process critical section is held!
1582 * Remove all unused modrefs and call the internal unloading routines
1583 * for the library type.
1585 static void MODULE_FlushModrefs(void)
1587 WINE_MODREF *wm, *next;
1589 for(wm = MODULE_modref_list; wm; wm = next)
1596 /* Unlink this modref from the chain */
1598 wm->next->prev = wm->prev;
1600 wm->prev->next = wm->next;
1601 if(wm == MODULE_modref_list)
1602 MODULE_modref_list = wm->next;
1604 TRACE(" unloading %s\n", wm->filename);
1605 if (wm->dlhandle) wine_dll_unload( wm->dlhandle );
1606 else UnmapViewOfFile( (LPVOID)wm->module );
1607 FreeLibrary16(wm->hDummyMod);
1608 HeapFree( GetProcessHeap(), 0, wm->deps );
1609 HeapFree( GetProcessHeap(), 0, wm );
1613 /***********************************************************************
1614 * FreeLibrary (KERNEL32.@)
1615 * FreeLibrary32 (KERNEL.486)
1617 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
1624 SetLastError( ERROR_INVALID_HANDLE );
1628 if ((ULONG_PTR)hLibModule & 1)
1630 /* this is a LOAD_LIBRARY_AS_DATAFILE module */
1631 char *ptr = (char *)hLibModule - 1;
1632 UnmapViewOfFile( ptr );
1636 RtlAcquirePebLock();
1639 if ((wm = MODULE32_LookupHMODULE( hLibModule ))) retv = MODULE_FreeLibrary( wm );
1642 RtlReleasePebLock();
1647 /***********************************************************************
1648 * MODULE_DecRefCount
1650 * NOTE: Assumes that the process critical section is held!
1652 static void MODULE_DecRefCount( WINE_MODREF *wm )
1656 if ( wm->flags & WINE_MODREF_MARKER )
1659 if ( wm->refCount <= 0 )
1663 TRACE("(%s) refCount: %d\n", wm->modname, wm->refCount );
1665 if ( wm->refCount == 0 )
1667 wm->flags |= WINE_MODREF_MARKER;
1669 for ( i = 0; i < wm->nDeps; i++ )
1671 MODULE_DecRefCount( wm->deps[i] );
1673 wm->flags &= ~WINE_MODREF_MARKER;
1677 /***********************************************************************
1678 * MODULE_FreeLibrary
1680 * NOTE: Assumes that the process critical section is held!
1682 BOOL MODULE_FreeLibrary( WINE_MODREF *wm )
1684 TRACE("(%s) - START\n", wm->modname );
1686 /* Recursively decrement reference counts */
1687 MODULE_DecRefCount( wm );
1689 /* Call process detach notifications */
1690 if ( free_lib_count <= 1 )
1692 MODULE_DllProcessDetach( FALSE, NULL );
1693 SERVER_START_REQ( unload_dll )
1695 req->base = (void *)wm->module;
1696 wine_server_call( req );
1699 MODULE_FlushModrefs();
1708 /***********************************************************************
1709 * FreeLibraryAndExitThread (KERNEL32.@)
1711 VOID WINAPI FreeLibraryAndExitThread(HINSTANCE hLibModule, DWORD dwExitCode)
1713 FreeLibrary(hLibModule);
1714 ExitThread(dwExitCode);
1717 /***********************************************************************
1718 * PrivateLoadLibrary (KERNEL32.@)
1720 * FIXME: rough guesswork, don't know what "Private" means
1722 HINSTANCE16 WINAPI PrivateLoadLibrary(LPCSTR libname)
1724 return LoadLibrary16(libname);
1729 /***********************************************************************
1730 * PrivateFreeLibrary (KERNEL32.@)
1732 * FIXME: rough guesswork, don't know what "Private" means
1734 void WINAPI PrivateFreeLibrary(HINSTANCE16 handle)
1736 FreeLibrary16(handle);
1740 /***********************************************************************
1741 * GetProcAddress16 (KERNEL32.37)
1742 * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
1744 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
1747 WARN("hModule may not be 0!\n");
1748 return (FARPROC16)0;
1750 if (HIWORD(hModule))
1752 WARN("hModule is Win32 handle (%08x)\n", hModule );
1753 return (FARPROC16)0;
1755 return GetProcAddress16( LOWORD(hModule), name );
1758 /***********************************************************************
1759 * GetProcAddress (KERNEL.50)
1761 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, LPCSTR name )
1766 if (!hModule) hModule = GetCurrentTask();
1767 hModule = GetExePtr( hModule );
1769 if (HIWORD(name) != 0)
1771 ordinal = NE_GetOrdinal( hModule, name );
1772 TRACE("%04x '%s'\n", hModule, name );
1776 ordinal = LOWORD(name);
1777 TRACE("%04x %04x\n", hModule, ordinal );
1779 if (!ordinal) return (FARPROC16)0;
1781 ret = NE_GetEntryPoint( hModule, ordinal );
1783 TRACE("returning %08x\n", (UINT)ret );
1788 /***********************************************************************
1789 * GetProcAddress (KERNEL32.@)
1791 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1793 return MODULE_GetProcAddress( hModule, function, TRUE );
1796 /***********************************************************************
1797 * GetProcAddress32 (KERNEL.453)
1799 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
1801 return MODULE_GetProcAddress( hModule, function, FALSE );
1804 /***********************************************************************
1805 * MODULE_GetProcAddress (internal)
1807 FARPROC MODULE_GetProcAddress(
1808 HMODULE hModule, /* [in] current module handle */
1809 LPCSTR function, /* [in] function to be looked up */
1813 FARPROC retproc = 0;
1815 if (HIWORD(function))
1816 TRACE_(win32)("(%08lx,%s)\n",(DWORD)hModule,function);
1818 TRACE_(win32)("(%08lx,%p)\n",(DWORD)hModule,function);
1820 RtlAcquirePebLock();
1821 if ((wm = MODULE32_LookupHMODULE( hModule )))
1823 retproc = wm->find_export( wm, function, snoop );
1824 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1826 RtlReleasePebLock();
1831 /***************************************************************************
1832 * HasGPHandler (KERNEL.338)
1835 #include "pshpack1.h"
1836 typedef struct _GPHANDLERDEF
1843 #include "poppack.h"
1845 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1850 GPHANDLERDEF *gpHandler;
1852 if ( (hModule = FarGetOwner16( SELECTOROF(address) )) != 0
1853 && (gpOrdinal = NE_GetOrdinal( hModule, "__GP" )) != 0
1854 && (gpPtr = (SEGPTR)NE_GetEntryPointEx( hModule, gpOrdinal, FALSE )) != 0
1855 && !IsBadReadPtr16( gpPtr, sizeof(GPHANDLERDEF) )
1856 && (gpHandler = MapSL( gpPtr )) != NULL )
1858 while (gpHandler->selector)
1860 if ( SELECTOROF(address) == gpHandler->selector
1861 && OFFSETOF(address) >= gpHandler->rangeStart
1862 && OFFSETOF(address) < gpHandler->rangeEnd )
1863 return MAKESEGPTR( gpHandler->selector, gpHandler->handler );