(strcasecmp): Conform to ANSI specs for toupper.
[wine.git] / loader / module.c
blob2d6b946d75dc19098dd823cdae63dcac2bcead02
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 "callback.h"
21 #include "loadorder.h"
22 #include "server.h"
24 DEFAULT_DEBUG_CHANNEL(module);
25 DECLARE_DEBUG_CHANNEL(win32);
27 WINE_MODREF *MODULE_modref_list = NULL;
29 static WINE_MODREF *exe_modref;
30 static int free_lib_count; /* recursion depth of FreeLibrary calls */
32 /*************************************************************************
33 * MODULE32_LookupHMODULE
34 * looks for the referenced HMODULE in the current process
35 * NOTE: Assumes that the process critical section is held!
37 static WINE_MODREF *MODULE32_LookupHMODULE( HMODULE hmod )
39 WINE_MODREF *wm;
41 if (!hmod)
42 return exe_modref;
44 if (!HIWORD(hmod)) {
45 ERR("tried to lookup 0x%04x in win32 module handler!\n",hmod);
46 SetLastError( ERROR_INVALID_HANDLE );
47 return NULL;
49 for ( wm = MODULE_modref_list; wm; wm=wm->next )
50 if (wm->module == hmod)
51 return wm;
52 SetLastError( ERROR_INVALID_HANDLE );
53 return NULL;
56 /*************************************************************************
57 * MODULE_AllocModRef
59 * Allocate a WINE_MODREF structure and add it to the process list
60 * NOTE: Assumes that the process critical section is held!
62 WINE_MODREF *MODULE_AllocModRef( HMODULE hModule, LPCSTR filename )
64 WINE_MODREF *wm;
65 DWORD len;
67 if ((wm = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*wm) )))
69 wm->module = hModule;
70 wm->tlsindex = -1;
72 wm->filename = HEAP_strdupA( GetProcessHeap(), 0, filename );
73 if ((wm->modname = strrchr( wm->filename, '\\' ))) wm->modname++;
74 else wm->modname = wm->filename;
76 len = GetShortPathNameA( wm->filename, NULL, 0 );
77 wm->short_filename = (char *)HeapAlloc( GetProcessHeap(), 0, len+1 );
78 GetShortPathNameA( wm->filename, wm->short_filename, len+1 );
79 if ((wm->short_modname = strrchr( wm->short_filename, '\\' ))) wm->short_modname++;
80 else wm->short_modname = wm->short_filename;
82 wm->next = MODULE_modref_list;
83 if (wm->next) wm->next->prev = wm;
84 MODULE_modref_list = wm;
86 if (!(PE_HEADER(hModule)->FileHeader.Characteristics & IMAGE_FILE_DLL))
88 if (!exe_modref) exe_modref = wm;
89 else FIXME( "Trying to load second .EXE file: %s\n", filename );
92 return wm;
95 /*************************************************************************
96 * MODULE_InitDLL
98 static BOOL MODULE_InitDLL( WINE_MODREF *wm, DWORD type, LPVOID lpReserved )
100 BOOL retv = TRUE;
102 static LPCSTR typeName[] = { "PROCESS_DETACH", "PROCESS_ATTACH",
103 "THREAD_ATTACH", "THREAD_DETACH" };
104 assert( wm );
106 /* Skip calls for modules loaded with special load flags */
108 if (wm->flags & WINE_MODREF_DONT_RESOLVE_REFS) return TRUE;
110 TRACE("(%s,%s,%p) - CALL\n", wm->modname, typeName[type], lpReserved );
112 /* Call the initialization routine */
113 retv = PE_InitDLL( wm->module, type, lpReserved );
115 /* The state of the module list may have changed due to the call
116 to PE_InitDLL. We cannot assume that this module has not been
117 deleted. */
118 TRACE("(%p,%s,%p) - RETURN %d\n", wm, typeName[type], lpReserved, retv );
120 return retv;
123 /*************************************************************************
124 * MODULE_DllProcessAttach
126 * Send the process attach notification to all DLLs the given module
127 * depends on (recursively). This is somewhat complicated due to the fact that
129 * - we have to respect the module dependencies, i.e. modules implicitly
130 * referenced by another module have to be initialized before the module
131 * itself can be initialized
133 * - the initialization routine of a DLL can itself call LoadLibrary,
134 * thereby introducing a whole new set of dependencies (even involving
135 * the 'old' modules) at any time during the whole process
137 * (Note that this routine can be recursively entered not only directly
138 * from itself, but also via LoadLibrary from one of the called initialization
139 * routines.)
141 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
142 * the process *detach* notifications to be sent in the correct order.
143 * This must not only take into account module dependencies, but also
144 * 'hidden' dependencies created by modules calling LoadLibrary in their
145 * attach notification routine.
147 * The strategy is rather simple: we move a WINE_MODREF to the head of the
148 * list after the attach notification has returned. This implies that the
149 * detach notifications are called in the reverse of the sequence the attach
150 * notifications *returned*.
152 BOOL MODULE_DllProcessAttach( WINE_MODREF *wm, LPVOID lpReserved )
154 BOOL retv = TRUE;
155 int i;
157 RtlAcquirePebLock();
159 if (!wm) wm = exe_modref;
160 assert( wm );
162 /* prevent infinite recursion in case of cyclical dependencies */
163 if ( ( wm->flags & WINE_MODREF_MARKER )
164 || ( wm->flags & WINE_MODREF_PROCESS_ATTACHED ) )
165 goto done;
167 TRACE("(%s,%p) - START\n", wm->modname, lpReserved );
169 /* Tag current MODREF to prevent recursive loop */
170 wm->flags |= WINE_MODREF_MARKER;
172 /* Recursively attach all DLLs this one depends on */
173 for ( i = 0; retv && i < wm->nDeps; i++ )
174 if ( wm->deps[i] )
175 retv = MODULE_DllProcessAttach( wm->deps[i], lpReserved );
177 /* Call DLL entry point */
178 if ( retv )
180 retv = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
181 if ( retv )
182 wm->flags |= WINE_MODREF_PROCESS_ATTACHED;
185 /* Re-insert MODREF at head of list */
186 if ( retv && wm->prev )
188 wm->prev->next = wm->next;
189 if ( wm->next ) wm->next->prev = wm->prev;
191 wm->prev = NULL;
192 wm->next = MODULE_modref_list;
193 MODULE_modref_list = wm->next->prev = wm;
196 /* Remove recursion flag */
197 wm->flags &= ~WINE_MODREF_MARKER;
199 TRACE("(%s,%p) - END\n", wm->modname, lpReserved );
201 done:
202 RtlReleasePebLock();
203 return retv;
206 /*************************************************************************
207 * MODULE_DllProcessDetach
209 * Send DLL process detach notifications. See the comment about calling
210 * sequence at MODULE_DllProcessAttach. Unless the bForceDetach flag
211 * is set, only DLLs with zero refcount are notified.
213 void MODULE_DllProcessDetach( BOOL bForceDetach, LPVOID lpReserved )
215 WINE_MODREF *wm;
217 RtlAcquirePebLock();
221 for ( wm = MODULE_modref_list; wm; wm = wm->next )
223 /* Check whether to detach this DLL */
224 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
225 continue;
226 if ( wm->refCount > 0 && !bForceDetach )
227 continue;
229 /* Call detach notification */
230 wm->flags &= ~WINE_MODREF_PROCESS_ATTACHED;
231 MODULE_InitDLL( wm, DLL_PROCESS_DETACH, lpReserved );
233 /* Restart at head of WINE_MODREF list, as entries might have
234 been added and/or removed while performing the call ... */
235 break;
237 } while ( wm );
239 RtlReleasePebLock();
242 /*************************************************************************
243 * MODULE_DllThreadAttach
245 * Send DLL thread attach notifications. These are sent in the
246 * reverse sequence of process detach notification.
249 void MODULE_DllThreadAttach( LPVOID lpReserved )
251 WINE_MODREF *wm;
253 RtlAcquirePebLock();
255 for ( wm = MODULE_modref_list; wm; wm = wm->next )
256 if ( !wm->next )
257 break;
259 for ( ; wm; wm = wm->prev )
261 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
262 continue;
263 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
264 continue;
266 MODULE_InitDLL( wm, DLL_THREAD_ATTACH, lpReserved );
269 RtlReleasePebLock();
272 /*************************************************************************
273 * MODULE_DllThreadDetach
275 * Send DLL thread detach notifications. These are sent in the
276 * same sequence as process detach notification.
279 void MODULE_DllThreadDetach( LPVOID lpReserved )
281 WINE_MODREF *wm;
283 RtlAcquirePebLock();
285 for ( wm = MODULE_modref_list; wm; wm = wm->next )
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_DETACH, lpReserved );
295 RtlReleasePebLock();
298 /****************************************************************************
299 * DisableThreadLibraryCalls (KERNEL32.74)
301 * Don't call DllEntryPoint for DLL_THREAD_{ATTACH,DETACH} if set.
303 BOOL WINAPI DisableThreadLibraryCalls( HMODULE hModule )
305 WINE_MODREF *wm;
306 BOOL retval = TRUE;
308 RtlAcquirePebLock();
310 wm = MODULE32_LookupHMODULE( hModule );
311 if ( !wm )
312 retval = FALSE;
313 else
314 wm->flags |= WINE_MODREF_NO_DLL_CALLS;
316 RtlReleasePebLock();
318 return retval;
322 /***********************************************************************
323 * MODULE_CreateDummyModule
325 * Create a dummy NE module for Win32 or Winelib.
327 HMODULE MODULE_CreateDummyModule( LPCSTR filename, HMODULE module32 )
329 HMODULE hModule;
330 NE_MODULE *pModule;
331 SEGTABLEENTRY *pSegment;
332 char *pStr,*s;
333 unsigned int len;
334 const char* basename;
335 OFSTRUCT *ofs;
336 int of_size, size;
338 /* Extract base filename */
339 basename = strrchr(filename, '\\');
340 if (!basename) basename = filename;
341 else basename++;
342 len = strlen(basename);
343 if ((s = strchr(basename, '.'))) len = s - basename;
345 /* Allocate module */
346 of_size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName)
347 + strlen(filename) + 1;
348 size = sizeof(NE_MODULE) +
349 /* loaded file info */
350 of_size +
351 /* segment table: DS,CS */
352 2 * sizeof(SEGTABLEENTRY) +
353 /* name table */
354 len + 2 +
355 /* several empty tables */
358 hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
359 if (!hModule) return (HMODULE)11; /* invalid exe */
361 FarSetOwner16( hModule, hModule );
362 pModule = (NE_MODULE *)GlobalLock16( hModule );
364 /* Set all used entries */
365 pModule->magic = IMAGE_OS2_SIGNATURE;
366 pModule->count = 1;
367 pModule->next = 0;
368 pModule->flags = 0;
369 pModule->dgroup = 0;
370 pModule->ss = 1;
371 pModule->cs = 2;
372 pModule->heap_size = 0;
373 pModule->stack_size = 0;
374 pModule->seg_count = 2;
375 pModule->modref_count = 0;
376 pModule->nrname_size = 0;
377 pModule->fileinfo = sizeof(NE_MODULE);
378 pModule->os_flags = NE_OSFLAGS_WINDOWS;
379 pModule->self = hModule;
380 pModule->module32 = module32;
382 /* Set version and flags */
383 if (module32)
385 pModule->expected_version =
386 ((PE_HEADER(module32)->OptionalHeader.MajorSubsystemVersion & 0xff) << 8 ) |
387 (PE_HEADER(module32)->OptionalHeader.MinorSubsystemVersion & 0xff);
388 pModule->flags |= NE_FFLAGS_WIN32;
389 if (PE_HEADER(module32)->FileHeader.Characteristics & IMAGE_FILE_DLL)
390 pModule->flags |= NE_FFLAGS_LIBMODULE | NE_FFLAGS_SINGLEDATA;
393 /* Set loaded file information */
394 ofs = (OFSTRUCT *)(pModule + 1);
395 memset( ofs, 0, of_size );
396 ofs->cBytes = of_size < 256 ? of_size : 255; /* FIXME */
397 strcpy( ofs->szPathName, filename );
399 pSegment = (SEGTABLEENTRY*)((char*)(pModule + 1) + of_size);
400 pModule->seg_table = (int)pSegment - (int)pModule;
401 /* Data segment */
402 pSegment->size = 0;
403 pSegment->flags = NE_SEGFLAGS_DATA;
404 pSegment->minsize = 0x1000;
405 pSegment++;
406 /* Code segment */
407 pSegment->flags = 0;
408 pSegment++;
410 /* Module name */
411 pStr = (char *)pSegment;
412 pModule->name_table = (int)pStr - (int)pModule;
413 assert(len<256);
414 *pStr = len;
415 lstrcpynA( pStr+1, basename, len+1 );
416 pStr += len+2;
418 /* All tables zero terminated */
419 pModule->res_table = pModule->import_table = pModule->entry_table =
420 (int)pStr - (int)pModule;
422 NE_RegisterModule( pModule );
423 return hModule;
427 /**********************************************************************
428 * MODULE_FindModule
430 * Find a (loaded) win32 module depending on path
432 * RETURNS
433 * the module handle if found
434 * 0 if not
436 WINE_MODREF *MODULE_FindModule(
437 LPCSTR path /* [in] pathname of module/library to be found */
439 WINE_MODREF *wm;
440 char dllname[260], *p;
442 /* Append .DLL to name if no extension present */
443 strcpy( dllname, path );
444 if (!(p = strrchr( dllname, '.')) || strchr( p, '/' ) || strchr( p, '\\'))
445 strcat( dllname, ".DLL" );
447 for ( wm = MODULE_modref_list; wm; wm = wm->next )
449 if ( !FILE_strcasecmp( dllname, wm->modname ) )
450 break;
451 if ( !FILE_strcasecmp( dllname, wm->filename ) )
452 break;
453 if ( !FILE_strcasecmp( dllname, wm->short_modname ) )
454 break;
455 if ( !FILE_strcasecmp( dllname, wm->short_filename ) )
456 break;
459 return wm;
463 /* Check whether a file is an OS/2 or a very old Windows executable
464 * by testing on import of KERNEL.
466 * FIXME: is reading the module imports the only way of discerning
467 * old Windows binaries from OS/2 ones ? At least it seems so...
469 static DWORD MODULE_Decide_OS2_OldWin(HANDLE hfile, IMAGE_DOS_HEADER *mz, IMAGE_OS2_HEADER *ne)
471 DWORD currpos = SetFilePointer( hfile, 0, NULL, SEEK_CUR);
472 DWORD type = SCS_OS216_BINARY;
473 LPWORD modtab = NULL;
474 LPSTR nametab = NULL;
475 DWORD len;
476 int i;
478 /* read modref table */
479 if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_modtab, NULL, SEEK_SET ) == -1)
480 || (!(modtab = HeapAlloc( GetProcessHeap(), 0, ne->ne_cmod*sizeof(WORD))))
481 || (!(ReadFile(hfile, modtab, ne->ne_cmod*sizeof(WORD), &len, NULL)))
482 || (len != ne->ne_cmod*sizeof(WORD)) )
483 goto broken;
485 /* read imported names table */
486 if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_imptab, NULL, SEEK_SET ) == -1)
487 || (!(nametab = HeapAlloc( GetProcessHeap(), 0, ne->ne_enttab - ne->ne_imptab)))
488 || (!(ReadFile(hfile, nametab, ne->ne_enttab - ne->ne_imptab, &len, NULL)))
489 || (len != ne->ne_enttab - ne->ne_imptab) )
490 goto broken;
492 for (i=0; i < ne->ne_cmod; i++)
494 LPSTR module = &nametab[modtab[i]];
495 TRACE("modref: %.*s\n", module[0], &module[1]);
496 if (!(strncmp(&module[1], "KERNEL", module[0])))
497 { /* very old Windows file */
498 MESSAGE("This seems to be a very old (pre-3.0) Windows executable. Expect crashes, especially if this is a real-mode binary !\n");
499 type = SCS_WOW_BINARY;
500 goto good;
504 broken:
505 ERR("Hmm, an error occurred. Is this binary file broken ?\n");
507 good:
508 HeapFree( GetProcessHeap(), 0, modtab);
509 HeapFree( GetProcessHeap(), 0, nametab);
510 SetFilePointer( hfile, currpos, NULL, SEEK_SET); /* restore filepos */
511 return type;
514 /***********************************************************************
515 * MODULE_GetBinaryType
517 * The GetBinaryType function determines whether a file is executable
518 * or not and if it is it returns what type of executable it is.
519 * The type of executable is a property that determines in which
520 * subsystem an executable file runs under.
522 * Binary types returned:
523 * SCS_32BIT_BINARY: A Win32 based application
524 * SCS_DOS_BINARY: An MS-Dos based application
525 * SCS_WOW_BINARY: A Win16 based application
526 * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
527 * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
528 * SCS_OS216_BINARY: A 16bit OS/2 based application
530 * Returns TRUE if the file is an executable in which case
531 * the value pointed by lpBinaryType is set.
532 * Returns FALSE if the file is not an executable or if the function fails.
534 * To do so it opens the file and reads in the header information
535 * if the extended header information is not present it will
536 * assume that the file is a DOS executable.
537 * If the extended header information is present it will
538 * determine if the file is a 16 or 32 bit Windows executable
539 * by check the flags in the header.
541 * Note that .COM and .PIF files are only recognized by their
542 * file name extension; but Windows does it the same way ...
544 static BOOL MODULE_GetBinaryType( HANDLE hfile, LPCSTR filename, LPDWORD lpBinaryType )
546 IMAGE_DOS_HEADER mz_header;
547 char magic[4], *ptr;
548 DWORD len;
550 /* Seek to the start of the file and read the DOS header information.
552 if ( SetFilePointer( hfile, 0, NULL, SEEK_SET ) != -1
553 && ReadFile( hfile, &mz_header, sizeof(mz_header), &len, NULL )
554 && len == sizeof(mz_header) )
556 /* Now that we have the header check the e_magic field
557 * to see if this is a dos image.
559 if ( mz_header.e_magic == IMAGE_DOS_SIGNATURE )
561 BOOL lfanewValid = FALSE;
562 /* We do have a DOS image so we will now try to seek into
563 * the file by the amount indicated by the field
564 * "Offset to extended header" and read in the
565 * "magic" field information at that location.
566 * This will tell us if there is more header information
567 * to read or not.
569 /* But before we do we will make sure that header
570 * structure encompasses the "Offset to extended header"
571 * field.
573 if ( (mz_header.e_cparhdr<<4) >= sizeof(IMAGE_DOS_HEADER) )
574 if ( ( mz_header.e_crlc == 0 ) ||
575 ( mz_header.e_lfarlc >= sizeof(IMAGE_DOS_HEADER) ) )
576 if ( mz_header.e_lfanew >= sizeof(IMAGE_DOS_HEADER)
577 && SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET ) != -1
578 && ReadFile( hfile, magic, sizeof(magic), &len, NULL )
579 && len == sizeof(magic) )
580 lfanewValid = TRUE;
582 if ( !lfanewValid )
584 /* If we cannot read this "extended header" we will
585 * assume that we have a simple DOS executable.
587 *lpBinaryType = SCS_DOS_BINARY;
588 return TRUE;
590 else
592 /* Reading the magic field succeeded so
593 * we will try to determine what type it is.
595 if ( *(DWORD*)magic == IMAGE_NT_SIGNATURE )
597 /* This is an NT signature.
599 *lpBinaryType = SCS_32BIT_BINARY;
600 return TRUE;
602 else if ( *(WORD*)magic == IMAGE_OS2_SIGNATURE )
604 /* The IMAGE_OS2_SIGNATURE indicates that the
605 * "extended header is a Windows executable (NE)
606 * header." This can mean either a 16-bit OS/2
607 * or a 16-bit Windows or even a DOS program
608 * (running under a DOS extender). To decide
609 * which, we'll have to read the NE header.
612 IMAGE_OS2_HEADER ne;
613 if ( SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET ) != -1
614 && ReadFile( hfile, &ne, sizeof(ne), &len, NULL )
615 && len == sizeof(ne) )
617 switch ( ne.ne_exetyp )
619 case 2: *lpBinaryType = SCS_WOW_BINARY; return TRUE;
620 case 5: *lpBinaryType = SCS_DOS_BINARY; return TRUE;
621 default: *lpBinaryType =
622 MODULE_Decide_OS2_OldWin(hfile, &mz_header, &ne);
623 return TRUE;
626 /* Couldn't read header, so abort. */
627 return FALSE;
629 else
631 /* Unknown extended header, but this file is nonetheless
632 DOS-executable.
634 *lpBinaryType = SCS_DOS_BINARY;
635 return TRUE;
641 /* If we get here, we don't even have a correct MZ header.
642 * Try to check the file extension for known types ...
644 ptr = strrchr( filename, '.' );
645 if ( ptr && !strchr( ptr, '\\' ) && !strchr( ptr, '/' ) )
647 if ( !FILE_strcasecmp( ptr, ".COM" ) )
649 *lpBinaryType = SCS_DOS_BINARY;
650 return TRUE;
653 if ( !FILE_strcasecmp( ptr, ".PIF" ) )
655 *lpBinaryType = SCS_PIF_BINARY;
656 return TRUE;
660 return FALSE;
663 /***********************************************************************
664 * GetBinaryTypeA [KERNEL32.280]
666 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
668 BOOL ret = FALSE;
669 HANDLE hfile;
671 TRACE_(win32)("%s\n", lpApplicationName );
673 /* Sanity check.
675 if ( lpApplicationName == NULL || lpBinaryType == NULL )
676 return FALSE;
678 /* Open the file indicated by lpApplicationName for reading.
680 hfile = CreateFileA( lpApplicationName, GENERIC_READ, FILE_SHARE_READ,
681 NULL, OPEN_EXISTING, 0, -1 );
682 if ( hfile == INVALID_HANDLE_VALUE )
683 return FALSE;
685 /* Check binary type
687 ret = MODULE_GetBinaryType( hfile, lpApplicationName, lpBinaryType );
689 /* Close the file.
691 CloseHandle( hfile );
693 return ret;
696 /***********************************************************************
697 * GetBinaryTypeW [KERNEL32.281]
699 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
701 BOOL ret = FALSE;
702 LPSTR strNew = NULL;
704 TRACE_(win32)("%s\n", debugstr_w(lpApplicationName) );
706 /* Sanity check.
708 if ( lpApplicationName == NULL || lpBinaryType == NULL )
709 return FALSE;
711 /* Convert the wide string to a ascii string.
713 strNew = HEAP_strdupWtoA( GetProcessHeap(), 0, lpApplicationName );
715 if ( strNew != NULL )
717 ret = GetBinaryTypeA( strNew, lpBinaryType );
719 /* Free the allocated string.
721 HeapFree( GetProcessHeap(), 0, strNew );
724 return ret;
728 /***********************************************************************
729 * WinExec16 (KERNEL.166)
731 HINSTANCE16 WINAPI WinExec16( LPCSTR lpCmdLine, UINT16 nCmdShow )
733 LPCSTR p, args = NULL;
734 LPCSTR name_beg, name_end;
735 LPSTR name, cmdline;
736 int arglen;
737 HINSTANCE16 ret;
738 char buffer[MAX_PATH];
740 if (*lpCmdLine == '"') /* has to be only one and only at beginning ! */
742 name_beg = lpCmdLine+1;
743 p = strchr ( lpCmdLine+1, '"' );
744 if (p)
746 name_end = p;
747 args = strchr ( p, ' ' );
749 else /* yes, even valid with trailing '"' missing */
750 name_end = lpCmdLine+strlen(lpCmdLine);
752 else
754 name_beg = lpCmdLine;
755 args = strchr( lpCmdLine, ' ' );
756 name_end = args ? args : lpCmdLine+strlen(lpCmdLine);
759 if ((name_beg == lpCmdLine) && (!args))
760 { /* just use the original cmdline string as file name */
761 name = (LPSTR)lpCmdLine;
763 else
765 if (!(name = HeapAlloc( GetProcessHeap(), 0, name_end - name_beg + 1 )))
766 return ERROR_NOT_ENOUGH_MEMORY;
767 memcpy( name, name_beg, name_end - name_beg );
768 name[name_end - name_beg] = '\0';
771 if (args)
773 args++;
774 arglen = strlen(args);
775 cmdline = SEGPTR_ALLOC( 2 + arglen );
776 cmdline[0] = (BYTE)arglen;
777 strcpy( cmdline + 1, args );
779 else
781 cmdline = SEGPTR_ALLOC( 2 );
782 cmdline[0] = cmdline[1] = 0;
785 TRACE("name: '%s', cmdline: '%.*s'\n", name, cmdline[0], &cmdline[1]);
787 if (SearchPathA( NULL, name, ".exe", sizeof(buffer), buffer, NULL ))
789 LOADPARAMS16 params;
790 WORD *showCmd = SEGPTR_ALLOC( 2*sizeof(WORD) );
791 showCmd[0] = 2;
792 showCmd[1] = nCmdShow;
794 params.hEnvironment = 0;
795 params.cmdLine = SEGPTR_GET(cmdline);
796 params.showCmd = SEGPTR_GET(showCmd);
797 params.reserved = 0;
799 ret = LoadModule16( buffer, &params );
801 SEGPTR_FREE( showCmd );
802 SEGPTR_FREE( cmdline );
804 else ret = GetLastError();
806 if (name != lpCmdLine) HeapFree( GetProcessHeap(), 0, name );
808 if (ret == 21) /* 32-bit module */
810 DWORD count;
811 ReleaseThunkLock( &count );
812 ret = WinExec( lpCmdLine, nCmdShow );
813 RestoreThunkLock( count );
815 return ret;
818 /***********************************************************************
819 * WinExec (KERNEL32.566)
821 HINSTANCE WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
823 PROCESS_INFORMATION info;
824 STARTUPINFOA startup;
825 HINSTANCE hInstance;
826 char *cmdline;
828 memset( &startup, 0, sizeof(startup) );
829 startup.cb = sizeof(startup);
830 startup.dwFlags = STARTF_USESHOWWINDOW;
831 startup.wShowWindow = nCmdShow;
833 /* cmdline needs to be writeable for CreateProcess */
834 if (!(cmdline = HEAP_strdupA( GetProcessHeap(), 0, lpCmdLine ))) return 0;
836 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
837 0, NULL, NULL, &startup, &info ))
839 /* Give 30 seconds to the app to come up */
840 if (Callout.WaitForInputIdle &&
841 Callout.WaitForInputIdle( info.hProcess, 30000 ) == 0xFFFFFFFF)
842 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
843 hInstance = 33;
844 /* Close off the handles */
845 CloseHandle( info.hThread );
846 CloseHandle( info.hProcess );
848 else if ((hInstance = GetLastError()) >= 32)
850 FIXME("Strange error set by CreateProcess: %d\n", hInstance );
851 hInstance = 11;
853 HeapFree( GetProcessHeap(), 0, cmdline );
854 return hInstance;
857 /**********************************************************************
858 * LoadModule (KERNEL32.499)
860 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
862 LOADPARAMS *params = (LOADPARAMS *)paramBlock;
863 PROCESS_INFORMATION info;
864 STARTUPINFOA startup;
865 HINSTANCE hInstance;
866 LPSTR cmdline, p;
867 char filename[MAX_PATH];
868 BYTE len;
870 if (!name) return ERROR_FILE_NOT_FOUND;
872 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
873 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
874 return GetLastError();
876 len = (BYTE)params->lpCmdLine[0];
877 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
878 return ERROR_NOT_ENOUGH_MEMORY;
880 strcpy( cmdline, filename );
881 p = cmdline + strlen(cmdline);
882 *p++ = ' ';
883 memcpy( p, params->lpCmdLine + 1, len );
884 p[len] = 0;
886 memset( &startup, 0, sizeof(startup) );
887 startup.cb = sizeof(startup);
888 if (params->lpCmdShow)
890 startup.dwFlags = STARTF_USESHOWWINDOW;
891 startup.wShowWindow = params->lpCmdShow[1];
894 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
895 params->lpEnvAddress, NULL, &startup, &info ))
897 /* Give 30 seconds to the app to come up */
898 if (Callout.WaitForInputIdle &&
899 Callout.WaitForInputIdle( info.hProcess, 30000 ) == 0xFFFFFFFF )
900 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
901 hInstance = 33;
902 /* Close off the handles */
903 CloseHandle( info.hThread );
904 CloseHandle( info.hProcess );
906 else if ((hInstance = GetLastError()) >= 32)
908 FIXME("Strange error set by CreateProcess: %d\n", hInstance );
909 hInstance = 11;
912 HeapFree( GetProcessHeap(), 0, cmdline );
913 return hInstance;
917 /*************************************************************************
918 * get_file_name
920 * Helper for CreateProcess: retrieve the file name to load from the
921 * app name and command line. Store the file name in buffer, and
922 * return a possibly modified command line.
924 static LPSTR get_file_name( LPCSTR appname, LPSTR cmdline, LPSTR buffer, int buflen )
926 char *name, *pos, *ret = NULL;
927 const char *p;
929 /* if we have an app name, everything is easy */
931 if (appname)
933 /* use the unmodified app name as file name */
934 lstrcpynA( buffer, appname, buflen );
935 if (!(ret = cmdline))
937 /* no command-line, create one */
938 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(appname) + 3 )))
939 sprintf( ret, "\"%s\"", appname );
941 return ret;
944 if (!cmdline)
946 SetLastError( ERROR_INVALID_PARAMETER );
947 return NULL;
950 /* first check for a quoted file name */
952 if ((cmdline[0] == '"') && ((p = strchr( cmdline + 1, '"' ))))
954 int len = p - cmdline - 1;
955 /* extract the quoted portion as file name */
956 if (!(name = HeapAlloc( GetProcessHeap(), 0, len + 1 ))) return NULL;
957 memcpy( name, cmdline + 1, len );
958 name[len] = 0;
960 if (SearchPathA( NULL, name, ".exe", buflen, buffer, NULL ) ||
961 SearchPathA( NULL, name, NULL, buflen, buffer, NULL ))
962 ret = cmdline; /* no change necessary */
963 goto done;
966 /* now try the command-line word by word */
968 if (!(name = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 1 ))) return NULL;
969 pos = name;
970 p = cmdline;
972 while (*p)
974 do *pos++ = *p++; while (*p && *p != ' ');
975 *pos = 0;
976 TRACE("trying '%s'\n", name );
977 if (SearchPathA( NULL, name, ".exe", buflen, buffer, NULL ) ||
978 SearchPathA( NULL, name, NULL, buflen, buffer, NULL ))
980 ret = cmdline;
981 break;
985 if (!ret || !strchr( name, ' ' )) goto done; /* no change necessary */
987 /* now build a new command-line with quotes */
989 if (!(ret = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 3 ))) goto done;
990 sprintf( ret, "\"%s\"%s", name, p );
992 done:
993 HeapFree( GetProcessHeap(), 0, name );
994 return ret;
998 /**********************************************************************
999 * CreateProcessA (KERNEL32.171)
1001 BOOL WINAPI CreateProcessA( LPCSTR lpApplicationName, LPSTR lpCommandLine,
1002 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1003 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1004 BOOL bInheritHandles, DWORD dwCreationFlags,
1005 LPVOID lpEnvironment, LPCSTR lpCurrentDirectory,
1006 LPSTARTUPINFOA lpStartupInfo,
1007 LPPROCESS_INFORMATION lpProcessInfo )
1009 BOOL retv = FALSE;
1010 HANDLE hFile;
1011 DWORD type;
1012 char name[MAX_PATH];
1013 LPSTR tidy_cmdline;
1015 /* Process the AppName and/or CmdLine to get module name and path */
1017 TRACE("app '%s' cmdline '%s'\n", lpApplicationName, lpCommandLine );
1019 if (!(tidy_cmdline = get_file_name( lpApplicationName, lpCommandLine, name, sizeof(name) )))
1020 return FALSE;
1022 /* Warn if unsupported features are used */
1024 if (dwCreationFlags & DETACHED_PROCESS)
1025 FIXME("(%s,...): DETACHED_PROCESS ignored\n", name);
1026 if (dwCreationFlags & CREATE_NEW_CONSOLE)
1027 FIXME("(%s,...): CREATE_NEW_CONSOLE ignored\n", name);
1028 if (dwCreationFlags & NORMAL_PRIORITY_CLASS)
1029 FIXME("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
1030 if (dwCreationFlags & IDLE_PRIORITY_CLASS)
1031 FIXME("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
1032 if (dwCreationFlags & HIGH_PRIORITY_CLASS)
1033 FIXME("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
1034 if (dwCreationFlags & REALTIME_PRIORITY_CLASS)
1035 FIXME("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
1036 if (dwCreationFlags & CREATE_NEW_PROCESS_GROUP)
1037 FIXME("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
1038 if (dwCreationFlags & CREATE_UNICODE_ENVIRONMENT)
1039 FIXME("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
1040 if (dwCreationFlags & CREATE_SEPARATE_WOW_VDM)
1041 FIXME("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
1042 if (dwCreationFlags & CREATE_SHARED_WOW_VDM)
1043 FIXME("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
1044 if (dwCreationFlags & CREATE_DEFAULT_ERROR_MODE)
1045 FIXME("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
1046 if (dwCreationFlags & CREATE_NO_WINDOW)
1047 FIXME("(%s,...): CREATE_NO_WINDOW ignored\n", name);
1048 if (dwCreationFlags & PROFILE_USER)
1049 FIXME("(%s,...): PROFILE_USER ignored\n", name);
1050 if (dwCreationFlags & PROFILE_KERNEL)
1051 FIXME("(%s,...): PROFILE_KERNEL ignored\n", name);
1052 if (dwCreationFlags & PROFILE_SERVER)
1053 FIXME("(%s,...): PROFILE_SERVER ignored\n", name);
1054 if (lpStartupInfo->lpDesktop)
1055 FIXME("(%s,...): lpStartupInfo->lpDesktop %s ignored\n",
1056 name, lpStartupInfo->lpDesktop);
1057 if (lpStartupInfo->lpTitle)
1058 FIXME("(%s,...): lpStartupInfo->lpTitle %s ignored\n",
1059 name, lpStartupInfo->lpTitle);
1060 if (lpStartupInfo->dwFlags & STARTF_USECOUNTCHARS)
1061 FIXME("(%s,...): STARTF_USECOUNTCHARS (%ld,%ld) ignored\n",
1062 name, lpStartupInfo->dwXCountChars, lpStartupInfo->dwYCountChars);
1063 if (lpStartupInfo->dwFlags & STARTF_USEFILLATTRIBUTE)
1064 FIXME("(%s,...): STARTF_USEFILLATTRIBUTE %lx ignored\n",
1065 name, lpStartupInfo->dwFillAttribute);
1066 if (lpStartupInfo->dwFlags & STARTF_RUNFULLSCREEN)
1067 FIXME("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
1068 if (lpStartupInfo->dwFlags & STARTF_FORCEONFEEDBACK)
1069 FIXME("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
1070 if (lpStartupInfo->dwFlags & STARTF_FORCEOFFFEEDBACK)
1071 FIXME("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
1072 if (lpStartupInfo->dwFlags & STARTF_USEHOTKEY)
1073 FIXME("(%s,...): STARTF_USEHOTKEY ignored\n", name);
1075 /* Open file and determine executable type */
1077 hFile = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, -1 );
1078 if (hFile == INVALID_HANDLE_VALUE) goto done;
1080 if ( !MODULE_GetBinaryType( hFile, name, &type ) )
1082 CloseHandle( hFile );
1083 retv = PROCESS_Create( -1, name, tidy_cmdline, lpEnvironment,
1084 lpProcessAttributes, lpThreadAttributes,
1085 bInheritHandles, dwCreationFlags,
1086 lpStartupInfo, lpProcessInfo, lpCurrentDirectory );
1087 goto done;
1090 /* Create process */
1092 switch ( type )
1094 case SCS_32BIT_BINARY:
1095 case SCS_WOW_BINARY:
1096 case SCS_DOS_BINARY:
1097 retv = PROCESS_Create( hFile, name, tidy_cmdline, lpEnvironment,
1098 lpProcessAttributes, lpThreadAttributes,
1099 bInheritHandles, dwCreationFlags,
1100 lpStartupInfo, lpProcessInfo, lpCurrentDirectory);
1101 break;
1103 case SCS_PIF_BINARY:
1104 case SCS_POSIX_BINARY:
1105 case SCS_OS216_BINARY:
1106 FIXME("Unsupported executable type: %ld\n", type );
1107 /* fall through */
1109 default:
1110 SetLastError( ERROR_BAD_FORMAT );
1111 break;
1113 CloseHandle( hFile );
1115 done:
1116 if (tidy_cmdline != lpCommandLine) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1117 return retv;
1120 /**********************************************************************
1121 * CreateProcessW (KERNEL32.172)
1122 * NOTES
1123 * lpReserved is not converted
1125 BOOL WINAPI CreateProcessW( LPCWSTR lpApplicationName, LPWSTR lpCommandLine,
1126 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1127 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1128 BOOL bInheritHandles, DWORD dwCreationFlags,
1129 LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory,
1130 LPSTARTUPINFOW lpStartupInfo,
1131 LPPROCESS_INFORMATION lpProcessInfo )
1132 { BOOL ret;
1133 STARTUPINFOA StartupInfoA;
1135 LPSTR lpApplicationNameA = HEAP_strdupWtoA (GetProcessHeap(),0,lpApplicationName);
1136 LPSTR lpCommandLineA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCommandLine);
1137 LPSTR lpCurrentDirectoryA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCurrentDirectory);
1139 memcpy (&StartupInfoA, lpStartupInfo, sizeof(STARTUPINFOA));
1140 StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpDesktop);
1141 StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpTitle);
1143 TRACE_(win32)("(%s,%s,...)\n", debugstr_w(lpApplicationName), debugstr_w(lpCommandLine));
1145 if (lpStartupInfo->lpReserved)
1146 FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n", debugstr_w(lpStartupInfo->lpReserved));
1148 ret = CreateProcessA( lpApplicationNameA, lpCommandLineA,
1149 lpProcessAttributes, lpThreadAttributes,
1150 bInheritHandles, dwCreationFlags,
1151 lpEnvironment, lpCurrentDirectoryA,
1152 &StartupInfoA, lpProcessInfo );
1154 HeapFree( GetProcessHeap(), 0, lpCurrentDirectoryA );
1155 HeapFree( GetProcessHeap(), 0, lpCommandLineA );
1156 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1157 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1159 return ret;
1162 /***********************************************************************
1163 * GetModuleHandleA (KERNEL32.237)
1165 HMODULE WINAPI GetModuleHandleA(LPCSTR module)
1167 WINE_MODREF *wm;
1169 if ( module == NULL )
1170 wm = exe_modref;
1171 else
1172 wm = MODULE_FindModule( module );
1174 return wm? wm->module : 0;
1177 /***********************************************************************
1178 * GetModuleHandleW
1180 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
1182 HMODULE hModule;
1183 LPSTR modulea = HEAP_strdupWtoA( GetProcessHeap(), 0, module );
1184 hModule = GetModuleHandleA( modulea );
1185 HeapFree( GetProcessHeap(), 0, modulea );
1186 return hModule;
1190 /***********************************************************************
1191 * GetModuleFileNameA (KERNEL32.235)
1193 * GetModuleFileNameA seems to *always* return the long path;
1194 * it's only GetModuleFileName16 that decides between short/long path
1195 * by checking if exe version >= 4.0.
1196 * (SDK docu doesn't mention this)
1198 DWORD WINAPI GetModuleFileNameA(
1199 HMODULE hModule, /* [in] module handle (32bit) */
1200 LPSTR lpFileName, /* [out] filenamebuffer */
1201 DWORD size ) /* [in] size of filenamebuffer */
1203 WINE_MODREF *wm;
1205 RtlAcquirePebLock();
1207 lpFileName[0] = 0;
1208 if ((wm = MODULE32_LookupHMODULE( hModule )))
1209 lstrcpynA( lpFileName, wm->filename, size );
1211 RtlReleasePebLock();
1212 TRACE("%s\n", lpFileName );
1213 return strlen(lpFileName);
1217 /***********************************************************************
1218 * GetModuleFileNameW (KERNEL32.236)
1220 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName,
1221 DWORD size )
1223 LPSTR fnA = (char*)HeapAlloc( GetProcessHeap(), 0, size );
1224 DWORD res = GetModuleFileNameA( hModule, fnA, size );
1225 if (size > 0 && !MultiByteToWideChar( CP_ACP, 0, fnA, -1, lpFileName, size ))
1226 lpFileName[size-1] = 0;
1227 HeapFree( GetProcessHeap(), 0, fnA );
1228 return res;
1232 /***********************************************************************
1233 * LoadLibraryExA (KERNEL32)
1235 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
1237 WINE_MODREF *wm;
1239 if(!libname)
1241 SetLastError(ERROR_INVALID_PARAMETER);
1242 return 0;
1245 if (flags & LOAD_LIBRARY_AS_DATAFILE)
1247 char filename[256];
1248 HFILE hFile;
1249 HMODULE hmod = 0;
1251 if (!SearchPathA( NULL, libname, ".dll", sizeof(filename), filename, NULL ))
1252 return 0;
1253 /* FIXME: maybe we should use the hfile parameter instead */
1254 hFile = CreateFileA( filename, GENERIC_READ, FILE_SHARE_READ,
1255 NULL, OPEN_EXISTING, 0, -1 );
1256 if (hFile != INVALID_HANDLE_VALUE)
1258 hmod = PE_LoadImage( hFile, filename, flags );
1259 CloseHandle( hFile );
1261 return hmod;
1264 RtlAcquirePebLock();
1266 wm = MODULE_LoadLibraryExA( libname, hfile, flags );
1267 if ( wm )
1269 if ( !MODULE_DllProcessAttach( wm, NULL ) )
1271 WARN_(module)("Attach failed for module '%s', \n", libname);
1272 MODULE_FreeLibrary(wm);
1273 SetLastError(ERROR_DLL_INIT_FAILED);
1274 wm = NULL;
1278 RtlReleasePebLock();
1279 return wm ? wm->module : 0;
1282 /***********************************************************************
1283 * MODULE_LoadLibraryExA (internal)
1285 * Load a PE style module according to the load order.
1287 * The HFILE parameter is not used and marked reserved in the SDK. I can
1288 * only guess that it should force a file to be mapped, but I rather
1289 * ignore the parameter because it would be extremely difficult to
1290 * integrate this with different types of module represenations.
1293 WINE_MODREF *MODULE_LoadLibraryExA( LPCSTR libname, HFILE hfile, DWORD flags )
1295 DWORD err = GetLastError();
1296 WINE_MODREF *pwm;
1297 int i;
1298 module_loadorder_t *plo;
1299 LPSTR filename, p;
1301 if ( !libname ) return NULL;
1303 filename = HeapAlloc ( GetProcessHeap(), 0, MAX_PATH + 1 );
1304 if ( !filename ) return NULL;
1306 /* build the modules filename */
1307 if (!SearchPathA( NULL, libname, ".dll", MAX_PATH, filename, NULL ))
1309 if ( ! GetSystemDirectoryA ( filename, MAX_PATH ) )
1310 goto error;
1312 /* if the library name contains a path and can not be found, return an error.
1313 exception: if the path is the system directory, proceed, so that modules,
1314 which are not PE-modules can be loaded
1316 if the library name does not contain a path and can not be found, assume the
1317 system directory is meant */
1319 if ( ! FILE_strncasecmp ( filename, libname, strlen ( filename ) ))
1320 strcpy ( filename, libname );
1321 else
1323 if ( strchr ( libname, '\\' ) || strchr ( libname, ':') || strchr ( libname, '/' ) )
1324 goto error;
1325 else
1327 strcat ( filename, "\\" );
1328 strcat ( filename, libname );
1332 /* if the filename doesn't have an extension append .DLL */
1333 if (!(p = strrchr( filename, '.')) || strchr( p, '/' ) || strchr( p, '\\'))
1334 strcat( filename, ".DLL" );
1337 RtlAcquirePebLock();
1339 /* Check for already loaded module */
1340 if (!(pwm = MODULE_FindModule(filename)) &&
1341 /* no path in libpath */
1342 !strchr( libname, '\\' ) && !strchr( libname, ':') && !strchr( libname, '/' ))
1344 LPSTR fn = HeapAlloc ( GetProcessHeap(), 0, MAX_PATH + 1 );
1345 if (fn)
1347 /* since the default loading mechanism uses a more detailed algorithm
1348 * than SearchPath (like using PATH, which can even be modified between
1349 * two attempts of loading the same DLL), the look-up above (with
1350 * SearchPath) can have put the file in system directory, whereas it
1351 * has already been loaded but with a different path. So do a specific
1352 * look-up with filename (without any path)
1354 strcpy ( fn, libname );
1355 /* if the filename doesn't have an extension append .DLL */
1356 if (!strrchr( fn, '.')) strcat( fn, ".dll" );
1357 if ((pwm = MODULE_FindModule( fn )) != NULL)
1358 strcpy( filename, fn );
1359 HeapFree( GetProcessHeap(), 0, fn );
1362 if (pwm)
1364 if(!(pwm->flags & WINE_MODREF_MARKER))
1365 pwm->refCount++;
1367 if ((pwm->flags & WINE_MODREF_DONT_RESOLVE_REFS) &&
1368 !(flags & DONT_RESOLVE_DLL_REFERENCES))
1370 extern DWORD fixup_imports(WINE_MODREF *wm); /*FIXME*/
1371 pwm->flags &= ~WINE_MODREF_DONT_RESOLVE_REFS;
1372 fixup_imports( pwm );
1374 TRACE("Already loaded module '%s' at 0x%08x, count=%d, \n", filename, pwm->module, pwm->refCount);
1375 RtlReleasePebLock();
1376 HeapFree ( GetProcessHeap(), 0, filename );
1377 return pwm;
1380 plo = MODULE_GetLoadOrder(filename, TRUE);
1382 for(i = 0; i < MODULE_LOADORDER_NTYPES; i++)
1384 SetLastError( ERROR_FILE_NOT_FOUND );
1385 switch(plo->loadorder[i])
1387 case MODULE_LOADORDER_DLL:
1388 TRACE("Trying native dll '%s'\n", filename);
1389 pwm = PE_LoadLibraryExA(filename, flags);
1390 break;
1392 case MODULE_LOADORDER_SO:
1393 TRACE("Trying so-library '%s'\n", filename);
1394 if (!(pwm = BUILTIN32_LoadLibraryExA(filename, flags)))
1395 pwm = ELF_LoadLibraryExA(filename, flags);
1396 break;
1398 case MODULE_LOADORDER_BI:
1399 TRACE("Trying built-in '%s'\n", filename);
1400 pwm = BUILTIN32_LoadLibraryExA(filename, flags);
1401 break;
1403 default:
1404 ERR("Got invalid loadorder type %d (%s index %d)\n", plo->loadorder[i], plo->modulename, i);
1405 /* Fall through */
1407 case MODULE_LOADORDER_INVALID: /* We ignore this as it is an empty entry */
1408 pwm = NULL;
1409 break;
1412 if(pwm)
1414 /* Initialize DLL just loaded */
1415 TRACE("Loaded module '%s' at 0x%08x, \n", filename, pwm->module);
1417 /* Set the refCount here so that an attach failure will */
1418 /* decrement the dependencies through the MODULE_FreeLibrary call. */
1419 pwm->refCount++;
1421 RtlReleasePebLock();
1422 SetLastError( err ); /* restore last error */
1423 HeapFree ( GetProcessHeap(), 0, filename );
1424 return pwm;
1427 if(GetLastError() != ERROR_FILE_NOT_FOUND)
1428 break;
1431 RtlReleasePebLock();
1432 error:
1433 WARN("Failed to load module '%s'; error=0x%08lx, \n", filename, GetLastError());
1434 HeapFree ( GetProcessHeap(), 0, filename );
1435 return NULL;
1438 /***********************************************************************
1439 * LoadLibraryA (KERNEL32)
1441 HMODULE WINAPI LoadLibraryA(LPCSTR libname) {
1442 return LoadLibraryExA(libname,0,0);
1445 /***********************************************************************
1446 * LoadLibraryW (KERNEL32)
1448 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
1450 return LoadLibraryExW(libnameW,0,0);
1453 /***********************************************************************
1454 * LoadLibrary32_16 (KERNEL.452)
1456 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
1458 HMODULE hModule;
1459 DWORD count;
1461 ReleaseThunkLock( &count );
1462 hModule = LoadLibraryA( libname );
1463 RestoreThunkLock( count );
1464 return hModule;
1467 /***********************************************************************
1468 * LoadLibraryExW (KERNEL32)
1470 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW,HANDLE hfile,DWORD flags)
1472 LPSTR libnameA = HEAP_strdupWtoA( GetProcessHeap(), 0, libnameW );
1473 HMODULE ret = LoadLibraryExA( libnameA , hfile, flags );
1475 HeapFree( GetProcessHeap(), 0, libnameA );
1476 return ret;
1479 /***********************************************************************
1480 * MODULE_FlushModrefs
1482 * NOTE: Assumes that the process critical section is held!
1484 * Remove all unused modrefs and call the internal unloading routines
1485 * for the library type.
1487 static void MODULE_FlushModrefs(void)
1489 WINE_MODREF *wm, *next;
1491 for(wm = MODULE_modref_list; wm; wm = next)
1493 next = wm->next;
1495 if(wm->refCount)
1496 continue;
1498 /* Unlink this modref from the chain */
1499 if(wm->next)
1500 wm->next->prev = wm->prev;
1501 if(wm->prev)
1502 wm->prev->next = wm->next;
1503 if(wm == MODULE_modref_list)
1504 MODULE_modref_list = wm->next;
1506 TRACE(" unloading %s\n", wm->filename);
1507 /* VirtualFree( (LPVOID)wm->module, 0, MEM_RELEASE ); */ /* FIXME */
1508 /* if (wm->dlhandle) wine_dlclose( wm->dlhandle, NULL, 0 ); */ /* FIXME */
1509 FreeLibrary16(wm->hDummyMod);
1510 HeapFree( GetProcessHeap(), 0, wm->deps );
1511 HeapFree( GetProcessHeap(), 0, wm->filename );
1512 HeapFree( GetProcessHeap(), 0, wm->short_filename );
1513 HeapFree( GetProcessHeap(), 0, wm );
1517 /***********************************************************************
1518 * FreeLibrary
1520 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
1522 BOOL retv = FALSE;
1523 WINE_MODREF *wm;
1525 RtlAcquirePebLock();
1526 free_lib_count++;
1528 wm = MODULE32_LookupHMODULE( hLibModule );
1529 if ( !wm || !hLibModule )
1530 SetLastError( ERROR_INVALID_HANDLE );
1531 else
1532 retv = MODULE_FreeLibrary( wm );
1534 free_lib_count--;
1535 RtlReleasePebLock();
1537 return retv;
1540 /***********************************************************************
1541 * MODULE_DecRefCount
1543 * NOTE: Assumes that the process critical section is held!
1545 static void MODULE_DecRefCount( WINE_MODREF *wm )
1547 int i;
1549 if ( wm->flags & WINE_MODREF_MARKER )
1550 return;
1552 if ( wm->refCount <= 0 )
1553 return;
1555 --wm->refCount;
1556 TRACE("(%s) refCount: %d\n", wm->modname, wm->refCount );
1558 if ( wm->refCount == 0 )
1560 wm->flags |= WINE_MODREF_MARKER;
1562 for ( i = 0; i < wm->nDeps; i++ )
1563 if ( wm->deps[i] )
1564 MODULE_DecRefCount( wm->deps[i] );
1566 wm->flags &= ~WINE_MODREF_MARKER;
1570 /***********************************************************************
1571 * MODULE_FreeLibrary
1573 * NOTE: Assumes that the process critical section is held!
1575 BOOL MODULE_FreeLibrary( WINE_MODREF *wm )
1577 TRACE("(%s) - START\n", wm->modname );
1579 /* Recursively decrement reference counts */
1580 MODULE_DecRefCount( wm );
1582 /* Call process detach notifications */
1583 if ( free_lib_count <= 1 )
1585 MODULE_DllProcessDetach( FALSE, NULL );
1586 SERVER_START_REQ
1588 struct unload_dll_request *req = server_alloc_req( sizeof(*req), 0 );
1589 req->base = (void *)wm->module;
1590 server_call_noerr( REQ_UNLOAD_DLL );
1592 SERVER_END_REQ;
1593 MODULE_FlushModrefs();
1596 TRACE("END\n");
1598 return TRUE;
1602 /***********************************************************************
1603 * FreeLibraryAndExitThread
1605 VOID WINAPI FreeLibraryAndExitThread(HINSTANCE hLibModule, DWORD dwExitCode)
1607 FreeLibrary(hLibModule);
1608 ExitThread(dwExitCode);
1611 /***********************************************************************
1612 * PrivateLoadLibrary (KERNEL32)
1614 * FIXME: rough guesswork, don't know what "Private" means
1616 HINSTANCE WINAPI PrivateLoadLibrary(LPCSTR libname)
1618 return (HINSTANCE)LoadLibrary16(libname);
1623 /***********************************************************************
1624 * PrivateFreeLibrary (KERNEL32)
1626 * FIXME: rough guesswork, don't know what "Private" means
1628 void WINAPI PrivateFreeLibrary(HINSTANCE handle)
1630 FreeLibrary16((HINSTANCE16)handle);
1634 /***********************************************************************
1635 * WIN32_GetProcAddress16 (KERNEL32.36)
1636 * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
1638 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
1640 if (!hModule) {
1641 WARN("hModule may not be 0!\n");
1642 return (FARPROC16)0;
1644 if (HIWORD(hModule))
1646 WARN("hModule is Win32 handle (%08x)\n", hModule );
1647 return (FARPROC16)0;
1649 return GetProcAddress16( hModule, name );
1652 /***********************************************************************
1653 * GetProcAddress16 (KERNEL.50)
1655 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, LPCSTR name )
1657 WORD ordinal;
1658 FARPROC16 ret;
1660 if (!hModule) hModule = GetCurrentTask();
1661 hModule = GetExePtr( hModule );
1663 if (HIWORD(name) != 0)
1665 ordinal = NE_GetOrdinal( hModule, name );
1666 TRACE("%04x '%s'\n", hModule, name );
1668 else
1670 ordinal = LOWORD(name);
1671 TRACE("%04x %04x\n", hModule, ordinal );
1673 if (!ordinal) return (FARPROC16)0;
1675 ret = NE_GetEntryPoint( hModule, ordinal );
1677 TRACE("returning %08x\n", (UINT)ret );
1678 return ret;
1682 /***********************************************************************
1683 * GetProcAddress (KERNEL32.257)
1685 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1687 return MODULE_GetProcAddress( hModule, function, TRUE );
1690 /***********************************************************************
1691 * GetProcAddress32 (KERNEL.453)
1693 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
1695 return MODULE_GetProcAddress( hModule, function, FALSE );
1698 /***********************************************************************
1699 * MODULE_GetProcAddress (internal)
1701 FARPROC MODULE_GetProcAddress(
1702 HMODULE hModule, /* [in] current module handle */
1703 LPCSTR function, /* [in] function to be looked up */
1704 BOOL snoop )
1706 WINE_MODREF *wm;
1707 FARPROC retproc = 0;
1709 if (HIWORD(function))
1710 TRACE_(win32)("(%08lx,%s)\n",(DWORD)hModule,function);
1711 else
1712 TRACE_(win32)("(%08lx,%p)\n",(DWORD)hModule,function);
1714 RtlAcquirePebLock();
1715 if ((wm = MODULE32_LookupHMODULE( hModule )))
1717 retproc = wm->find_export( wm, function, snoop );
1718 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1720 RtlReleasePebLock();
1721 return retproc;
1725 /***************************************************************************
1726 * HasGPHandler (KERNEL.338)
1729 #include "pshpack1.h"
1730 typedef struct _GPHANDLERDEF
1732 WORD selector;
1733 WORD rangeStart;
1734 WORD rangeEnd;
1735 WORD handler;
1736 } GPHANDLERDEF;
1737 #include "poppack.h"
1739 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1741 HMODULE16 hModule;
1742 int gpOrdinal;
1743 SEGPTR gpPtr;
1744 GPHANDLERDEF *gpHandler;
1746 if ( (hModule = FarGetOwner16( SELECTOROF(address) )) != 0
1747 && (gpOrdinal = NE_GetOrdinal( hModule, "__GP" )) != 0
1748 && (gpPtr = (SEGPTR)NE_GetEntryPointEx( hModule, gpOrdinal, FALSE )) != 0
1749 && !IsBadReadPtr16( gpPtr, sizeof(GPHANDLERDEF) )
1750 && (gpHandler = MapSL( gpPtr )) != NULL )
1752 while (gpHandler->selector)
1754 if ( SELECTOROF(address) == gpHandler->selector
1755 && OFFSETOF(address) >= gpHandler->rangeStart
1756 && OFFSETOF(address) < gpHandler->rangeEnd )
1757 return MAKESEGPTR( gpHandler->selector, gpHandler->handler );
1758 gpHandler++;
1762 return 0;