Compile fix for building wine outside the source tree.
[wine/wine64.git] / loader / module.c
blobe845783447b435d07b573a4eebab8c4edad76ad3
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 "process.h"
18 #include "selectors.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);
28 /*************************************************************************
29 * MODULE32_LookupHMODULE
30 * looks for the referenced HMODULE in the current process
31 * NOTE: Assumes that the process critical section is held!
33 static WINE_MODREF *MODULE32_LookupHMODULE( HMODULE hmod )
35 WINE_MODREF *wm;
37 if (!hmod)
38 return PROCESS_Current()->exe_modref;
40 if (!HIWORD(hmod)) {
41 ERR("tried to lookup 0x%04x in win32 module handler!\n",hmod);
42 SetLastError( ERROR_INVALID_HANDLE );
43 return NULL;
45 for ( wm = PROCESS_Current()->modref_list; wm; wm=wm->next )
46 if (wm->module == hmod)
47 return wm;
48 SetLastError( ERROR_INVALID_HANDLE );
49 return NULL;
52 /*************************************************************************
53 * MODULE_AllocModRef
55 * Allocate a WINE_MODREF structure and add it to the process list
56 * NOTE: Assumes that the process critical section is held!
58 WINE_MODREF *MODULE_AllocModRef( HMODULE hModule, LPCSTR filename )
60 WINE_MODREF *wm;
61 DWORD len;
63 if ((wm = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*wm) )))
65 wm->module = hModule;
66 wm->tlsindex = -1;
68 wm->filename = HEAP_strdupA( GetProcessHeap(), 0, filename );
69 if ((wm->modname = strrchr( wm->filename, '\\' ))) wm->modname++;
70 else wm->modname = wm->filename;
72 len = GetShortPathNameA( wm->filename, NULL, 0 );
73 wm->short_filename = (char *)HeapAlloc( GetProcessHeap(), 0, len+1 );
74 GetShortPathNameA( wm->filename, wm->short_filename, len+1 );
75 if ((wm->short_modname = strrchr( wm->short_filename, '\\' ))) wm->short_modname++;
76 else wm->short_modname = wm->short_filename;
78 wm->next = PROCESS_Current()->modref_list;
79 if (wm->next) wm->next->prev = wm;
80 PROCESS_Current()->modref_list = wm;
82 return wm;
85 /*************************************************************************
86 * MODULE_InitDLL
88 static BOOL MODULE_InitDLL( WINE_MODREF *wm, DWORD type, LPVOID lpReserved )
90 BOOL retv = TRUE;
92 static LPCSTR typeName[] = { "PROCESS_DETACH", "PROCESS_ATTACH",
93 "THREAD_ATTACH", "THREAD_DETACH" };
94 assert( wm );
96 /* Skip calls for modules loaded with special load flags */
98 if (wm->flags & WINE_MODREF_DONT_RESOLVE_REFS) return TRUE;
100 TRACE("(%s,%s,%p) - CALL\n", wm->modname, typeName[type], lpReserved );
102 /* Call the initialization routine */
103 retv = PE_InitDLL( wm->module, type, lpReserved );
105 /* The state of the module list may have changed due to the call
106 to PE_InitDLL. We cannot assume that this module has not been
107 deleted. */
108 TRACE("(%p,%s,%p) - RETURN %d\n", wm, typeName[type], lpReserved, retv );
110 return retv;
113 /*************************************************************************
114 * MODULE_DllProcessAttach
116 * Send the process attach notification to all DLLs the given module
117 * depends on (recursively). This is somewhat complicated due to the fact that
119 * - we have to respect the module dependencies, i.e. modules implicitly
120 * referenced by another module have to be initialized before the module
121 * itself can be initialized
123 * - the initialization routine of a DLL can itself call LoadLibrary,
124 * thereby introducing a whole new set of dependencies (even involving
125 * the 'old' modules) at any time during the whole process
127 * (Note that this routine can be recursively entered not only directly
128 * from itself, but also via LoadLibrary from one of the called initialization
129 * routines.)
131 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
132 * the process *detach* notifications to be sent in the correct order.
133 * This must not only take into account module dependencies, but also
134 * 'hidden' dependencies created by modules calling LoadLibrary in their
135 * attach notification routine.
137 * The strategy is rather simple: we move a WINE_MODREF to the head of the
138 * list after the attach notification has returned. This implies that the
139 * detach notifications are called in the reverse of the sequence the attach
140 * notifications *returned*.
142 * NOTE: Assumes that the process critical section is held!
145 BOOL MODULE_DllProcessAttach( WINE_MODREF *wm, LPVOID lpReserved )
147 BOOL retv = TRUE;
148 int i;
149 assert( wm );
151 /* prevent infinite recursion in case of cyclical dependencies */
152 if ( ( wm->flags & WINE_MODREF_MARKER )
153 || ( wm->flags & WINE_MODREF_PROCESS_ATTACHED ) )
154 return retv;
156 TRACE("(%s,%p) - START\n", wm->modname, lpReserved );
158 /* Tag current MODREF to prevent recursive loop */
159 wm->flags |= WINE_MODREF_MARKER;
161 /* Recursively attach all DLLs this one depends on */
162 for ( i = 0; retv && i < wm->nDeps; i++ )
163 if ( wm->deps[i] )
164 retv = MODULE_DllProcessAttach( wm->deps[i], lpReserved );
166 /* Call DLL entry point */
167 if ( retv )
169 retv = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
170 if ( retv )
171 wm->flags |= WINE_MODREF_PROCESS_ATTACHED;
174 /* Re-insert MODREF at head of list */
175 if ( retv && wm->prev )
177 wm->prev->next = wm->next;
178 if ( wm->next ) wm->next->prev = wm->prev;
180 wm->prev = NULL;
181 wm->next = PROCESS_Current()->modref_list;
182 PROCESS_Current()->modref_list = wm->next->prev = wm;
185 /* Remove recursion flag */
186 wm->flags &= ~WINE_MODREF_MARKER;
188 TRACE("(%s,%p) - END\n", wm->modname, lpReserved );
190 return retv;
193 /*************************************************************************
194 * MODULE_DllProcessDetach
196 * Send DLL process detach notifications. See the comment about calling
197 * sequence at MODULE_DllProcessAttach. Unless the bForceDetach flag
198 * is set, only DLLs with zero refcount are notified.
200 void MODULE_DllProcessDetach( BOOL bForceDetach, LPVOID lpReserved )
202 WINE_MODREF *wm;
204 EnterCriticalSection( &PROCESS_Current()->crit_section );
208 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
210 /* Check whether to detach this DLL */
211 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
212 continue;
213 if ( wm->refCount > 0 && !bForceDetach )
214 continue;
216 /* Call detach notification */
217 wm->flags &= ~WINE_MODREF_PROCESS_ATTACHED;
218 MODULE_InitDLL( wm, DLL_PROCESS_DETACH, lpReserved );
220 /* Restart at head of WINE_MODREF list, as entries might have
221 been added and/or removed while performing the call ... */
222 break;
224 } while ( wm );
226 LeaveCriticalSection( &PROCESS_Current()->crit_section );
229 /*************************************************************************
230 * MODULE_DllThreadAttach
232 * Send DLL thread attach notifications. These are sent in the
233 * reverse sequence of process detach notification.
236 void MODULE_DllThreadAttach( LPVOID lpReserved )
238 WINE_MODREF *wm;
240 EnterCriticalSection( &PROCESS_Current()->crit_section );
242 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
243 if ( !wm->next )
244 break;
246 for ( ; wm; wm = wm->prev )
248 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
249 continue;
250 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
251 continue;
253 MODULE_InitDLL( wm, DLL_THREAD_ATTACH, lpReserved );
256 LeaveCriticalSection( &PROCESS_Current()->crit_section );
259 /*************************************************************************
260 * MODULE_DllThreadDetach
262 * Send DLL thread detach notifications. These are sent in the
263 * same sequence as process detach notification.
266 void MODULE_DllThreadDetach( LPVOID lpReserved )
268 WINE_MODREF *wm;
270 EnterCriticalSection( &PROCESS_Current()->crit_section );
272 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
274 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
275 continue;
276 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
277 continue;
279 MODULE_InitDLL( wm, DLL_THREAD_DETACH, lpReserved );
282 LeaveCriticalSection( &PROCESS_Current()->crit_section );
285 /****************************************************************************
286 * DisableThreadLibraryCalls (KERNEL32.74)
288 * Don't call DllEntryPoint for DLL_THREAD_{ATTACH,DETACH} if set.
290 BOOL WINAPI DisableThreadLibraryCalls( HMODULE hModule )
292 WINE_MODREF *wm;
293 BOOL retval = TRUE;
295 EnterCriticalSection( &PROCESS_Current()->crit_section );
297 wm = MODULE32_LookupHMODULE( hModule );
298 if ( !wm )
299 retval = FALSE;
300 else
301 wm->flags |= WINE_MODREF_NO_DLL_CALLS;
303 LeaveCriticalSection( &PROCESS_Current()->crit_section );
305 return retval;
309 /***********************************************************************
310 * MODULE_CreateDummyModule
312 * Create a dummy NE module for Win32 or Winelib.
314 HMODULE MODULE_CreateDummyModule( LPCSTR filename, HMODULE module32 )
316 HMODULE hModule;
317 NE_MODULE *pModule;
318 SEGTABLEENTRY *pSegment;
319 char *pStr,*s;
320 unsigned int len;
321 const char* basename;
322 OFSTRUCT *ofs;
323 int of_size, size;
325 /* Extract base filename */
326 basename = strrchr(filename, '\\');
327 if (!basename) basename = filename;
328 else basename++;
329 len = strlen(basename);
330 if ((s = strchr(basename, '.'))) len = s - basename;
332 /* Allocate module */
333 of_size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName)
334 + strlen(filename) + 1;
335 size = sizeof(NE_MODULE) +
336 /* loaded file info */
337 of_size +
338 /* segment table: DS,CS */
339 2 * sizeof(SEGTABLEENTRY) +
340 /* name table */
341 len + 2 +
342 /* several empty tables */
345 hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
346 if (!hModule) return (HMODULE)11; /* invalid exe */
348 FarSetOwner16( hModule, hModule );
349 pModule = (NE_MODULE *)GlobalLock16( hModule );
351 /* Set all used entries */
352 pModule->magic = IMAGE_OS2_SIGNATURE;
353 pModule->count = 1;
354 pModule->next = 0;
355 pModule->flags = 0;
356 pModule->dgroup = 0;
357 pModule->ss = 1;
358 pModule->cs = 2;
359 pModule->heap_size = 0;
360 pModule->stack_size = 0;
361 pModule->seg_count = 2;
362 pModule->modref_count = 0;
363 pModule->nrname_size = 0;
364 pModule->fileinfo = sizeof(NE_MODULE);
365 pModule->os_flags = NE_OSFLAGS_WINDOWS;
366 pModule->self = hModule;
367 pModule->module32 = module32;
369 /* Set version and flags */
370 if (module32)
372 pModule->expected_version =
373 ((PE_HEADER(module32)->OptionalHeader.MajorSubsystemVersion & 0xff) << 8 ) |
374 (PE_HEADER(module32)->OptionalHeader.MinorSubsystemVersion & 0xff);
375 pModule->flags |= NE_FFLAGS_WIN32;
376 if (PE_HEADER(module32)->FileHeader.Characteristics & IMAGE_FILE_DLL)
377 pModule->flags |= NE_FFLAGS_LIBMODULE | NE_FFLAGS_SINGLEDATA;
380 /* Set loaded file information */
381 ofs = (OFSTRUCT *)(pModule + 1);
382 memset( ofs, 0, of_size );
383 ofs->cBytes = of_size < 256 ? of_size : 255; /* FIXME */
384 strcpy( ofs->szPathName, filename );
386 pSegment = (SEGTABLEENTRY*)((char*)(pModule + 1) + of_size);
387 pModule->seg_table = (int)pSegment - (int)pModule;
388 /* Data segment */
389 pSegment->size = 0;
390 pSegment->flags = NE_SEGFLAGS_DATA;
391 pSegment->minsize = 0x1000;
392 pSegment++;
393 /* Code segment */
394 pSegment->flags = 0;
395 pSegment++;
397 /* Module name */
398 pStr = (char *)pSegment;
399 pModule->name_table = (int)pStr - (int)pModule;
400 assert(len<256);
401 *pStr = len;
402 lstrcpynA( pStr+1, basename, len+1 );
403 pStr += len+2;
405 /* All tables zero terminated */
406 pModule->res_table = pModule->import_table = pModule->entry_table =
407 (int)pStr - (int)pModule;
409 NE_RegisterModule( pModule );
410 return hModule;
414 /**********************************************************************
415 * MODULE_FindModule
417 * Find a (loaded) win32 module depending on path
419 * RETURNS
420 * the module handle if found
421 * 0 if not
423 WINE_MODREF *MODULE_FindModule(
424 LPCSTR path /* [in] pathname of module/library to be found */
426 WINE_MODREF *wm;
427 char dllname[260], *p;
429 /* Append .DLL to name if no extension present */
430 strcpy( dllname, path );
431 if (!(p = strrchr( dllname, '.')) || strchr( p, '/' ) || strchr( p, '\\'))
432 strcat( dllname, ".DLL" );
434 for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
436 if ( !strcasecmp( dllname, wm->modname ) )
437 break;
438 if ( !strcasecmp( dllname, wm->filename ) )
439 break;
440 if ( !strcasecmp( dllname, wm->short_modname ) )
441 break;
442 if ( !strcasecmp( dllname, wm->short_filename ) )
443 break;
446 return wm;
450 /* Check whether a file is an OS/2 or a very old Windows executable
451 * by testing on import of KERNEL.
453 * FIXME: is reading the module imports the only way of discerning
454 * old Windows binaries from OS/2 ones ? At least it seems so...
456 static DWORD MODULE_Decide_OS2_OldWin(HANDLE hfile, IMAGE_DOS_HEADER *mz, IMAGE_OS2_HEADER *ne)
458 DWORD currpos = SetFilePointer( hfile, 0, NULL, SEEK_CUR);
459 DWORD type = SCS_OS216_BINARY;
460 LPWORD modtab = NULL;
461 LPSTR nametab = NULL;
462 DWORD len;
463 int i;
465 /* read modref table */
466 if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_modtab, NULL, SEEK_SET ) == -1)
467 || (!(modtab = HeapAlloc( GetProcessHeap(), 0, ne->ne_cmod*sizeof(WORD))))
468 || (!(ReadFile(hfile, modtab, ne->ne_cmod*sizeof(WORD), &len, NULL)))
469 || (len != ne->ne_cmod*sizeof(WORD)) )
470 goto broken;
472 /* read imported names table */
473 if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_imptab, NULL, SEEK_SET ) == -1)
474 || (!(nametab = HeapAlloc( GetProcessHeap(), 0, ne->ne_enttab - ne->ne_imptab)))
475 || (!(ReadFile(hfile, nametab, ne->ne_enttab - ne->ne_imptab, &len, NULL)))
476 || (len != ne->ne_enttab - ne->ne_imptab) )
477 goto broken;
479 for (i=0; i < ne->ne_cmod; i++)
481 LPSTR module = &nametab[modtab[i]];
482 TRACE("modref: %.*s\n", module[0], &module[1]);
483 if (!(strncmp(&module[1], "KERNEL", module[0])))
484 { /* very old Windows file */
485 MESSAGE("This seems to be a very old (pre-3.0) Windows executable. Expect crashes, especially if this is a real-mode binary !\n");
486 type = SCS_WOW_BINARY;
487 goto good;
491 broken:
492 ERR("Hmm, an error occurred. Is this binary file broken ?\n");
494 good:
495 HeapFree( GetProcessHeap(), 0, modtab);
496 HeapFree( GetProcessHeap(), 0, nametab);
497 SetFilePointer( hfile, currpos, NULL, SEEK_SET); /* restore filepos */
498 return type;
501 /***********************************************************************
502 * MODULE_GetBinaryType
504 * The GetBinaryType function determines whether a file is executable
505 * or not and if it is it returns what type of executable it is.
506 * The type of executable is a property that determines in which
507 * subsystem an executable file runs under.
509 * Binary types returned:
510 * SCS_32BIT_BINARY: A Win32 based application
511 * SCS_DOS_BINARY: An MS-Dos based application
512 * SCS_WOW_BINARY: A Win16 based application
513 * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
514 * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
515 * SCS_OS216_BINARY: A 16bit OS/2 based application
517 * Returns TRUE if the file is an executable in which case
518 * the value pointed by lpBinaryType is set.
519 * Returns FALSE if the file is not an executable or if the function fails.
521 * To do so it opens the file and reads in the header information
522 * if the extended header information is not present it will
523 * assume that the file is a DOS executable.
524 * If the extended header information is present it will
525 * determine if the file is a 16 or 32 bit Windows executable
526 * by check the flags in the header.
528 * Note that .COM and .PIF files are only recognized by their
529 * file name extension; but Windows does it the same way ...
531 static BOOL MODULE_GetBinaryType( HANDLE hfile, LPCSTR filename, LPDWORD lpBinaryType )
533 IMAGE_DOS_HEADER mz_header;
534 char magic[4], *ptr;
535 DWORD len;
537 /* Seek to the start of the file and read the DOS header information.
539 if ( SetFilePointer( hfile, 0, NULL, SEEK_SET ) != -1
540 && ReadFile( hfile, &mz_header, sizeof(mz_header), &len, NULL )
541 && len == sizeof(mz_header) )
543 /* Now that we have the header check the e_magic field
544 * to see if this is a dos image.
546 if ( mz_header.e_magic == IMAGE_DOS_SIGNATURE )
548 BOOL lfanewValid = FALSE;
549 /* We do have a DOS image so we will now try to seek into
550 * the file by the amount indicated by the field
551 * "Offset to extended header" and read in the
552 * "magic" field information at that location.
553 * This will tell us if there is more header information
554 * to read or not.
556 /* But before we do we will make sure that header
557 * structure encompasses the "Offset to extended header"
558 * field.
560 if ( (mz_header.e_cparhdr<<4) >= sizeof(IMAGE_DOS_HEADER) )
561 if ( ( mz_header.e_crlc == 0 ) ||
562 ( mz_header.e_lfarlc >= sizeof(IMAGE_DOS_HEADER) ) )
563 if ( mz_header.e_lfanew >= sizeof(IMAGE_DOS_HEADER)
564 && SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET ) != -1
565 && ReadFile( hfile, magic, sizeof(magic), &len, NULL )
566 && len == sizeof(magic) )
567 lfanewValid = TRUE;
569 if ( !lfanewValid )
571 /* If we cannot read this "extended header" we will
572 * assume that we have a simple DOS executable.
574 *lpBinaryType = SCS_DOS_BINARY;
575 return TRUE;
577 else
579 /* Reading the magic field succeeded so
580 * we will try to determine what type it is.
582 if ( *(DWORD*)magic == IMAGE_NT_SIGNATURE )
584 /* This is an NT signature.
586 *lpBinaryType = SCS_32BIT_BINARY;
587 return TRUE;
589 else if ( *(WORD*)magic == IMAGE_OS2_SIGNATURE )
591 /* The IMAGE_OS2_SIGNATURE indicates that the
592 * "extended header is a Windows executable (NE)
593 * header." This can mean either a 16-bit OS/2
594 * or a 16-bit Windows or even a DOS program
595 * (running under a DOS extender). To decide
596 * which, we'll have to read the NE header.
599 IMAGE_OS2_HEADER ne;
600 if ( SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET ) != -1
601 && ReadFile( hfile, &ne, sizeof(ne), &len, NULL )
602 && len == sizeof(ne) )
604 switch ( ne.ne_exetyp )
606 case 2: *lpBinaryType = SCS_WOW_BINARY; return TRUE;
607 case 5: *lpBinaryType = SCS_DOS_BINARY; return TRUE;
608 default: *lpBinaryType =
609 MODULE_Decide_OS2_OldWin(hfile, &mz_header, &ne);
610 return TRUE;
613 /* Couldn't read header, so abort. */
614 return FALSE;
616 else
618 /* Unknown extended header, but this file is nonetheless
619 DOS-executable.
621 *lpBinaryType = SCS_DOS_BINARY;
622 return TRUE;
628 /* If we get here, we don't even have a correct MZ header.
629 * Try to check the file extension for known types ...
631 ptr = strrchr( filename, '.' );
632 if ( ptr && !strchr( ptr, '\\' ) && !strchr( ptr, '/' ) )
634 if ( !strcasecmp( ptr, ".COM" ) )
636 *lpBinaryType = SCS_DOS_BINARY;
637 return TRUE;
640 if ( !strcasecmp( ptr, ".PIF" ) )
642 *lpBinaryType = SCS_PIF_BINARY;
643 return TRUE;
647 return FALSE;
650 /***********************************************************************
651 * GetBinaryTypeA [KERNEL32.280]
653 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
655 BOOL ret = FALSE;
656 HANDLE hfile;
658 TRACE_(win32)("%s\n", lpApplicationName );
660 /* Sanity check.
662 if ( lpApplicationName == NULL || lpBinaryType == NULL )
663 return FALSE;
665 /* Open the file indicated by lpApplicationName for reading.
667 hfile = CreateFileA( lpApplicationName, GENERIC_READ, FILE_SHARE_READ,
668 NULL, OPEN_EXISTING, 0, -1 );
669 if ( hfile == INVALID_HANDLE_VALUE )
670 return FALSE;
672 /* Check binary type
674 ret = MODULE_GetBinaryType( hfile, lpApplicationName, lpBinaryType );
676 /* Close the file.
678 CloseHandle( hfile );
680 return ret;
683 /***********************************************************************
684 * GetBinaryTypeW [KERNEL32.281]
686 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
688 BOOL ret = FALSE;
689 LPSTR strNew = NULL;
691 TRACE_(win32)("%s\n", debugstr_w(lpApplicationName) );
693 /* Sanity check.
695 if ( lpApplicationName == NULL || lpBinaryType == NULL )
696 return FALSE;
698 /* Convert the wide string to a ascii string.
700 strNew = HEAP_strdupWtoA( GetProcessHeap(), 0, lpApplicationName );
702 if ( strNew != NULL )
704 ret = GetBinaryTypeA( strNew, lpBinaryType );
706 /* Free the allocated string.
708 HeapFree( GetProcessHeap(), 0, strNew );
711 return ret;
715 /***********************************************************************
716 * WinExec16 (KERNEL.166)
718 HINSTANCE16 WINAPI WinExec16( LPCSTR lpCmdLine, UINT16 nCmdShow )
720 LPCSTR p, args = NULL;
721 LPCSTR name_beg, name_end;
722 LPSTR name, cmdline;
723 int arglen;
724 HINSTANCE16 ret;
725 char buffer[MAX_PATH];
727 if (*lpCmdLine == '"') /* has to be only one and only at beginning ! */
729 name_beg = lpCmdLine+1;
730 p = strchr ( lpCmdLine+1, '"' );
731 if (p)
733 name_end = p;
734 args = strchr ( p, ' ' );
736 else /* yes, even valid with trailing '"' missing */
737 name_end = lpCmdLine+strlen(lpCmdLine);
739 else
741 name_beg = lpCmdLine;
742 args = strchr( lpCmdLine, ' ' );
743 name_end = args ? args : lpCmdLine+strlen(lpCmdLine);
746 if ((name_beg == lpCmdLine) && (!args))
747 { /* just use the original cmdline string as file name */
748 name = (LPSTR)lpCmdLine;
750 else
752 if (!(name = HeapAlloc( GetProcessHeap(), 0, name_end - name_beg + 1 )))
753 return ERROR_NOT_ENOUGH_MEMORY;
754 memcpy( name, name_beg, name_end - name_beg );
755 name[name_end - name_beg] = '\0';
758 if (args)
760 args++;
761 arglen = strlen(args);
762 cmdline = SEGPTR_ALLOC( 2 + arglen );
763 cmdline[0] = (BYTE)arglen;
764 strcpy( cmdline + 1, args );
766 else
768 cmdline = SEGPTR_ALLOC( 2 );
769 cmdline[0] = cmdline[1] = 0;
772 TRACE("name: '%s', cmdline: '%.*s'\n", name, cmdline[0], &cmdline[1]);
774 if (SearchPathA( NULL, name, ".exe", sizeof(buffer), buffer, NULL ))
776 LOADPARAMS16 params;
777 WORD *showCmd = SEGPTR_ALLOC( 2*sizeof(WORD) );
778 showCmd[0] = 2;
779 showCmd[1] = nCmdShow;
781 params.hEnvironment = 0;
782 params.cmdLine = SEGPTR_GET(cmdline);
783 params.showCmd = SEGPTR_GET(showCmd);
784 params.reserved = 0;
786 ret = LoadModule16( buffer, &params );
788 SEGPTR_FREE( showCmd );
789 SEGPTR_FREE( cmdline );
791 else ret = GetLastError();
793 if (name != lpCmdLine) HeapFree( GetProcessHeap(), 0, name );
795 if (ret == 21) /* 32-bit module */
797 DWORD count;
798 ReleaseThunkLock( &count );
799 ret = WinExec( lpCmdLine, nCmdShow );
800 RestoreThunkLock( count );
802 return ret;
805 /***********************************************************************
806 * WinExec (KERNEL32.566)
808 HINSTANCE WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
810 PROCESS_INFORMATION info;
811 STARTUPINFOA startup;
812 HINSTANCE hInstance;
813 char *cmdline;
815 memset( &startup, 0, sizeof(startup) );
816 startup.cb = sizeof(startup);
817 startup.dwFlags = STARTF_USESHOWWINDOW;
818 startup.wShowWindow = nCmdShow;
820 /* cmdline needs to be writeable for CreateProcess */
821 if (!(cmdline = HEAP_strdupA( GetProcessHeap(), 0, lpCmdLine ))) return 0;
823 if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
824 0, NULL, NULL, &startup, &info ))
826 /* Give 30 seconds to the app to come up */
827 if (Callout.WaitForInputIdle &&
828 Callout.WaitForInputIdle( info.hProcess, 30000 ) == 0xFFFFFFFF)
829 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
830 hInstance = 33;
831 /* Close off the handles */
832 CloseHandle( info.hThread );
833 CloseHandle( info.hProcess );
835 else if ((hInstance = GetLastError()) >= 32)
837 FIXME("Strange error set by CreateProcess: %d\n", hInstance );
838 hInstance = 11;
840 HeapFree( GetProcessHeap(), 0, cmdline );
841 return hInstance;
844 /**********************************************************************
845 * LoadModule (KERNEL32.499)
847 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock )
849 LOADPARAMS *params = (LOADPARAMS *)paramBlock;
850 PROCESS_INFORMATION info;
851 STARTUPINFOA startup;
852 HINSTANCE hInstance;
853 LPSTR cmdline, p;
854 char filename[MAX_PATH];
855 BYTE len;
857 if (!name) return ERROR_FILE_NOT_FOUND;
859 if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
860 !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
861 return GetLastError();
863 len = (BYTE)params->lpCmdLine[0];
864 if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
865 return ERROR_NOT_ENOUGH_MEMORY;
867 strcpy( cmdline, filename );
868 p = cmdline + strlen(cmdline);
869 *p++ = ' ';
870 memcpy( p, params->lpCmdLine + 1, len );
871 p[len] = 0;
873 memset( &startup, 0, sizeof(startup) );
874 startup.cb = sizeof(startup);
875 if (params->lpCmdShow)
877 startup.dwFlags = STARTF_USESHOWWINDOW;
878 startup.wShowWindow = params->lpCmdShow[1];
881 if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
882 params->lpEnvAddress, NULL, &startup, &info ))
884 /* Give 30 seconds to the app to come up */
885 if (Callout.WaitForInputIdle &&
886 Callout.WaitForInputIdle( info.hProcess, 30000 ) == 0xFFFFFFFF )
887 WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
888 hInstance = 33;
889 /* Close off the handles */
890 CloseHandle( info.hThread );
891 CloseHandle( info.hProcess );
893 else if ((hInstance = GetLastError()) >= 32)
895 FIXME("Strange error set by CreateProcess: %d\n", hInstance );
896 hInstance = 11;
899 HeapFree( GetProcessHeap(), 0, cmdline );
900 return hInstance;
904 /*************************************************************************
905 * get_file_name
907 * Helper for CreateProcess: retrieve the file name to load from the
908 * app name and command line. Store the file name in buffer, and
909 * return a possibly modified command line.
911 static LPSTR get_file_name( LPCSTR appname, LPSTR cmdline, LPSTR buffer, int buflen )
913 char *name, *pos, *ret = NULL;
914 const char *p;
916 /* if we have an app name, everything is easy */
918 if (appname)
920 /* use the unmodified app name as file name */
921 lstrcpynA( buffer, appname, buflen );
922 if (!(ret = cmdline))
924 /* no command-line, create one */
925 if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(appname) + 3 )))
926 sprintf( ret, "\"%s\"", appname );
928 return ret;
931 if (!cmdline)
933 SetLastError( ERROR_INVALID_PARAMETER );
934 return NULL;
937 /* first check for a quoted file name */
939 if ((cmdline[0] == '"') && ((p = strchr( cmdline + 1, '"' ))))
941 int len = p - cmdline - 1;
942 /* extract the quoted portion as file name */
943 if (!(name = HeapAlloc( GetProcessHeap(), 0, len + 1 ))) return NULL;
944 memcpy( name, cmdline + 1, len );
945 name[len] = 0;
947 if (SearchPathA( NULL, name, ".exe", buflen, buffer, NULL ) ||
948 SearchPathA( NULL, name, NULL, buflen, buffer, NULL ))
949 ret = cmdline; /* no change necessary */
950 goto done;
953 /* now try the command-line word by word */
955 if (!(name = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 1 ))) return NULL;
956 pos = name;
957 p = cmdline;
959 while (*p)
961 do *pos++ = *p++; while (*p && *p != ' ');
962 *pos = 0;
963 TRACE("trying '%s'\n", name );
964 if (SearchPathA( NULL, name, ".exe", buflen, buffer, NULL ) ||
965 SearchPathA( NULL, name, NULL, buflen, buffer, NULL ))
967 ret = cmdline;
968 break;
972 if (!ret || !strchr( name, ' ' )) goto done; /* no change necessary */
974 /* now build a new command-line with quotes */
976 if (!(ret = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 3 ))) goto done;
977 sprintf( ret, "\"%s\"%s", name, p );
979 done:
980 HeapFree( GetProcessHeap(), 0, name );
981 return ret;
985 /**********************************************************************
986 * CreateProcessA (KERNEL32.171)
988 BOOL WINAPI CreateProcessA( LPCSTR lpApplicationName, LPSTR lpCommandLine,
989 LPSECURITY_ATTRIBUTES lpProcessAttributes,
990 LPSECURITY_ATTRIBUTES lpThreadAttributes,
991 BOOL bInheritHandles, DWORD dwCreationFlags,
992 LPVOID lpEnvironment, LPCSTR lpCurrentDirectory,
993 LPSTARTUPINFOA lpStartupInfo,
994 LPPROCESS_INFORMATION lpProcessInfo )
996 BOOL retv = FALSE;
997 HANDLE hFile;
998 DWORD type;
999 char name[MAX_PATH];
1000 LPSTR tidy_cmdline;
1002 /* Process the AppName and/or CmdLine to get module name and path */
1004 TRACE("app '%s' cmdline '%s'\n", lpApplicationName, lpCommandLine );
1006 if (!(tidy_cmdline = get_file_name( lpApplicationName, lpCommandLine, name, sizeof(name) )))
1007 return FALSE;
1009 /* Warn if unsupported features are used */
1011 if (dwCreationFlags & DETACHED_PROCESS)
1012 FIXME("(%s,...): DETACHED_PROCESS ignored\n", name);
1013 if (dwCreationFlags & CREATE_NEW_CONSOLE)
1014 FIXME("(%s,...): CREATE_NEW_CONSOLE ignored\n", name);
1015 if (dwCreationFlags & NORMAL_PRIORITY_CLASS)
1016 FIXME("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
1017 if (dwCreationFlags & IDLE_PRIORITY_CLASS)
1018 FIXME("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
1019 if (dwCreationFlags & HIGH_PRIORITY_CLASS)
1020 FIXME("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
1021 if (dwCreationFlags & REALTIME_PRIORITY_CLASS)
1022 FIXME("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
1023 if (dwCreationFlags & CREATE_NEW_PROCESS_GROUP)
1024 FIXME("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
1025 if (dwCreationFlags & CREATE_UNICODE_ENVIRONMENT)
1026 FIXME("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
1027 if (dwCreationFlags & CREATE_SEPARATE_WOW_VDM)
1028 FIXME("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
1029 if (dwCreationFlags & CREATE_SHARED_WOW_VDM)
1030 FIXME("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
1031 if (dwCreationFlags & CREATE_DEFAULT_ERROR_MODE)
1032 FIXME("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
1033 if (dwCreationFlags & CREATE_NO_WINDOW)
1034 FIXME("(%s,...): CREATE_NO_WINDOW ignored\n", name);
1035 if (dwCreationFlags & PROFILE_USER)
1036 FIXME("(%s,...): PROFILE_USER ignored\n", name);
1037 if (dwCreationFlags & PROFILE_KERNEL)
1038 FIXME("(%s,...): PROFILE_KERNEL ignored\n", name);
1039 if (dwCreationFlags & PROFILE_SERVER)
1040 FIXME("(%s,...): PROFILE_SERVER ignored\n", name);
1041 if (lpStartupInfo->lpDesktop)
1042 FIXME("(%s,...): lpStartupInfo->lpDesktop %s ignored\n",
1043 name, lpStartupInfo->lpDesktop);
1044 if (lpStartupInfo->lpTitle)
1045 FIXME("(%s,...): lpStartupInfo->lpTitle %s ignored\n",
1046 name, lpStartupInfo->lpTitle);
1047 if (lpStartupInfo->dwFlags & STARTF_USECOUNTCHARS)
1048 FIXME("(%s,...): STARTF_USECOUNTCHARS (%ld,%ld) ignored\n",
1049 name, lpStartupInfo->dwXCountChars, lpStartupInfo->dwYCountChars);
1050 if (lpStartupInfo->dwFlags & STARTF_USEFILLATTRIBUTE)
1051 FIXME("(%s,...): STARTF_USEFILLATTRIBUTE %lx ignored\n",
1052 name, lpStartupInfo->dwFillAttribute);
1053 if (lpStartupInfo->dwFlags & STARTF_RUNFULLSCREEN)
1054 FIXME("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
1055 if (lpStartupInfo->dwFlags & STARTF_FORCEONFEEDBACK)
1056 FIXME("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
1057 if (lpStartupInfo->dwFlags & STARTF_FORCEOFFFEEDBACK)
1058 FIXME("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
1059 if (lpStartupInfo->dwFlags & STARTF_USEHOTKEY)
1060 FIXME("(%s,...): STARTF_USEHOTKEY ignored\n", name);
1062 /* Open file and determine executable type */
1064 hFile = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, -1 );
1065 if (hFile == INVALID_HANDLE_VALUE) goto done;
1067 if ( !MODULE_GetBinaryType( hFile, name, &type ) )
1069 CloseHandle( hFile );
1070 retv = PROCESS_Create( -1, name, tidy_cmdline, lpEnvironment,
1071 lpProcessAttributes, lpThreadAttributes,
1072 bInheritHandles, dwCreationFlags,
1073 lpStartupInfo, lpProcessInfo, lpCurrentDirectory );
1074 goto done;
1077 /* Create process */
1079 switch ( type )
1081 case SCS_32BIT_BINARY:
1082 case SCS_WOW_BINARY:
1083 case SCS_DOS_BINARY:
1084 retv = PROCESS_Create( hFile, name, tidy_cmdline, lpEnvironment,
1085 lpProcessAttributes, lpThreadAttributes,
1086 bInheritHandles, dwCreationFlags,
1087 lpStartupInfo, lpProcessInfo, lpCurrentDirectory);
1088 break;
1090 case SCS_PIF_BINARY:
1091 case SCS_POSIX_BINARY:
1092 case SCS_OS216_BINARY:
1093 FIXME("Unsupported executable type: %ld\n", type );
1094 /* fall through */
1096 default:
1097 SetLastError( ERROR_BAD_FORMAT );
1098 break;
1100 CloseHandle( hFile );
1102 done:
1103 if (tidy_cmdline != lpCommandLine) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1104 return retv;
1107 /**********************************************************************
1108 * CreateProcessW (KERNEL32.172)
1109 * NOTES
1110 * lpReserved is not converted
1112 BOOL WINAPI CreateProcessW( LPCWSTR lpApplicationName, LPWSTR lpCommandLine,
1113 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1114 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1115 BOOL bInheritHandles, DWORD dwCreationFlags,
1116 LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory,
1117 LPSTARTUPINFOW lpStartupInfo,
1118 LPPROCESS_INFORMATION lpProcessInfo )
1119 { BOOL ret;
1120 STARTUPINFOA StartupInfoA;
1122 LPSTR lpApplicationNameA = HEAP_strdupWtoA (GetProcessHeap(),0,lpApplicationName);
1123 LPSTR lpCommandLineA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCommandLine);
1124 LPSTR lpCurrentDirectoryA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCurrentDirectory);
1126 memcpy (&StartupInfoA, lpStartupInfo, sizeof(STARTUPINFOA));
1127 StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpDesktop);
1128 StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpTitle);
1130 TRACE_(win32)("(%s,%s,...)\n", debugstr_w(lpApplicationName), debugstr_w(lpCommandLine));
1132 if (lpStartupInfo->lpReserved)
1133 FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n", debugstr_w(lpStartupInfo->lpReserved));
1135 ret = CreateProcessA( lpApplicationNameA, lpCommandLineA,
1136 lpProcessAttributes, lpThreadAttributes,
1137 bInheritHandles, dwCreationFlags,
1138 lpEnvironment, lpCurrentDirectoryA,
1139 &StartupInfoA, lpProcessInfo );
1141 HeapFree( GetProcessHeap(), 0, lpCurrentDirectoryA );
1142 HeapFree( GetProcessHeap(), 0, lpCommandLineA );
1143 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1144 HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1146 return ret;
1149 /***********************************************************************
1150 * GetModuleHandleA (KERNEL32.237)
1152 HMODULE WINAPI GetModuleHandleA(LPCSTR module)
1154 WINE_MODREF *wm;
1156 if ( module == NULL )
1157 wm = PROCESS_Current()->exe_modref;
1158 else
1159 wm = MODULE_FindModule( module );
1161 return wm? wm->module : 0;
1164 /***********************************************************************
1165 * GetModuleHandleW
1167 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
1169 HMODULE hModule;
1170 LPSTR modulea = HEAP_strdupWtoA( GetProcessHeap(), 0, module );
1171 hModule = GetModuleHandleA( modulea );
1172 HeapFree( GetProcessHeap(), 0, modulea );
1173 return hModule;
1177 /***********************************************************************
1178 * GetModuleFileNameA (KERNEL32.235)
1180 * GetModuleFileNameA seems to *always* return the long path;
1181 * it's only GetModuleFileName16 that decides between short/long path
1182 * by checking if exe version >= 4.0.
1183 * (SDK docu doesn't mention this)
1185 DWORD WINAPI GetModuleFileNameA(
1186 HMODULE hModule, /* [in] module handle (32bit) */
1187 LPSTR lpFileName, /* [out] filenamebuffer */
1188 DWORD size ) /* [in] size of filenamebuffer */
1190 WINE_MODREF *wm;
1192 EnterCriticalSection( &PROCESS_Current()->crit_section );
1194 lpFileName[0] = 0;
1195 if ((wm = MODULE32_LookupHMODULE( hModule )))
1196 lstrcpynA( lpFileName, wm->filename, size );
1198 LeaveCriticalSection( &PROCESS_Current()->crit_section );
1199 TRACE("%s\n", lpFileName );
1200 return strlen(lpFileName);
1204 /***********************************************************************
1205 * GetModuleFileNameW (KERNEL32.236)
1207 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName,
1208 DWORD size )
1210 LPSTR fnA = (char*)HeapAlloc( GetProcessHeap(), 0, size );
1211 DWORD res = GetModuleFileNameA( hModule, fnA, size );
1212 if (size > 0 && !MultiByteToWideChar( CP_ACP, 0, fnA, -1, lpFileName, size ))
1213 lpFileName[size-1] = 0;
1214 HeapFree( GetProcessHeap(), 0, fnA );
1215 return res;
1219 /***********************************************************************
1220 * LoadLibraryExA (KERNEL32)
1222 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
1224 WINE_MODREF *wm;
1226 if(!libname)
1228 SetLastError(ERROR_INVALID_PARAMETER);
1229 return 0;
1232 if (flags & LOAD_LIBRARY_AS_DATAFILE)
1234 char filename[256];
1235 HFILE hFile;
1236 HMODULE hmod = 0;
1238 if (!SearchPathA( NULL, libname, ".dll", sizeof(filename), filename, NULL ))
1239 return 0;
1240 /* FIXME: maybe we should use the hfile parameter instead */
1241 hFile = CreateFileA( filename, GENERIC_READ, FILE_SHARE_READ,
1242 NULL, OPEN_EXISTING, 0, -1 );
1243 if (hFile != INVALID_HANDLE_VALUE)
1245 hmod = PE_LoadImage( hFile, filename, flags );
1246 CloseHandle( hFile );
1248 return hmod;
1251 EnterCriticalSection(&PROCESS_Current()->crit_section);
1253 wm = MODULE_LoadLibraryExA( libname, hfile, flags );
1254 if ( wm )
1256 if ( !MODULE_DllProcessAttach( wm, NULL ) )
1258 WARN_(module)("Attach failed for module '%s', \n", libname);
1259 MODULE_FreeLibrary(wm);
1260 SetLastError(ERROR_DLL_INIT_FAILED);
1261 wm = NULL;
1265 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1267 return wm ? wm->module : 0;
1270 /***********************************************************************
1271 * MODULE_LoadLibraryExA (internal)
1273 * Load a PE style module according to the load order.
1275 * The HFILE parameter is not used and marked reserved in the SDK. I can
1276 * only guess that it should force a file to be mapped, but I rather
1277 * ignore the parameter because it would be extremely difficult to
1278 * integrate this with different types of module represenations.
1281 WINE_MODREF *MODULE_LoadLibraryExA( LPCSTR libname, HFILE hfile, DWORD flags )
1283 DWORD err = GetLastError();
1284 WINE_MODREF *pwm;
1285 int i;
1286 module_loadorder_t *plo;
1287 LPSTR filename, p;
1289 if ( !libname ) return NULL;
1291 filename = HeapAlloc ( GetProcessHeap(), 0, MAX_PATH + 1 );
1292 if ( !filename ) return NULL;
1294 /* build the modules filename */
1295 if (!SearchPathA( NULL, libname, ".dll", MAX_PATH, filename, NULL ))
1297 if ( ! GetSystemDirectoryA ( filename, MAX_PATH ) )
1298 goto error;
1300 /* if the library name contains a path and can not be found, return an error.
1301 exception: if the path is the system directory, proceed, so that modules,
1302 which are not PE-modules can be loaded
1304 if the library name does not contain a path and can not be found, assume the
1305 system directory is meant */
1307 if ( ! strncasecmp ( filename, libname, strlen ( filename ) ))
1308 strcpy ( filename, libname );
1309 else
1311 if ( strchr ( libname, '\\' ) || strchr ( libname, ':') || strchr ( libname, '/' ) )
1312 goto error;
1313 else
1315 strcat ( filename, "\\" );
1316 strcat ( filename, libname );
1320 /* if the filename doesn't have an extension append .DLL */
1321 if (!(p = strrchr( filename, '.')) || strchr( p, '/' ) || strchr( p, '\\'))
1322 strcat( filename, ".DLL" );
1325 EnterCriticalSection(&PROCESS_Current()->crit_section);
1327 /* Check for already loaded module */
1328 if (!(pwm = MODULE_FindModule(filename)) &&
1329 /* no path in libpath */
1330 !strchr( libname, '\\' ) && !strchr( libname, ':') && !strchr( libname, '/' ))
1332 LPSTR fn = HeapAlloc ( GetProcessHeap(), 0, MAX_PATH + 1 );
1333 if (fn)
1335 /* since the default loading mechanism uses a more detailed algorithm
1336 * than SearchPath (like using PATH, which can even be modified between
1337 * two attempts of loading the same DLL), the look-up above (with
1338 * SearchPath) can have put the file in system directory, whereas it
1339 * has already been loaded but with a different path. So do a specific
1340 * look-up with filename (without any path)
1342 strcpy ( fn, libname );
1343 /* if the filename doesn't have an extension append .DLL */
1344 if (!strrchr( fn, '.')) strcat( fn, ".dll" );
1345 if ((pwm = MODULE_FindModule( fn )) != NULL)
1346 strcpy( filename, fn );
1347 HeapFree( GetProcessHeap(), 0, fn );
1350 if (pwm)
1352 if(!(pwm->flags & WINE_MODREF_MARKER))
1353 pwm->refCount++;
1355 if ((pwm->flags & WINE_MODREF_DONT_RESOLVE_REFS) &&
1356 !(flags & DONT_RESOLVE_DLL_REFERENCES))
1358 extern DWORD fixup_imports(WINE_MODREF *wm); /*FIXME*/
1359 pwm->flags &= ~WINE_MODREF_DONT_RESOLVE_REFS;
1360 fixup_imports( pwm );
1362 TRACE("Already loaded module '%s' at 0x%08x, count=%d, \n", filename, pwm->module, pwm->refCount);
1363 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1364 HeapFree ( GetProcessHeap(), 0, filename );
1365 return pwm;
1368 plo = MODULE_GetLoadOrder(filename, TRUE);
1370 for(i = 0; i < MODULE_LOADORDER_NTYPES; i++)
1372 SetLastError( ERROR_FILE_NOT_FOUND );
1373 switch(plo->loadorder[i])
1375 case MODULE_LOADORDER_DLL:
1376 TRACE("Trying native dll '%s'\n", filename);
1377 pwm = PE_LoadLibraryExA(filename, flags);
1378 break;
1380 case MODULE_LOADORDER_SO:
1381 TRACE("Trying so-library '%s'\n", filename);
1382 if (!(pwm = BUILTIN32_LoadLibraryExA(filename, flags)))
1383 pwm = ELF_LoadLibraryExA(filename, flags);
1384 break;
1386 case MODULE_LOADORDER_BI:
1387 TRACE("Trying built-in '%s'\n", filename);
1388 pwm = BUILTIN32_LoadLibraryExA(filename, flags);
1389 break;
1391 default:
1392 ERR("Got invalid loadorder type %d (%s index %d)\n", plo->loadorder[i], plo->modulename, i);
1393 /* Fall through */
1395 case MODULE_LOADORDER_INVALID: /* We ignore this as it is an empty entry */
1396 pwm = NULL;
1397 break;
1400 if(pwm)
1402 /* Initialize DLL just loaded */
1403 TRACE("Loaded module '%s' at 0x%08x, \n", filename, pwm->module);
1405 /* Set the refCount here so that an attach failure will */
1406 /* decrement the dependencies through the MODULE_FreeLibrary call. */
1407 pwm->refCount++;
1409 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1410 SetLastError( err ); /* restore last error */
1411 HeapFree ( GetProcessHeap(), 0, filename );
1412 return pwm;
1415 if(GetLastError() != ERROR_FILE_NOT_FOUND)
1416 break;
1419 LeaveCriticalSection(&PROCESS_Current()->crit_section);
1420 error:
1421 WARN("Failed to load module '%s'; error=0x%08lx, \n", filename, GetLastError());
1422 HeapFree ( GetProcessHeap(), 0, filename );
1423 return NULL;
1426 /***********************************************************************
1427 * LoadLibraryA (KERNEL32)
1429 HMODULE WINAPI LoadLibraryA(LPCSTR libname) {
1430 return LoadLibraryExA(libname,0,0);
1433 /***********************************************************************
1434 * LoadLibraryW (KERNEL32)
1436 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
1438 return LoadLibraryExW(libnameW,0,0);
1441 /***********************************************************************
1442 * LoadLibrary32_16 (KERNEL.452)
1444 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
1446 HMODULE hModule;
1447 DWORD count;
1449 ReleaseThunkLock( &count );
1450 hModule = LoadLibraryA( libname );
1451 RestoreThunkLock( count );
1452 return hModule;
1455 /***********************************************************************
1456 * LoadLibraryExW (KERNEL32)
1458 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW,HANDLE hfile,DWORD flags)
1460 LPSTR libnameA = HEAP_strdupWtoA( GetProcessHeap(), 0, libnameW );
1461 HMODULE ret = LoadLibraryExA( libnameA , hfile, flags );
1463 HeapFree( GetProcessHeap(), 0, libnameA );
1464 return ret;
1467 /***********************************************************************
1468 * MODULE_FlushModrefs
1470 * NOTE: Assumes that the process critical section is held!
1472 * Remove all unused modrefs and call the internal unloading routines
1473 * for the library type.
1475 static void MODULE_FlushModrefs(void)
1477 WINE_MODREF *wm, *next;
1479 for(wm = PROCESS_Current()->modref_list; wm; wm = next)
1481 next = wm->next;
1483 if(wm->refCount)
1484 continue;
1486 /* Unlink this modref from the chain */
1487 if(wm->next)
1488 wm->next->prev = wm->prev;
1489 if(wm->prev)
1490 wm->prev->next = wm->next;
1491 if(wm == PROCESS_Current()->modref_list)
1492 PROCESS_Current()->modref_list = wm->next;
1494 TRACE(" unloading %s\n", wm->filename);
1495 /* VirtualFree( (LPVOID)wm->module, 0, MEM_RELEASE ); */ /* FIXME */
1496 /* if (wm->dlhandle) dlclose( wm->dlhandle ); */ /* FIXME */
1497 FreeLibrary16(wm->hDummyMod);
1498 HeapFree( GetProcessHeap(), 0, wm->deps );
1499 HeapFree( GetProcessHeap(), 0, wm->filename );
1500 HeapFree( GetProcessHeap(), 0, wm->short_filename );
1501 HeapFree( GetProcessHeap(), 0, wm );
1505 /***********************************************************************
1506 * FreeLibrary
1508 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
1510 BOOL retv = FALSE;
1511 WINE_MODREF *wm;
1513 EnterCriticalSection( &PROCESS_Current()->crit_section );
1514 PROCESS_Current()->free_lib_count++;
1516 wm = MODULE32_LookupHMODULE( hLibModule );
1517 if ( !wm || !hLibModule )
1518 SetLastError( ERROR_INVALID_HANDLE );
1519 else
1520 retv = MODULE_FreeLibrary( wm );
1522 PROCESS_Current()->free_lib_count--;
1523 LeaveCriticalSection( &PROCESS_Current()->crit_section );
1525 return retv;
1528 /***********************************************************************
1529 * MODULE_DecRefCount
1531 * NOTE: Assumes that the process critical section is held!
1533 static void MODULE_DecRefCount( WINE_MODREF *wm )
1535 int i;
1537 if ( wm->flags & WINE_MODREF_MARKER )
1538 return;
1540 if ( wm->refCount <= 0 )
1541 return;
1543 --wm->refCount;
1544 TRACE("(%s) refCount: %d\n", wm->modname, wm->refCount );
1546 if ( wm->refCount == 0 )
1548 wm->flags |= WINE_MODREF_MARKER;
1550 for ( i = 0; i < wm->nDeps; i++ )
1551 if ( wm->deps[i] )
1552 MODULE_DecRefCount( wm->deps[i] );
1554 wm->flags &= ~WINE_MODREF_MARKER;
1558 /***********************************************************************
1559 * MODULE_FreeLibrary
1561 * NOTE: Assumes that the process critical section is held!
1563 BOOL MODULE_FreeLibrary( WINE_MODREF *wm )
1565 TRACE("(%s) - START\n", wm->modname );
1567 /* Recursively decrement reference counts */
1568 MODULE_DecRefCount( wm );
1570 /* Call process detach notifications */
1571 if ( PROCESS_Current()->free_lib_count <= 1 )
1573 MODULE_DllProcessDetach( FALSE, NULL );
1574 SERVER_START_REQ
1576 struct unload_dll_request *req = server_alloc_req( sizeof(*req), 0 );
1577 req->base = (void *)wm->module;
1578 server_call_noerr( REQ_UNLOAD_DLL );
1580 SERVER_END_REQ;
1581 MODULE_FlushModrefs();
1584 TRACE("END\n");
1586 return TRUE;
1590 /***********************************************************************
1591 * FreeLibraryAndExitThread
1593 VOID WINAPI FreeLibraryAndExitThread(HINSTANCE hLibModule, DWORD dwExitCode)
1595 FreeLibrary(hLibModule);
1596 ExitThread(dwExitCode);
1599 /***********************************************************************
1600 * PrivateLoadLibrary (KERNEL32)
1602 * FIXME: rough guesswork, don't know what "Private" means
1604 HINSTANCE WINAPI PrivateLoadLibrary(LPCSTR libname)
1606 return (HINSTANCE)LoadLibrary16(libname);
1611 /***********************************************************************
1612 * PrivateFreeLibrary (KERNEL32)
1614 * FIXME: rough guesswork, don't know what "Private" means
1616 void WINAPI PrivateFreeLibrary(HINSTANCE handle)
1618 FreeLibrary16((HINSTANCE16)handle);
1622 /***********************************************************************
1623 * WIN32_GetProcAddress16 (KERNEL32.36)
1624 * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
1626 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
1628 if (!hModule) {
1629 WARN("hModule may not be 0!\n");
1630 return (FARPROC16)0;
1632 if (HIWORD(hModule))
1634 WARN("hModule is Win32 handle (%08x)\n", hModule );
1635 return (FARPROC16)0;
1637 return GetProcAddress16( hModule, name );
1640 /***********************************************************************
1641 * GetProcAddress16 (KERNEL.50)
1643 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, LPCSTR name )
1645 WORD ordinal;
1646 FARPROC16 ret;
1648 if (!hModule) hModule = GetCurrentTask();
1649 hModule = GetExePtr( hModule );
1651 if (HIWORD(name) != 0)
1653 ordinal = NE_GetOrdinal( hModule, name );
1654 TRACE("%04x '%s'\n", hModule, name );
1656 else
1658 ordinal = LOWORD(name);
1659 TRACE("%04x %04x\n", hModule, ordinal );
1661 if (!ordinal) return (FARPROC16)0;
1663 ret = NE_GetEntryPoint( hModule, ordinal );
1665 TRACE("returning %08x\n", (UINT)ret );
1666 return ret;
1670 /***********************************************************************
1671 * GetProcAddress (KERNEL32.257)
1673 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1675 return MODULE_GetProcAddress( hModule, function, TRUE );
1678 /***********************************************************************
1679 * GetProcAddress32 (KERNEL.453)
1681 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
1683 return MODULE_GetProcAddress( hModule, function, FALSE );
1686 /***********************************************************************
1687 * MODULE_GetProcAddress (internal)
1689 FARPROC MODULE_GetProcAddress(
1690 HMODULE hModule, /* [in] current module handle */
1691 LPCSTR function, /* [in] function to be looked up */
1692 BOOL snoop )
1694 WINE_MODREF *wm;
1695 FARPROC retproc = 0;
1697 if (HIWORD(function))
1698 TRACE_(win32)("(%08lx,%s)\n",(DWORD)hModule,function);
1699 else
1700 TRACE_(win32)("(%08lx,%p)\n",(DWORD)hModule,function);
1702 EnterCriticalSection( &PROCESS_Current()->crit_section );
1703 if ((wm = MODULE32_LookupHMODULE( hModule )))
1705 retproc = wm->find_export( wm, function, snoop );
1706 if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1708 LeaveCriticalSection( &PROCESS_Current()->crit_section );
1709 return retproc;
1713 /***************************************************************************
1714 * HasGPHandler (KERNEL.338)
1717 #include "pshpack1.h"
1718 typedef struct _GPHANDLERDEF
1720 WORD selector;
1721 WORD rangeStart;
1722 WORD rangeEnd;
1723 WORD handler;
1724 } GPHANDLERDEF;
1725 #include "poppack.h"
1727 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1729 HMODULE16 hModule;
1730 int gpOrdinal;
1731 SEGPTR gpPtr;
1732 GPHANDLERDEF *gpHandler;
1734 if ( (hModule = FarGetOwner16( SELECTOROF(address) )) != 0
1735 && (gpOrdinal = NE_GetOrdinal( hModule, "__GP" )) != 0
1736 && (gpPtr = (SEGPTR)NE_GetEntryPointEx( hModule, gpOrdinal, FALSE )) != 0
1737 && !IsBadReadPtr16( gpPtr, sizeof(GPHANDLERDEF) )
1738 && (gpHandler = PTR_SEG_TO_LIN( gpPtr )) != NULL )
1740 while (gpHandler->selector)
1742 if ( SELECTOROF(address) == gpHandler->selector
1743 && OFFSETOF(address) >= gpHandler->rangeStart
1744 && OFFSETOF(address) < gpHandler->rangeEnd )
1745 return PTR_SEG_OFF_TO_SEGPTR( gpHandler->selector,
1746 gpHandler->handler );
1747 gpHandler++;
1751 return 0;