Fixed copyright date.
[wine/testsucceed.git] / loader / module.c
blobb49e28b6ad4ebbce3deb706db3174b122686a1db
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 = HeapAlloc( GetProcessHeap(), 0, 2 + arglen );
808 cmdline[0] = (BYTE)arglen;
809 strcpy( cmdline + 1, args );
811 else
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 ))
821 LOADPARAMS16 params;
822 WORD showCmd[2];
823 showCmd[0] = 2;
824 showCmd[1] = nCmdShow;
826 params.hEnvironment = 0;
827 params.cmdLine = MapLS( cmdline );
828 params.showCmd = MapLS( showCmd );
829 params.reserved = 0;
831 ret = LoadModule16( buffer, &params );
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 */
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", debugstr_a(lpApplicationName), debugstr_a(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 & 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 );
1114 goto done;
1117 /* Create process */
1119 switch ( type )
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);
1128 break;
1130 case SCS_PIF_BINARY:
1131 case SCS_POSIX_BINARY:
1132 case SCS_OS216_BINARY:
1133 FIXME("Unsupported executable type: %ld\n", type );
1134 /* fall through */
1136 default:
1137 SetLastError( ERROR_BAD_FORMAT );
1138 break;
1140 CloseHandle( hFile );
1142 done:
1143 if (tidy_cmdline != lpCommandLine) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1144 return retv;
1147 /**********************************************************************
1148 * CreateProcessW (KERNEL32.@)
1149 * NOTES
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 )
1159 { BOOL ret;
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 );
1186 return ret;
1189 /***********************************************************************
1190 * GetModuleHandleA (KERNEL32.@)
1191 * GetModuleHandle32 (KERNEL.488)
1193 HMODULE WINAPI GetModuleHandleA(LPCSTR module)
1195 WINE_MODREF *wm;
1197 if ( module == NULL )
1198 wm = exe_modref;
1199 else
1200 wm = MODULE_FindModule( module );
1202 return wm? wm->module : 0;
1205 /***********************************************************************
1206 * GetModuleHandleW (KERNEL32.@)
1208 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
1210 HMODULE hModule;
1211 LPSTR modulea = HEAP_strdupWtoA( GetProcessHeap(), 0, module );
1212 hModule = GetModuleHandleA( modulea );
1213 HeapFree( GetProcessHeap(), 0, modulea );
1214 return hModule;
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 */
1232 WINE_MODREF *wm;
1234 RtlAcquirePebLock();
1236 lpFileName[0] = 0;
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,
1250 DWORD size )
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 );
1257 return res;
1261 /***********************************************************************
1262 * LoadLibraryExA (KERNEL32.@)
1264 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
1266 WINE_MODREF *wm;
1268 if(!libname)
1270 SetLastError(ERROR_INVALID_PARAMETER);
1271 return 0;
1274 if (flags & LOAD_LIBRARY_AS_DATAFILE)
1276 char filename[256];
1277 HMODULE hmod = 0;
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 );
1299 if ( wm )
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);
1306 wm = NULL;
1310 RtlReleasePebLock();
1311 return wm ? wm->module : 0;
1314 /***********************************************************************
1315 * allocate_lib_dir
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)
1323 LPCSTR p, pmax;
1324 LPSTR result;
1325 int length;
1327 pmax = 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);
1336 if (result)
1338 strncpy (result, libname, length);
1339 result [length] = '\0';
1342 return result;
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();
1369 WINE_MODREF *pwm;
1370 int i;
1371 enum loadorder_type loadorder[LOADORDER_NTYPES];
1372 LPSTR filename, p;
1373 const char *filetype = "";
1374 DWORD found;
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);
1393 else
1394 found = DIR_SearchAlternatePath(libdir, libname, ".dll", MAX_PATH, filename, NULL);
1396 /* build the modules filename */
1397 if (!found)
1399 if ( ! GetSystemDirectoryA ( filename, MAX_PATH ) )
1400 goto error;
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 );
1411 else
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 );
1427 if (fn)
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 );
1444 if (pwm)
1446 if(!(pwm->flags & WINE_MODREF_MARKER))
1447 pwm->refCount++;
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 );
1459 libdir = NULL;
1461 RtlReleasePebLock();
1462 HeapFree ( GetProcessHeap(), 0, filename );
1463 return pwm;
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])
1475 case LOADORDER_DLL:
1476 TRACE("Trying native dll '%s'\n", filename);
1477 pwm = PE_LoadLibraryExA(filename, flags);
1478 filetype = "native";
1479 break;
1481 case LOADORDER_SO:
1482 TRACE("Trying so-library '%s'\n", filename);
1483 pwm = ELF_LoadLibraryExA(filename, flags);
1484 filetype = "so";
1485 break;
1487 case LOADORDER_BI:
1488 TRACE("Trying built-in '%s'\n", filename);
1489 pwm = BUILTIN32_LoadLibraryExA(filename, flags);
1490 filetype = "builtin";
1491 break;
1493 default:
1494 pwm = NULL;
1495 break;
1498 if(pwm)
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. */
1506 pwm->refCount++;
1508 if (allocated_libdir)
1510 HeapFree ( GetProcessHeap(), 0, (LPSTR)libdir );
1511 libdir = NULL;
1513 RtlReleasePebLock();
1514 SetLastError( err ); /* restore last error */
1515 HeapFree ( GetProcessHeap(), 0, filename );
1516 return pwm;
1519 if(GetLastError() != ERROR_FILE_NOT_FOUND)
1520 break;
1523 error:
1524 if (allocated_libdir)
1526 HeapFree ( GetProcessHeap(), 0, (LPSTR)libdir );
1527 libdir = NULL;
1529 RtlReleasePebLock();
1530 WARN("Failed to load module '%s'; error=0x%08lx\n", filename, GetLastError());
1531 HeapFree ( GetProcessHeap(), 0, filename );
1532 return NULL;
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 )
1556 HMODULE hModule;
1557 DWORD count;
1559 ReleaseThunkLock( &count );
1560 hModule = LoadLibraryA( libname );
1561 RestoreThunkLock( count );
1562 return hModule;
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 );
1574 return ret;
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)
1591 next = wm->next;
1593 if(wm->refCount)
1594 continue;
1596 /* Unlink this modref from the chain */
1597 if(wm->next)
1598 wm->next->prev = wm->prev;
1599 if(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)
1619 BOOL retv = FALSE;
1620 WINE_MODREF *wm;
1622 if (!hLibModule)
1624 SetLastError( ERROR_INVALID_HANDLE );
1625 return FALSE;
1628 if ((ULONG_PTR)hLibModule & 1)
1630 /* this is a LOAD_LIBRARY_AS_DATAFILE module */
1631 char *ptr = (char *)hLibModule - 1;
1632 UnmapViewOfFile( ptr );
1633 return TRUE;
1636 RtlAcquirePebLock();
1637 free_lib_count++;
1639 if ((wm = MODULE32_LookupHMODULE( hLibModule ))) retv = MODULE_FreeLibrary( wm );
1641 free_lib_count--;
1642 RtlReleasePebLock();
1644 return retv;
1647 /***********************************************************************
1648 * MODULE_DecRefCount
1650 * NOTE: Assumes that the process critical section is held!
1652 static void MODULE_DecRefCount( WINE_MODREF *wm )
1654 int i;
1656 if ( wm->flags & WINE_MODREF_MARKER )
1657 return;
1659 if ( wm->refCount <= 0 )
1660 return;
1662 --wm->refCount;
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++ )
1670 if ( wm->deps[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 );
1698 SERVER_END_REQ;
1699 MODULE_FlushModrefs();
1702 TRACE("END\n");
1704 return TRUE;
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 )
1746 if (!hModule) {
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 )
1763 WORD ordinal;
1764 FARPROC16 ret;
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 );
1774 else
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 );
1784 return 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 */
1810 BOOL snoop )
1812 WINE_MODREF *wm;
1813 FARPROC retproc = 0;
1815 if (HIWORD(function))
1816 TRACE_(win32)("(%08lx,%s)\n",(DWORD)hModule,function);
1817 else
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();
1827 return retproc;
1831 /***************************************************************************
1832 * HasGPHandler (KERNEL.338)
1835 #include "pshpack1.h"
1836 typedef struct _GPHANDLERDEF
1838 WORD selector;
1839 WORD rangeStart;
1840 WORD rangeEnd;
1841 WORD handler;
1842 } GPHANDLERDEF;
1843 #include "poppack.h"
1845 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1847 HMODULE16 hModule;
1848 int gpOrdinal;
1849 SEGPTR gpPtr;
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 );
1864 gpHandler++;
1868 return 0;