Added some stubs for quartz dll.
[wine/multimedia.git] / loader / module.c
blob692ea11352b5fb17d8f200e2145734e4bac22c5c
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 "file.h"
18 #include "module.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 /***********************************************************************
33 * wait_input_idle
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" );
42 if (mod)
44 WaitForInputIdle_ptr ptr = (WaitForInputIdle_ptr)GetProcAddress( mod, "WaitForInputIdle" );
45 if (ptr) return ptr( process, timeout );
47 return 0;
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 )
58 WINE_MODREF *wm;
60 if (!hmod)
61 return exe_modref;
63 if (!HIWORD(hmod)) {
64 ERR("tried to lookup 0x%04x in win32 module handler!\n",hmod);
65 SetLastError( ERROR_INVALID_HANDLE );
66 return NULL;
68 for ( wm = MODULE_modref_list; wm; wm=wm->next )
69 if (wm->module == hmod)
70 return wm;
71 SetLastError( ERROR_INVALID_HANDLE );
72 return NULL;
75 /*************************************************************************
76 * MODULE_AllocModRef
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 )
83 WINE_MODREF *wm;
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 )))
91 wm->module = hModule;
92 wm->tlsindex = -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 );
114 return wm;
117 /*************************************************************************
118 * MODULE_InitDLL
120 static BOOL MODULE_InitDLL( WINE_MODREF *wm, DWORD type, LPVOID lpReserved )
122 BOOL retv = TRUE;
124 static LPCSTR typeName[] = { "PROCESS_DETACH", "PROCESS_ATTACH",
125 "THREAD_ATTACH", "THREAD_DETACH" };
126 assert( wm );
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
139 deleted. */
140 TRACE("(%p,%s,%p) - RETURN %d\n", wm, typeName[type], lpReserved, retv );
142 return 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
161 * routines.)
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 )
176 BOOL retv = TRUE;
177 int i;
179 RtlAcquirePebLock();
181 if (!wm) wm = exe_modref;
182 assert( wm );
184 /* prevent infinite recursion in case of cyclical dependencies */
185 if ( ( wm->flags & WINE_MODREF_MARKER )
186 || ( wm->flags & WINE_MODREF_PROCESS_ATTACHED ) )
187 goto done;
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++ )
196 if ( wm->deps[i] )
197 retv = MODULE_DllProcessAttach( wm->deps[i], lpReserved );
199 /* Call DLL entry point */
200 if ( retv )
202 retv = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
203 if ( retv )
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;
213 wm->prev = NULL;
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 );
223 done:
224 RtlReleasePebLock();
225 return retv;
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 )
237 WINE_MODREF *wm;
239 RtlAcquirePebLock();
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) )
247 continue;
248 if ( wm->refCount > 0 && !bForceDetach )
249 continue;
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 ... */
257 break;
259 } while ( wm );
261 RtlReleasePebLock();
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 )
273 WINE_MODREF *wm;
275 /* don't do any attach calls if process is exiting */
276 if (process_detaching) return;
277 /* FIXME: there is still a race here */
279 RtlAcquirePebLock();
281 for ( wm = MODULE_modref_list; wm; wm = wm->next )
282 if ( !wm->next )
283 break;
285 for ( ; wm; wm = wm->prev )
287 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
288 continue;
289 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
290 continue;
292 MODULE_InitDLL( wm, DLL_THREAD_ATTACH, lpReserved );
295 RtlReleasePebLock();
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 )
307 WINE_MODREF *wm;
309 /* don't do any detach calls if process is exiting */
310 if (process_detaching) return;
311 /* FIXME: there is still a race here */
313 RtlAcquirePebLock();
315 for ( wm = MODULE_modref_list; wm; wm = wm->next )
317 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
318 continue;
319 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
320 continue;
322 MODULE_InitDLL( wm, DLL_THREAD_DETACH, lpReserved );
325 RtlReleasePebLock();
328 /****************************************************************************
329 * DisableThreadLibraryCalls (KERNEL32.@)
331 * Don't call DllEntryPoint for DLL_THREAD_{ATTACH,DETACH} if set.
333 BOOL WINAPI DisableThreadLibraryCalls( HMODULE hModule )
335 WINE_MODREF *wm;
336 BOOL retval = TRUE;
338 RtlAcquirePebLock();
340 wm = MODULE32_LookupHMODULE( hModule );
341 if ( !wm )
342 retval = FALSE;
343 else
344 wm->flags |= WINE_MODREF_NO_DLL_CALLS;
346 RtlReleasePebLock();
348 return retval;
352 /***********************************************************************
353 * MODULE_CreateDummyModule
355 * Create a dummy NE module for Win32 or Winelib.
357 HMODULE16 MODULE_CreateDummyModule( LPCSTR filename, HMODULE module32 )
359 HMODULE16 hModule;
360 NE_MODULE *pModule;
361 SEGTABLEENTRY *pSegment;
362 char *pStr,*s;
363 unsigned int len;
364 const char* basename;
365 OFSTRUCT *ofs;
366 int of_size, size;
368 /* Extract base filename */
369 basename = strrchr(filename, '\\');
370 if (!basename) basename = filename;
371 else basename++;
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) +
383 /* name table */
384 len + 2 +
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;
396 pModule->count = 1;
397 pModule->next = 0;
398 pModule->flags = 0;
399 pModule->dgroup = 0;
400 pModule->ss = 1;
401 pModule->cs = 2;
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 */
413 if (module32)
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;
431 /* Data segment */
432 pSegment->size = 0;
433 pSegment->flags = NE_SEGFLAGS_DATA;
434 pSegment->minsize = 0x1000;
435 pSegment++;
436 /* Code segment */
437 pSegment->flags = 0;
438 pSegment++;
440 /* Module name */
441 pStr = (char *)pSegment;
442 pModule->name_table = (int)pStr - (int)pModule;
443 assert(len<256);
444 *pStr = len;
445 lstrcpynA( pStr+1, basename, len+1 );
446 pStr += len+2;
448 /* All tables zero terminated */
449 pModule->res_table = pModule->import_table = pModule->entry_table =
450 (int)pStr - (int)pModule;
452 NE_RegisterModule( pModule );
453 return hModule;
457 /**********************************************************************
458 * MODULE_FindModule
460 * Find a (loaded) win32 module depending on path
462 * RETURNS
463 * the module handle if found
464 * 0 if not
466 WINE_MODREF *MODULE_FindModule(
467 LPCSTR path /* [in] pathname of module/library to be found */
469 WINE_MODREF *wm;
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 ) )
480 break;
481 if ( !FILE_strcasecmp( dllname, wm->filename ) )
482 break;
483 if ( !FILE_strcasecmp( dllname, wm->short_modname ) )
484 break;
485 if ( !FILE_strcasecmp( dllname, wm->short_filename ) )
486 break;
489 return wm;
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;
505 DWORD len;
506 int i;
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)) )
513 goto broken;
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) )
520 goto broken;
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;
530 goto good;
534 broken:
535 ERR("Hmm, an error occurred. Is this binary file broken ?\n");
537 good:
538 HeapFree( GetProcessHeap(), 0, modtab);
539 HeapFree( GetProcessHeap(), 0, nametab);
540 SetFilePointer( hfile, currpos, NULL, SEEK_SET); /* restore filepos */
541 return type;
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;
577 char magic[4], *ptr;
578 DWORD len;
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
597 * to read or not.
599 /* But before we do we will make sure that header
600 * structure encompasses the "Offset to extended header"
601 * field.
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) )
610 lfanewValid = TRUE;
612 if ( !lfanewValid )
614 /* If we cannot read this "extended header" we will
615 * assume that we have a simple DOS executable.
617 *lpBinaryType = SCS_DOS_BINARY;
618 return TRUE;
620 else
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;
630 return TRUE;
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.
642 IMAGE_OS2_HEADER ne;
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);
653 return TRUE;
656 /* Couldn't read header, so abort. */
657 return FALSE;
659 else
661 /* Unknown extended header, but this file is nonetheless
662 DOS-executable.
664 *lpBinaryType = SCS_DOS_BINARY;
665 return TRUE;
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;
680 return TRUE;
683 if ( !FILE_strcasecmp( ptr, ".PIF" ) )
685 *lpBinaryType = SCS_PIF_BINARY;
686 return TRUE;
690 return FALSE;
693 /***********************************************************************
694 * GetBinaryTypeA [KERNEL32.@]
695 * GetBinaryType [KERNEL32.@]
697 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
699 BOOL ret = FALSE;
700 HANDLE hfile;
702 TRACE_(win32)("%s\n", lpApplicationName );
704 /* Sanity check.
706 if ( lpApplicationName == NULL || lpBinaryType == NULL )
707 return FALSE;
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 )
714 return FALSE;
716 /* Check binary type
718 ret = MODULE_GetBinaryType( hfile, lpApplicationName, lpBinaryType );
720 /* Close the file.
722 CloseHandle( hfile );
724 return ret;
727 /***********************************************************************
728 * GetBinaryTypeW [KERNEL32.@]
730 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
732 BOOL ret = FALSE;
733 LPSTR strNew = NULL;
735 TRACE_(win32)("%s\n", debugstr_w(lpApplicationName) );
737 /* Sanity check.
739 if ( lpApplicationName == NULL || lpBinaryType == NULL )
740 return FALSE;
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 );
755 return ret;
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;
767 LPSTR name, cmdline;
768 int arglen;
769 HINSTANCE16 ret;
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, '"' );
776 if (p)
778 name_end = p;
779 args = strchr ( p, ' ' );
781 else /* yes, even valid with trailing '"' missing */
782 name_end = lpCmdLine+strlen(lpCmdLine);
784 else
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;
795 else
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';
803 if (args)
805 args++;
806 arglen = strlen(args);
807 cmdline = SEGPTR_ALLOC( 2 + arglen );
808 cmdline[0] = (BYTE)arglen;
809 strcpy( cmdline + 1, args );
811 else
813 cmdline = SEGPTR_ALLOC( 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 ))
821 LOADPARAMS16 params;
822 WORD *showCmd = SEGPTR_ALLOC( 2*sizeof(WORD) );
823 showCmd[0] = 2;
824 showCmd[1] = nCmdShow;
826 params.hEnvironment = 0;
827 params.cmdLine = SEGPTR_GET(cmdline);
828 params.showCmd = SEGPTR_GET(showCmd);
829 params.reserved = 0;
831 ret = LoadModule16( buffer, &params );
833 SEGPTR_FREE( showCmd );
834 SEGPTR_FREE( cmdline );
836 else ret = GetLastError();
838 if (name != lpCmdLine) HeapFree( GetProcessHeap(), 0, name );
840 if (ret == 21) /* 32-bit module */
842 DWORD count;
843 ReleaseThunkLock( &count );
844 ret = LOWORD( WinExec( lpCmdLine, nCmdShow ) );
845 RestoreThunkLock( count );
847 return ret;
850 /***********************************************************************
851 * WinExec (KERNEL32.@)
853 HINSTANCE WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
855 PROCESS_INFORMATION info;
856 STARTUPINFOA startup;
857 HINSTANCE hInstance;
858 char *cmdline;
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 );
886 return hInstance;
889 /**********************************************************************
890 * LoadModule (KERNEL32.@)
892 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
894 LOADPARAMS *params = (LOADPARAMS *)paramBlock;
895 PROCESS_INFORMATION info;
896 STARTUPINFOA startup;
897 HINSTANCE hInstance;
898 LPSTR cmdline, p;
899 char filename[MAX_PATH];
900 BYTE len;
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);
914 *p++ = ' ';
915 memcpy( p, params->lpCmdLine + 1, len );
916 p[len] = 0;
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 );
944 return hInstance;
948 /*************************************************************************
949 * get_file_name
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;
958 const char *p;
960 /* if we have an app name, everything is easy */
962 if (appname)
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 );
972 return ret;
975 if (!cmdline)
977 SetLastError( ERROR_INVALID_PARAMETER );
978 return NULL;
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 );
989 name[len] = 0;
991 if (SearchPathA( NULL, name, ".exe", buflen, buffer, NULL ) ||
992 SearchPathA( NULL, name, NULL, buflen, buffer, NULL ))
993 ret = cmdline; /* no change necessary */
994 goto done;
997 /* now try the command-line word by word */
999 if (!(name = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 1 ))) return NULL;
1000 pos = name;
1001 p = cmdline;
1003 while (*p)
1005 do *pos++ = *p++; while (*p && *p != ' ');
1006 *pos = 0;
1007 TRACE("trying '%s'\n", name );
1008 if (SearchPathA( NULL, name, ".exe", buflen, buffer, NULL ) ||
1009 SearchPathA( NULL, name, NULL, buflen, buffer, NULL ))
1011 ret = cmdline;
1012 break;
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 );
1023 done:
1024 HeapFree( GetProcessHeap(), 0, name );
1025 return ret;
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 )
1040 BOOL retv = FALSE;
1041 HANDLE hFile;
1042 DWORD type;
1043 char name[MAX_PATH];
1044 LPSTR tidy_cmdline;
1046 /* Process the AppName and/or CmdLine to get module name and path */
1048 TRACE("app '%s' cmdline '%s'\n", lpApplicationName, lpCommandLine );
1050 if (!(tidy_cmdline = get_file_name( lpApplicationName, lpCommandLine, name, sizeof(name) )))
1051 return FALSE;
1053 /* Warn if unsupported features are used */
1055 if (dwCreationFlags & DETACHED_PROCESS)
1056 FIXME("(%s,...): DETACHED_PROCESS ignored\n", name);
1057 if (dwCreationFlags & CREATE_NEW_CONSOLE)
1058 FIXME("(%s,...): CREATE_NEW_CONSOLE ignored\n", name);
1059 if (dwCreationFlags & NORMAL_PRIORITY_CLASS)
1060 FIXME("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
1061 if (dwCreationFlags & IDLE_PRIORITY_CLASS)
1062 FIXME("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
1063 if (dwCreationFlags & HIGH_PRIORITY_CLASS)
1064 FIXME("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
1065 if (dwCreationFlags & REALTIME_PRIORITY_CLASS)
1066 FIXME("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
1067 if (dwCreationFlags & CREATE_NEW_PROCESS_GROUP)
1068 FIXME("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
1069 if (dwCreationFlags & CREATE_UNICODE_ENVIRONMENT)
1070 FIXME("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
1071 if (dwCreationFlags & CREATE_SEPARATE_WOW_VDM)
1072 FIXME("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
1073 if (dwCreationFlags & CREATE_SHARED_WOW_VDM)
1074 FIXME("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
1075 if (dwCreationFlags & CREATE_DEFAULT_ERROR_MODE)
1076 FIXME("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
1077 if (dwCreationFlags & CREATE_NO_WINDOW)
1078 FIXME("(%s,...): CREATE_NO_WINDOW ignored\n", name);
1079 if (dwCreationFlags & PROFILE_USER)
1080 FIXME("(%s,...): PROFILE_USER ignored\n", name);
1081 if (dwCreationFlags & PROFILE_KERNEL)
1082 FIXME("(%s,...): PROFILE_KERNEL ignored\n", name);
1083 if (dwCreationFlags & PROFILE_SERVER)
1084 FIXME("(%s,...): PROFILE_SERVER ignored\n", name);
1085 if (lpStartupInfo->lpDesktop)
1086 FIXME("(%s,...): lpStartupInfo->lpDesktop %s ignored\n",
1087 name, lpStartupInfo->lpDesktop);
1088 if (lpStartupInfo->lpTitle)
1089 FIXME("(%s,...): lpStartupInfo->lpTitle %s ignored\n",
1090 name, lpStartupInfo->lpTitle);
1091 if (lpStartupInfo->dwFlags & STARTF_USECOUNTCHARS)
1092 FIXME("(%s,...): STARTF_USECOUNTCHARS (%ld,%ld) ignored\n",
1093 name, lpStartupInfo->dwXCountChars, lpStartupInfo->dwYCountChars);
1094 if (lpStartupInfo->dwFlags & STARTF_USEFILLATTRIBUTE)
1095 FIXME("(%s,...): STARTF_USEFILLATTRIBUTE %lx ignored\n",
1096 name, lpStartupInfo->dwFillAttribute);
1097 if (lpStartupInfo->dwFlags & STARTF_RUNFULLSCREEN)
1098 FIXME("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
1099 if (lpStartupInfo->dwFlags & STARTF_FORCEONFEEDBACK)
1100 FIXME("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
1101 if (lpStartupInfo->dwFlags & STARTF_FORCEOFFFEEDBACK)
1102 FIXME("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
1103 if (lpStartupInfo->dwFlags & STARTF_USEHOTKEY)
1104 FIXME("(%s,...): STARTF_USEHOTKEY ignored\n", name);
1106 /* Open file and determine executable type */
1108 hFile = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0 );
1109 if (hFile == INVALID_HANDLE_VALUE) goto done;
1111 if ( !MODULE_GetBinaryType( hFile, name, &type ) )
1113 CloseHandle( hFile );
1114 retv = PROCESS_Create( 0, name, tidy_cmdline, lpEnvironment,
1115 lpProcessAttributes, lpThreadAttributes,
1116 bInheritHandles, dwCreationFlags,
1117 lpStartupInfo, lpProcessInfo, lpCurrentDirectory );
1118 goto done;
1121 /* Create process */
1123 switch ( type )
1125 case SCS_32BIT_BINARY:
1126 case SCS_WOW_BINARY:
1127 case SCS_DOS_BINARY:
1128 retv = PROCESS_Create( hFile, name, tidy_cmdline, lpEnvironment,
1129 lpProcessAttributes, lpThreadAttributes,
1130 bInheritHandles, dwCreationFlags,
1131 lpStartupInfo, lpProcessInfo, lpCurrentDirectory);
1132 break;
1134 case SCS_PIF_BINARY:
1135 case SCS_POSIX_BINARY:
1136 case SCS_OS216_BINARY:
1137 FIXME("Unsupported executable type: %ld\n", type );
1138 /* fall through */
1140 default:
1141 SetLastError( ERROR_BAD_FORMAT );
1142 break;
1144 CloseHandle( hFile );
1146 done:
1147 if (tidy_cmdline != lpCommandLine) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1148 return retv;
1151 /**********************************************************************
1152 * CreateProcessW (KERNEL32.@)
1153 * NOTES
1154 * lpReserved is not converted
1156 BOOL WINAPI CreateProcessW( LPCWSTR lpApplicationName, LPWSTR lpCommandLine,
1157 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1158 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1159 BOOL bInheritHandles, DWORD dwCreationFlags,
1160 LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory,
1161 LPSTARTUPINFOW lpStartupInfo,
1162 LPPROCESS_INFORMATION lpProcessInfo )
1163 { BOOL ret;
1164 STARTUPINFOA StartupInfoA;
1166 LPSTR lpApplicationNameA = HEAP_strdupWtoA (GetProcessHeap(),0,lpApplicationName);
1167 LPSTR lpCommandLineA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCommandLine);
1168 LPSTR lpCurrentDirectoryA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCurrentDirectory);
1170 memcpy (&StartupInfoA, lpStartupInfo, sizeof(STARTUPINFOA));
1171 StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpDesktop);
1172 StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpTitle);
1174 TRACE_(win32)("(%s,%s,...)\n", debugstr_w(lpApplicationName), debugstr_w(lpCommandLine));
1176 if (lpStartupInfo->lpReserved)
1177 FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n", debugstr_w(lpStartupInfo->lpReserved));
1179 ret = CreateProcessA( lpApplicationNameA, lpCommandLineA,
1180 lpProcessAttributes, lpThreadAttributes,
1181 bInheritHandles, dwCreationFlags,
1182 lpEnvironment, lpCurrentDirectoryA,
1183 &StartupInfoA, lpProcessInfo );
1185 HeapFree( GetProcessHeap(), 0, lpCurrentDirectoryA );
1186 HeapFree( GetProcessHeap(), 0, lpCommandLineA );
1187 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1188 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1190 return ret;
1193 /***********************************************************************
1194 * GetModuleHandleA (KERNEL32.@)
1195 * GetModuleHandle32 (KERNEL.488)
1197 HMODULE WINAPI GetModuleHandleA(LPCSTR module)
1199 WINE_MODREF *wm;
1201 if ( module == NULL )
1202 wm = exe_modref;
1203 else
1204 wm = MODULE_FindModule( module );
1206 return wm? wm->module : 0;
1209 /***********************************************************************
1210 * GetModuleHandleW (KERNEL32.@)
1212 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
1214 HMODULE hModule;
1215 LPSTR modulea = HEAP_strdupWtoA( GetProcessHeap(), 0, module );
1216 hModule = GetModuleHandleA( modulea );
1217 HeapFree( GetProcessHeap(), 0, modulea );
1218 return hModule;
1222 /***********************************************************************
1223 * GetModuleFileNameA (KERNEL32.@)
1224 * GetModuleFileName32 (KERNEL.487)
1226 * GetModuleFileNameA seems to *always* return the long path;
1227 * it's only GetModuleFileName16 that decides between short/long path
1228 * by checking if exe version >= 4.0.
1229 * (SDK docu doesn't mention this)
1231 DWORD WINAPI GetModuleFileNameA(
1232 HMODULE hModule, /* [in] module handle (32bit) */
1233 LPSTR lpFileName, /* [out] filenamebuffer */
1234 DWORD size ) /* [in] size of filenamebuffer */
1236 WINE_MODREF *wm;
1238 RtlAcquirePebLock();
1240 lpFileName[0] = 0;
1241 if ((wm = MODULE32_LookupHMODULE( hModule )))
1242 lstrcpynA( lpFileName, wm->filename, size );
1244 RtlReleasePebLock();
1245 TRACE("%s\n", lpFileName );
1246 return strlen(lpFileName);
1250 /***********************************************************************
1251 * GetModuleFileNameW (KERNEL32.@)
1253 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName,
1254 DWORD size )
1256 LPSTR fnA = (char*)HeapAlloc( GetProcessHeap(), 0, size );
1257 DWORD res = GetModuleFileNameA( hModule, fnA, size );
1258 if (size > 0 && !MultiByteToWideChar( CP_ACP, 0, fnA, -1, lpFileName, size ))
1259 lpFileName[size-1] = 0;
1260 HeapFree( GetProcessHeap(), 0, fnA );
1261 return res;
1265 /***********************************************************************
1266 * LoadLibraryExA (KERNEL32.@)
1268 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
1270 WINE_MODREF *wm;
1272 if(!libname)
1274 SetLastError(ERROR_INVALID_PARAMETER);
1275 return 0;
1278 if (flags & LOAD_LIBRARY_AS_DATAFILE)
1280 char filename[256];
1281 HMODULE hmod = 0;
1283 /* This method allows searching for the 'native' libraries only */
1284 if (SearchPathA( NULL, libname, ".dll", sizeof(filename), filename, NULL ))
1286 /* FIXME: maybe we should use the hfile parameter instead */
1287 HANDLE hFile = CreateFileA( filename, GENERIC_READ, FILE_SHARE_READ,
1288 NULL, OPEN_EXISTING, 0, 0 );
1289 if (hFile != INVALID_HANDLE_VALUE)
1291 hmod = PE_LoadImage( hFile, filename, flags );
1292 CloseHandle( hFile );
1294 if (hmod) return (HMODULE)((ULONG_PTR)hmod + 1);
1296 flags |= DONT_RESOLVE_DLL_REFERENCES; /* Just in case */
1297 /* Fallback to normal behaviour */
1300 RtlAcquirePebLock();
1302 wm = MODULE_LoadLibraryExA( libname, hfile, flags );
1303 if ( wm )
1305 if ( !MODULE_DllProcessAttach( wm, NULL ) )
1307 WARN_(module)("Attach failed for module '%s', \n", libname);
1308 MODULE_FreeLibrary(wm);
1309 SetLastError(ERROR_DLL_INIT_FAILED);
1310 wm = NULL;
1314 RtlReleasePebLock();
1315 return wm ? wm->module : 0;
1318 /***********************************************************************
1319 * MODULE_LoadLibraryExA (internal)
1321 * Load a PE style module according to the load order.
1323 * The HFILE parameter is not used and marked reserved in the SDK. I can
1324 * only guess that it should force a file to be mapped, but I rather
1325 * ignore the parameter because it would be extremely difficult to
1326 * integrate this with different types of module represenations.
1329 WINE_MODREF *MODULE_LoadLibraryExA( LPCSTR libname, HFILE hfile, DWORD flags )
1331 DWORD err = GetLastError();
1332 WINE_MODREF *pwm;
1333 int i;
1334 enum loadorder_type loadorder[LOADORDER_NTYPES];
1335 LPSTR filename, p;
1336 const char *filetype = "";
1338 if ( !libname ) return NULL;
1340 filename = HeapAlloc ( GetProcessHeap(), 0, MAX_PATH + 1 );
1341 if ( !filename ) return NULL;
1343 /* build the modules filename */
1344 if (!SearchPathA( NULL, libname, ".dll", MAX_PATH, filename, NULL ))
1346 if ( ! GetSystemDirectoryA ( filename, MAX_PATH ) )
1347 goto error;
1349 /* if the library name contains a path and can not be found, return an error.
1350 exception: if the path is the system directory, proceed, so that modules,
1351 which are not PE-modules can be loaded
1353 if the library name does not contain a path and can not be found, assume the
1354 system directory is meant */
1356 if ( ! FILE_strncasecmp ( filename, libname, strlen ( filename ) ))
1357 strcpy ( filename, libname );
1358 else
1360 if ( strchr ( libname, '\\' ) || strchr ( libname, ':') || strchr ( libname, '/' ) )
1361 goto error;
1362 else
1364 strcat ( filename, "\\" );
1365 strcat ( filename, libname );
1369 /* if the filename doesn't have an extension append .DLL */
1370 if (!(p = strrchr( filename, '.')) || strchr( p, '/' ) || strchr( p, '\\'))
1371 strcat( filename, ".DLL" );
1374 RtlAcquirePebLock();
1376 /* Check for already loaded module */
1377 if (!(pwm = MODULE_FindModule(filename)) &&
1378 /* no path in libpath */
1379 !strchr( libname, '\\' ) && !strchr( libname, ':') && !strchr( libname, '/' ))
1381 LPSTR fn = HeapAlloc ( GetProcessHeap(), 0, MAX_PATH + 1 );
1382 if (fn)
1384 /* since the default loading mechanism uses a more detailed algorithm
1385 * than SearchPath (like using PATH, which can even be modified between
1386 * two attempts of loading the same DLL), the look-up above (with
1387 * SearchPath) can have put the file in system directory, whereas it
1388 * has already been loaded but with a different path. So do a specific
1389 * look-up with filename (without any path)
1391 strcpy ( fn, libname );
1392 /* if the filename doesn't have an extension append .DLL */
1393 if (!strrchr( fn, '.')) strcat( fn, ".dll" );
1394 if ((pwm = MODULE_FindModule( fn )) != NULL)
1395 strcpy( filename, fn );
1396 HeapFree( GetProcessHeap(), 0, fn );
1399 if (pwm)
1401 if(!(pwm->flags & WINE_MODREF_MARKER))
1402 pwm->refCount++;
1404 if ((pwm->flags & WINE_MODREF_DONT_RESOLVE_REFS) &&
1405 !(flags & DONT_RESOLVE_DLL_REFERENCES))
1407 extern DWORD fixup_imports(WINE_MODREF *wm); /*FIXME*/
1408 pwm->flags &= ~WINE_MODREF_DONT_RESOLVE_REFS;
1409 fixup_imports( pwm );
1411 TRACE("Already loaded module '%s' at 0x%08x, count=%d, \n", filename, pwm->module, pwm->refCount);
1412 RtlReleasePebLock();
1413 HeapFree ( GetProcessHeap(), 0, filename );
1414 return pwm;
1417 MODULE_GetLoadOrder( loadorder, filename, TRUE);
1419 for(i = 0; i < LOADORDER_NTYPES; i++)
1421 if (loadorder[i] == LOADORDER_INVALID) break;
1422 SetLastError( ERROR_FILE_NOT_FOUND );
1424 switch(loadorder[i])
1426 case LOADORDER_DLL:
1427 TRACE("Trying native dll '%s'\n", filename);
1428 pwm = PE_LoadLibraryExA(filename, flags);
1429 filetype = "native";
1430 break;
1432 case LOADORDER_SO:
1433 TRACE("Trying so-library '%s'\n", filename);
1434 pwm = ELF_LoadLibraryExA(filename, flags);
1435 filetype = "so";
1436 break;
1438 case LOADORDER_BI:
1439 TRACE("Trying built-in '%s'\n", filename);
1440 pwm = BUILTIN32_LoadLibraryExA(filename, flags);
1441 filetype = "builtin";
1442 break;
1444 default:
1445 pwm = NULL;
1446 break;
1449 if(pwm)
1451 /* Initialize DLL just loaded */
1452 TRACE("Loaded module '%s' at 0x%08x, \n", filename, pwm->module);
1453 if (!TRACE_ON(module))
1454 TRACE_(loaddll)("Loaded module '%s' : %s\n", filename, filetype);
1455 /* Set the refCount here so that an attach failure will */
1456 /* decrement the dependencies through the MODULE_FreeLibrary call. */
1457 pwm->refCount++;
1459 RtlReleasePebLock();
1460 SetLastError( err ); /* restore last error */
1461 HeapFree ( GetProcessHeap(), 0, filename );
1462 return pwm;
1465 if(GetLastError() != ERROR_FILE_NOT_FOUND)
1466 break;
1469 RtlReleasePebLock();
1470 error:
1471 WARN("Failed to load module '%s'; error=0x%08lx, \n", filename, GetLastError());
1472 HeapFree ( GetProcessHeap(), 0, filename );
1473 return NULL;
1476 /***********************************************************************
1477 * LoadLibraryA (KERNEL32.@)
1479 HMODULE WINAPI LoadLibraryA(LPCSTR libname) {
1480 return LoadLibraryExA(libname,0,0);
1483 /***********************************************************************
1484 * LoadLibraryW (KERNEL32.@)
1486 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
1488 return LoadLibraryExW(libnameW,0,0);
1491 /***********************************************************************
1492 * LoadLibrary32 (KERNEL.452)
1493 * LoadSystemLibrary32 (KERNEL.482)
1495 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
1497 HMODULE hModule;
1498 DWORD count;
1500 ReleaseThunkLock( &count );
1501 hModule = LoadLibraryA( libname );
1502 RestoreThunkLock( count );
1503 return hModule;
1506 /***********************************************************************
1507 * LoadLibraryExW (KERNEL32.@)
1509 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW,HANDLE hfile,DWORD flags)
1511 LPSTR libnameA = HEAP_strdupWtoA( GetProcessHeap(), 0, libnameW );
1512 HMODULE ret = LoadLibraryExA( libnameA , hfile, flags );
1514 HeapFree( GetProcessHeap(), 0, libnameA );
1515 return ret;
1518 /***********************************************************************
1519 * MODULE_FlushModrefs
1521 * NOTE: Assumes that the process critical section is held!
1523 * Remove all unused modrefs and call the internal unloading routines
1524 * for the library type.
1526 static void MODULE_FlushModrefs(void)
1528 WINE_MODREF *wm, *next;
1530 for(wm = MODULE_modref_list; wm; wm = next)
1532 next = wm->next;
1534 if(wm->refCount)
1535 continue;
1537 /* Unlink this modref from the chain */
1538 if(wm->next)
1539 wm->next->prev = wm->prev;
1540 if(wm->prev)
1541 wm->prev->next = wm->next;
1542 if(wm == MODULE_modref_list)
1543 MODULE_modref_list = wm->next;
1545 TRACE(" unloading %s\n", wm->filename);
1546 if (wm->dlhandle) wine_dll_unload( wm->dlhandle );
1547 else UnmapViewOfFile( (LPVOID)wm->module );
1548 FreeLibrary16(wm->hDummyMod);
1549 HeapFree( GetProcessHeap(), 0, wm->deps );
1550 HeapFree( GetProcessHeap(), 0, wm );
1554 /***********************************************************************
1555 * FreeLibrary (KERNEL32.@)
1556 * FreeLibrary32 (KERNEL.486)
1558 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
1560 BOOL retv = FALSE;
1561 WINE_MODREF *wm;
1563 if (!hLibModule)
1565 SetLastError( ERROR_INVALID_HANDLE );
1566 return FALSE;
1569 if ((ULONG_PTR)hLibModule & 1)
1571 /* this is a LOAD_LIBRARY_AS_DATAFILE module */
1572 char *ptr = (char *)hLibModule - 1;
1573 UnmapViewOfFile( ptr );
1574 return TRUE;
1577 RtlAcquirePebLock();
1578 free_lib_count++;
1580 if ((wm = MODULE32_LookupHMODULE( hLibModule ))) retv = MODULE_FreeLibrary( wm );
1582 free_lib_count--;
1583 RtlReleasePebLock();
1585 return retv;
1588 /***********************************************************************
1589 * MODULE_DecRefCount
1591 * NOTE: Assumes that the process critical section is held!
1593 static void MODULE_DecRefCount( WINE_MODREF *wm )
1595 int i;
1597 if ( wm->flags & WINE_MODREF_MARKER )
1598 return;
1600 if ( wm->refCount <= 0 )
1601 return;
1603 --wm->refCount;
1604 TRACE("(%s) refCount: %d\n", wm->modname, wm->refCount );
1606 if ( wm->refCount == 0 )
1608 wm->flags |= WINE_MODREF_MARKER;
1610 for ( i = 0; i < wm->nDeps; i++ )
1611 if ( wm->deps[i] )
1612 MODULE_DecRefCount( wm->deps[i] );
1614 wm->flags &= ~WINE_MODREF_MARKER;
1618 /***********************************************************************
1619 * MODULE_FreeLibrary
1621 * NOTE: Assumes that the process critical section is held!
1623 BOOL MODULE_FreeLibrary( WINE_MODREF *wm )
1625 TRACE("(%s) - START\n", wm->modname );
1627 /* Recursively decrement reference counts */
1628 MODULE_DecRefCount( wm );
1630 /* Call process detach notifications */
1631 if ( free_lib_count <= 1 )
1633 MODULE_DllProcessDetach( FALSE, NULL );
1634 SERVER_START_REQ( unload_dll )
1636 req->base = (void *)wm->module;
1637 SERVER_CALL();
1639 SERVER_END_REQ;
1640 MODULE_FlushModrefs();
1643 TRACE("END\n");
1645 return TRUE;
1649 /***********************************************************************
1650 * FreeLibraryAndExitThread (KERNEL32.@)
1652 VOID WINAPI FreeLibraryAndExitThread(HINSTANCE hLibModule, DWORD dwExitCode)
1654 FreeLibrary(hLibModule);
1655 ExitThread(dwExitCode);
1658 /***********************************************************************
1659 * PrivateLoadLibrary (KERNEL32.@)
1661 * FIXME: rough guesswork, don't know what "Private" means
1663 HINSTANCE16 WINAPI PrivateLoadLibrary(LPCSTR libname)
1665 return LoadLibrary16(libname);
1670 /***********************************************************************
1671 * PrivateFreeLibrary (KERNEL32.@)
1673 * FIXME: rough guesswork, don't know what "Private" means
1675 void WINAPI PrivateFreeLibrary(HINSTANCE16 handle)
1677 FreeLibrary16(handle);
1681 /***********************************************************************
1682 * GetProcAddress16 (KERNEL32.37)
1683 * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
1685 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
1687 if (!hModule) {
1688 WARN("hModule may not be 0!\n");
1689 return (FARPROC16)0;
1691 if (HIWORD(hModule))
1693 WARN("hModule is Win32 handle (%08x)\n", hModule );
1694 return (FARPROC16)0;
1696 return GetProcAddress16( LOWORD(hModule), name );
1699 /***********************************************************************
1700 * GetProcAddress (KERNEL.50)
1702 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, LPCSTR name )
1704 WORD ordinal;
1705 FARPROC16 ret;
1707 if (!hModule) hModule = GetCurrentTask();
1708 hModule = GetExePtr( hModule );
1710 if (HIWORD(name) != 0)
1712 ordinal = NE_GetOrdinal( hModule, name );
1713 TRACE("%04x '%s'\n", hModule, name );
1715 else
1717 ordinal = LOWORD(name);
1718 TRACE("%04x %04x\n", hModule, ordinal );
1720 if (!ordinal) return (FARPROC16)0;
1722 ret = NE_GetEntryPoint( hModule, ordinal );
1724 TRACE("returning %08x\n", (UINT)ret );
1725 return ret;
1729 /***********************************************************************
1730 * GetProcAddress (KERNEL32.@)
1732 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1734 return MODULE_GetProcAddress( hModule, function, TRUE );
1737 /***********************************************************************
1738 * GetProcAddress32 (KERNEL.453)
1740 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
1742 return MODULE_GetProcAddress( hModule, function, FALSE );
1745 /***********************************************************************
1746 * MODULE_GetProcAddress (internal)
1748 FARPROC MODULE_GetProcAddress(
1749 HMODULE hModule, /* [in] current module handle */
1750 LPCSTR function, /* [in] function to be looked up */
1751 BOOL snoop )
1753 WINE_MODREF *wm;
1754 FARPROC retproc = 0;
1756 if (HIWORD(function))
1757 TRACE_(win32)("(%08lx,%s)\n",(DWORD)hModule,function);
1758 else
1759 TRACE_(win32)("(%08lx,%p)\n",(DWORD)hModule,function);
1761 RtlAcquirePebLock();
1762 if ((wm = MODULE32_LookupHMODULE( hModule )))
1764 retproc = wm->find_export( wm, function, snoop );
1765 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1767 RtlReleasePebLock();
1768 return retproc;
1772 /***************************************************************************
1773 * HasGPHandler (KERNEL.338)
1776 #include "pshpack1.h"
1777 typedef struct _GPHANDLERDEF
1779 WORD selector;
1780 WORD rangeStart;
1781 WORD rangeEnd;
1782 WORD handler;
1783 } GPHANDLERDEF;
1784 #include "poppack.h"
1786 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1788 HMODULE16 hModule;
1789 int gpOrdinal;
1790 SEGPTR gpPtr;
1791 GPHANDLERDEF *gpHandler;
1793 if ( (hModule = FarGetOwner16( SELECTOROF(address) )) != 0
1794 && (gpOrdinal = NE_GetOrdinal( hModule, "__GP" )) != 0
1795 && (gpPtr = (SEGPTR)NE_GetEntryPointEx( hModule, gpOrdinal, FALSE )) != 0
1796 && !IsBadReadPtr16( gpPtr, sizeof(GPHANDLERDEF) )
1797 && (gpHandler = MapSL( gpPtr )) != NULL )
1799 while (gpHandler->selector)
1801 if ( SELECTOROF(address) == gpHandler->selector
1802 && OFFSETOF(address) >= gpHandler->rangeStart
1803 && OFFSETOF(address) < gpHandler->rangeEnd )
1804 return MAKESEGPTR( gpHandler->selector, gpHandler->handler );
1805 gpHandler++;
1809 return 0;