Fixed Win16 documentation not fixed because of a bug in winapi_check.
[wine] / loader / module.c
1 /*
2  * Modules
3  *
4  * Copyright 1995 Alexandre Julliard
5  */
6
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"
23
24 DEFAULT_DEBUG_CHANNEL(module);
25 DECLARE_DEBUG_CHANNEL(win32);
26
27
28 /*************************************************************************
29  *              MODULE32_LookupHMODULE
30  * looks for the referenced HMODULE in the current process
31  * NOTE: Assumes that the process critical section is held!
32  */
33 static WINE_MODREF *MODULE32_LookupHMODULE( HMODULE hmod )
34 {
35     WINE_MODREF *wm;
36
37     if (!hmod) 
38         return PROCESS_Current()->exe_modref;
39
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;
44     }
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;
50 }
51
52 /*************************************************************************
53  *              MODULE_AllocModRef
54  *
55  * Allocate a WINE_MODREF structure and add it to the process list
56  * NOTE: Assumes that the process critical section is held!
57  */
58 WINE_MODREF *MODULE_AllocModRef( HMODULE hModule, LPCSTR filename )
59 {
60     WINE_MODREF *wm;
61     DWORD len;
62
63     if ((wm = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*wm) )))
64     {
65         wm->module = hModule;
66         wm->tlsindex = -1;
67
68         wm->filename = HEAP_strdupA( GetProcessHeap(), 0, filename );
69         if ((wm->modname = strrchr( wm->filename, '\\' ))) wm->modname++;
70         else wm->modname = wm->filename;
71
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;
77
78         wm->next = PROCESS_Current()->modref_list;
79         if (wm->next) wm->next->prev = wm;
80         PROCESS_Current()->modref_list = wm;
81     }
82     return wm;
83 }
84
85 /*************************************************************************
86  *              MODULE_InitDLL
87  */
88 static BOOL MODULE_InitDLL( WINE_MODREF *wm, DWORD type, LPVOID lpReserved )
89 {
90     BOOL retv = TRUE;
91
92     static LPCSTR typeName[] = { "PROCESS_DETACH", "PROCESS_ATTACH", 
93                                  "THREAD_ATTACH", "THREAD_DETACH" };
94     assert( wm );
95
96     /* Skip calls for modules loaded with special load flags */
97
98     if (wm->flags & WINE_MODREF_DONT_RESOLVE_REFS) return TRUE;
99
100     TRACE("(%s,%s,%p) - CALL\n", wm->modname, typeName[type], lpReserved );
101
102     /* Call the initialization routine */
103     retv = PE_InitDLL( wm->module, type, lpReserved );
104
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 );
109
110     return retv;
111 }
112
113 /*************************************************************************
114  *              MODULE_DllProcessAttach
115  * 
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
118  *
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
122  * 
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
126  *
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.)
130  *
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.
136  *
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*.
141  *
142  * NOTE: Assumes that the process critical section is held!
143  *
144  */
145 BOOL MODULE_DllProcessAttach( WINE_MODREF *wm, LPVOID lpReserved )
146 {
147     BOOL retv = TRUE;
148     int i;
149     assert( wm );
150
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;
155
156     TRACE("(%s,%p) - START\n", wm->modname, lpReserved );
157
158     /* Tag current MODREF to prevent recursive loop */
159     wm->flags |= WINE_MODREF_MARKER;
160
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 );
165
166     /* Call DLL entry point */
167     if ( retv )
168     {
169         retv = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
170         if ( retv )
171             wm->flags |= WINE_MODREF_PROCESS_ATTACHED;
172     }
173
174     /* Re-insert MODREF at head of list */
175     if ( retv && wm->prev )
176     {
177         wm->prev->next = wm->next;
178         if ( wm->next ) wm->next->prev = wm->prev;
179
180         wm->prev = NULL;
181         wm->next = PROCESS_Current()->modref_list;
182         PROCESS_Current()->modref_list = wm->next->prev = wm;
183     }
184
185     /* Remove recursion flag */
186     wm->flags &= ~WINE_MODREF_MARKER;
187
188     TRACE("(%s,%p) - END\n", wm->modname, lpReserved );
189
190     return retv;
191 }
192
193 /*************************************************************************
194  *              MODULE_DllProcessDetach
195  * 
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.
199  */
200 void MODULE_DllProcessDetach( BOOL bForceDetach, LPVOID lpReserved )
201 {
202     WINE_MODREF *wm;
203
204     EnterCriticalSection( &PROCESS_Current()->crit_section );
205
206     do
207     {
208         for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
209         {
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;
215
216             /* Call detach notification */
217             wm->flags &= ~WINE_MODREF_PROCESS_ATTACHED;
218             MODULE_InitDLL( wm, DLL_PROCESS_DETACH, lpReserved );
219
220             /* Restart at head of WINE_MODREF list, as entries might have
221                been added and/or removed while performing the call ... */
222             break;
223         }
224     } while ( wm );
225
226     LeaveCriticalSection( &PROCESS_Current()->crit_section );
227 }
228
229 /*************************************************************************
230  *              MODULE_DllThreadAttach
231  * 
232  * Send DLL thread attach notifications. These are sent in the
233  * reverse sequence of process detach notification.
234  *
235  */
236 void MODULE_DllThreadAttach( LPVOID lpReserved )
237 {
238     WINE_MODREF *wm;
239
240     EnterCriticalSection( &PROCESS_Current()->crit_section );
241
242     for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
243         if ( !wm->next )
244             break;
245
246     for ( ; wm; wm = wm->prev )
247     {
248         if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
249             continue;
250         if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
251             continue;
252
253         MODULE_InitDLL( wm, DLL_THREAD_ATTACH, lpReserved );
254     }
255
256     LeaveCriticalSection( &PROCESS_Current()->crit_section );
257 }
258
259 /*************************************************************************
260  *              MODULE_DllThreadDetach
261  * 
262  * Send DLL thread detach notifications. These are sent in the
263  * same sequence as process detach notification.
264  *
265  */
266 void MODULE_DllThreadDetach( LPVOID lpReserved )
267 {
268     WINE_MODREF *wm;
269
270     EnterCriticalSection( &PROCESS_Current()->crit_section );
271
272     for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
273     {
274         if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
275             continue;
276         if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
277             continue;
278
279         MODULE_InitDLL( wm, DLL_THREAD_DETACH, lpReserved );
280     }
281
282     LeaveCriticalSection( &PROCESS_Current()->crit_section );
283 }
284
285 /****************************************************************************
286  *              DisableThreadLibraryCalls (KERNEL32.74)
287  *
288  * Don't call DllEntryPoint for DLL_THREAD_{ATTACH,DETACH} if set.
289  */
290 BOOL WINAPI DisableThreadLibraryCalls( HMODULE hModule )
291 {
292     WINE_MODREF *wm;
293     BOOL retval = TRUE;
294
295     EnterCriticalSection( &PROCESS_Current()->crit_section );
296
297     wm = MODULE32_LookupHMODULE( hModule );
298     if ( !wm )
299         retval = FALSE;
300     else
301         wm->flags |= WINE_MODREF_NO_DLL_CALLS;
302
303     LeaveCriticalSection( &PROCESS_Current()->crit_section );
304
305     return retval;
306 }
307
308
309 /***********************************************************************
310  *           MODULE_CreateDummyModule
311  *
312  * Create a dummy NE module for Win32 or Winelib.
313  */
314 HMODULE MODULE_CreateDummyModule( LPCSTR filename, HMODULE module32 )
315 {
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;
324
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;
331
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 */
343                  8;
344
345     hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
346     if (!hModule) return (HMODULE)11;  /* invalid exe */
347
348     FarSetOwner16( hModule, hModule );
349     pModule = (NE_MODULE *)GlobalLock16( hModule );
350
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;
368
369     /* Set version and flags */
370     if (module32)
371     {
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;
378     }
379
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 );
385
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++;
396
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;
404
405     /* All tables zero terminated */
406     pModule->res_table = pModule->import_table = pModule->entry_table =
407                 (int)pStr - (int)pModule;
408
409     NE_RegisterModule( pModule );
410     return hModule;
411 }
412
413
414 /**********************************************************************
415  *          MODULE_FindModule
416  *
417  * Find a (loaded) win32 module depending on path
418  *
419  * RETURNS
420  *      the module handle if found
421  *      0 if not
422  */
423 WINE_MODREF *MODULE_FindModule(
424         LPCSTR path     /* [in] pathname of module/library to be found */
425 ) {
426     WINE_MODREF *wm;
427     char dllname[260], *p;
428
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" );
433
434     for ( wm = PROCESS_Current()->modref_list; wm; wm = wm->next )
435     {
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;
444     }
445
446     return wm;
447 }
448
449
450 /* Check whether a file is an OS/2 or a very old Windows executable
451  * by testing on import of KERNEL.
452  *
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...
455  */
456 static DWORD MODULE_Decide_OS2_OldWin(HANDLE hfile, IMAGE_DOS_HEADER *mz, IMAGE_OS2_HEADER *ne)
457 {
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;
464
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;
471
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;
478
479     for (i=0; i < ne->ne_cmod; i++)
480     {
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;
488         }
489     }
490
491 broken:
492     ERR("Hmm, an error occurred. Is this binary file broken ?\n");
493
494 good:
495     HeapFree( GetProcessHeap(), 0, modtab);
496     HeapFree( GetProcessHeap(), 0, nametab);
497     SetFilePointer( hfile, currpos, NULL, SEEK_SET); /* restore filepos */
498     return type;
499 }
500
501 /***********************************************************************
502  *           MODULE_GetBinaryType
503  *
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.
508  *
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
516  *
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.
520  *
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.
527  *
528  * Note that .COM and .PIF files are only recognized by their
529  * file name extension; but Windows does it the same way ...
530  */
531 static BOOL MODULE_GetBinaryType( HANDLE hfile, LPCSTR filename, LPDWORD lpBinaryType )
532 {
533     IMAGE_DOS_HEADER mz_header;
534     char magic[4], *ptr;
535     DWORD len;
536
537     /* Seek to the start of the file and read the DOS header information.
538      */
539     if (    SetFilePointer( hfile, 0, NULL, SEEK_SET ) != -1  
540          && ReadFile( hfile, &mz_header, sizeof(mz_header), &len, NULL )
541          && len == sizeof(mz_header) )
542     {
543         /* Now that we have the header check the e_magic field
544          * to see if this is a dos image.
545          */
546         if ( mz_header.e_magic == IMAGE_DOS_SIGNATURE )
547         {
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.
555              */
556             /* But before we do we will make sure that header
557              * structure encompasses the "Offset to extended header"
558              * field.
559              */
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;
568
569             if ( !lfanewValid )
570             {
571                 /* If we cannot read this "extended header" we will
572                  * assume that we have a simple DOS executable.
573                  */
574                 *lpBinaryType = SCS_DOS_BINARY;
575                 return TRUE;
576             }
577             else
578             {
579                 /* Reading the magic field succeeded so
580                  * we will try to determine what type it is.
581                  */
582                 if ( *(DWORD*)magic      == IMAGE_NT_SIGNATURE )
583                 {
584                     /* This is an NT signature.
585                      */
586                     *lpBinaryType = SCS_32BIT_BINARY;
587                     return TRUE;
588                 }
589                 else if ( *(WORD*)magic == IMAGE_OS2_SIGNATURE )
590                 {
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.
597                      */
598
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) )
603                      {
604                          switch ( ne.ne_exetyp )
605                          {
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;
611                          }
612                      }
613                      /* Couldn't read header, so abort. */
614                      return FALSE;
615                 }
616                 else
617                 {
618                     /* Unknown extended header, but this file is nonetheless
619                        DOS-executable.
620                      */
621                     *lpBinaryType = SCS_DOS_BINARY;
622                     return TRUE;
623                 }
624             }
625         }
626     }
627
628     /* If we get here, we don't even have a correct MZ header.
629      * Try to check the file extension for known types ...
630      */
631     ptr = strrchr( filename, '.' );
632     if ( ptr && !strchr( ptr, '\\' ) && !strchr( ptr, '/' ) )
633     {
634         if ( !strcasecmp( ptr, ".COM" ) )
635         {
636             *lpBinaryType = SCS_DOS_BINARY;
637             return TRUE;
638         }
639
640         if ( !strcasecmp( ptr, ".PIF" ) )
641         {
642             *lpBinaryType = SCS_PIF_BINARY;
643             return TRUE;
644         }
645     }
646
647     return FALSE;
648 }
649
650 /***********************************************************************
651  *             GetBinaryTypeA                     [KERNEL32.280]
652  */
653 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
654 {
655     BOOL ret = FALSE;
656     HANDLE hfile;
657
658     TRACE_(win32)("%s\n", lpApplicationName );
659
660     /* Sanity check.
661      */
662     if ( lpApplicationName == NULL || lpBinaryType == NULL )
663         return FALSE;
664
665     /* Open the file indicated by lpApplicationName for reading.
666      */
667     hfile = CreateFileA( lpApplicationName, GENERIC_READ, FILE_SHARE_READ,
668                          NULL, OPEN_EXISTING, 0, -1 );
669     if ( hfile == INVALID_HANDLE_VALUE )
670         return FALSE;
671
672     /* Check binary type
673      */
674     ret = MODULE_GetBinaryType( hfile, lpApplicationName, lpBinaryType );
675
676     /* Close the file.
677      */
678     CloseHandle( hfile );
679
680     return ret;
681 }
682
683 /***********************************************************************
684  *             GetBinaryTypeW                      [KERNEL32.281]
685  */
686 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
687 {
688     BOOL ret = FALSE;
689     LPSTR strNew = NULL;
690
691     TRACE_(win32)("%s\n", debugstr_w(lpApplicationName) );
692
693     /* Sanity check.
694      */
695     if ( lpApplicationName == NULL || lpBinaryType == NULL )
696         return FALSE;
697
698     /* Convert the wide string to a ascii string.
699      */
700     strNew = HEAP_strdupWtoA( GetProcessHeap(), 0, lpApplicationName );
701
702     if ( strNew != NULL )
703     {
704         ret = GetBinaryTypeA( strNew, lpBinaryType );
705
706         /* Free the allocated string.
707          */
708         HeapFree( GetProcessHeap(), 0, strNew );
709     }
710
711     return ret;
712 }
713
714
715 /***********************************************************************
716  *           WinExec16   (KERNEL.166)
717  */
718 HINSTANCE16 WINAPI WinExec16( LPCSTR lpCmdLine, UINT16 nCmdShow )
719 {
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];
726
727     if (*lpCmdLine == '"') /* has to be only one and only at beginning ! */
728     {
729       name_beg = lpCmdLine+1;
730       p = strchr ( lpCmdLine+1, '"' );
731       if (p)
732       {
733           name_end = p;
734           args = strchr ( p, ' ' );
735       }
736       else /* yes, even valid with trailing '"' missing */
737           name_end = lpCmdLine+strlen(lpCmdLine);
738     }
739     else 
740     {
741       name_beg = lpCmdLine;
742       args = strchr( lpCmdLine, ' ' );
743       name_end = args ? args : lpCmdLine+strlen(lpCmdLine);
744     }
745
746     if ((name_beg == lpCmdLine) && (!args))
747     { /* just use the original cmdline string as file name */
748         name = (LPSTR)lpCmdLine;
749     }
750     else
751     {
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';
756     }
757
758     if (args)
759     {
760         args++;
761         arglen = strlen(args);
762         cmdline = SEGPTR_ALLOC( 2 + arglen );
763         cmdline[0] = (BYTE)arglen;
764         strcpy( cmdline + 1, args );
765     }
766     else
767     {
768         cmdline = SEGPTR_ALLOC( 2 );
769         cmdline[0] = cmdline[1] = 0;
770     }
771
772     TRACE("name: '%s', cmdline: '%.*s'\n", name, cmdline[0], &cmdline[1]);
773
774     if (SearchPathA( NULL, name, ".exe", sizeof(buffer), buffer, NULL ))
775     {
776         LOADPARAMS16 params;
777         WORD *showCmd = SEGPTR_ALLOC( 2*sizeof(WORD) );
778         showCmd[0] = 2;
779         showCmd[1] = nCmdShow;
780
781         params.hEnvironment = 0;
782         params.cmdLine = SEGPTR_GET(cmdline);
783         params.showCmd = SEGPTR_GET(showCmd);
784         params.reserved = 0;
785
786         ret = LoadModule16( buffer, &params );
787
788         SEGPTR_FREE( showCmd );
789         SEGPTR_FREE( cmdline );
790     }
791     else ret = GetLastError();
792
793     if (name != lpCmdLine) HeapFree( GetProcessHeap(), 0, name );
794
795     if (ret == 21)  /* 32-bit module */
796     {
797         DWORD count;
798         ReleaseThunkLock( &count );
799         ret = WinExec( lpCmdLine, nCmdShow );
800         RestoreThunkLock( count );
801     }
802     return ret;
803 }
804
805 /***********************************************************************
806  *           WinExec   (KERNEL32.566)
807  */
808 HINSTANCE WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
809 {
810     PROCESS_INFORMATION info;
811     STARTUPINFOA startup;
812     HINSTANCE hInstance;
813     char *cmdline;
814
815     memset( &startup, 0, sizeof(startup) );
816     startup.cb = sizeof(startup);
817     startup.dwFlags = STARTF_USESHOWWINDOW;
818     startup.wShowWindow = nCmdShow;
819
820     /* cmdline needs to be writeable for CreateProcess */
821     if (!(cmdline = HEAP_strdupA( GetProcessHeap(), 0, lpCmdLine ))) return 0;
822
823     if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
824                         0, NULL, NULL, &startup, &info ))
825     {
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 );
834     }
835     else if ((hInstance = GetLastError()) >= 32)
836     {
837         FIXME("Strange error set by CreateProcess: %d\n", hInstance );
838         hInstance = 11;
839     }
840     HeapFree( GetProcessHeap(), 0, cmdline );
841     return hInstance;
842 }
843
844 /**********************************************************************
845  *          LoadModule    (KERNEL32.499)
846  */
847 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock ) 
848 {
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;
856
857     if (!name) return ERROR_FILE_NOT_FOUND;
858
859     if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
860         !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
861         return GetLastError();
862
863     len = (BYTE)params->lpCmdLine[0];
864     if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
865         return ERROR_NOT_ENOUGH_MEMORY;
866
867     strcpy( cmdline, filename );
868     p = cmdline + strlen(cmdline);
869     *p++ = ' ';
870     memcpy( p, params->lpCmdLine + 1, len );
871     p[len] = 0;
872
873     memset( &startup, 0, sizeof(startup) );
874     startup.cb = sizeof(startup);
875     if (params->lpCmdShow)
876     {
877         startup.dwFlags = STARTF_USESHOWWINDOW;
878         startup.wShowWindow = params->lpCmdShow[1];
879     }
880     
881     if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
882                         params->lpEnvAddress, NULL, &startup, &info ))
883     {
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 );
892     }
893     else if ((hInstance = GetLastError()) >= 32)
894     {
895         FIXME("Strange error set by CreateProcess: %d\n", hInstance );
896         hInstance = 11;
897     }
898
899     HeapFree( GetProcessHeap(), 0, cmdline );
900     return hInstance;
901 }
902
903
904 /*************************************************************************
905  *               get_file_name
906  *
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.
910  */
911 static LPSTR get_file_name( LPCSTR appname, LPSTR cmdline, LPSTR buffer, int buflen )
912 {
913     char *name, *pos, *ret = NULL;
914     const char *p;
915
916     /* if we have an app name, everything is easy */
917
918     if (appname)
919     {
920         /* use the unmodified app name as file name */
921         lstrcpynA( buffer, appname, buflen );
922         if (!(ret = cmdline))
923         {
924             /* no command-line, create one */
925             if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(appname) + 3 )))
926                 sprintf( ret, "\"%s\"", appname );
927         }
928         return ret;
929     }
930
931     if (!cmdline)
932     {
933         SetLastError( ERROR_INVALID_PARAMETER );
934         return NULL;
935     }
936
937     /* first check for a quoted file name */
938
939     if ((cmdline[0] == '"') && ((p = strchr( cmdline + 1, '"' ))))
940     {
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;
946
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;
951     }
952
953     /* now try the command-line word by word */
954
955     if (!(name = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 1 ))) return NULL;
956     pos = name;
957     p = cmdline;
958
959     while (*p)
960     {
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 ))
966         {
967             ret = cmdline;
968             break;
969         }
970     }
971
972     if (!ret || !strchr( name, ' ' )) goto done;  /* no change necessary */
973
974     /* now build a new command-line with quotes */
975
976     if (!(ret = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 3 ))) goto done;
977     sprintf( ret, "\"%s\"%s", name, p );
978
979  done:
980     HeapFree( GetProcessHeap(), 0, name );
981     return ret;
982 }
983
984
985 /**********************************************************************
986  *       CreateProcessA          (KERNEL32.171)
987  */
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 )
995 {
996     BOOL retv = FALSE;
997     HANDLE hFile;
998     DWORD type;
999     char name[MAX_PATH];
1000     LPSTR tidy_cmdline;
1001
1002     /* Process the AppName and/or CmdLine to get module name and path */
1003
1004     TRACE("app '%s' cmdline '%s'\n", lpApplicationName, lpCommandLine );
1005
1006     if (!(tidy_cmdline = get_file_name( lpApplicationName, lpCommandLine, name, sizeof(name) )))
1007         return FALSE;
1008
1009     /* Warn if unsupported features are used */
1010
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);
1061
1062     /* Open file and determine executable type */
1063
1064     hFile = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, -1 );
1065     if (hFile == INVALID_HANDLE_VALUE) goto done;
1066
1067     if ( !MODULE_GetBinaryType( hFile, name, &type ) )
1068     {
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;
1075     }
1076
1077     /* Create process */
1078
1079     switch ( type )
1080     {
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;
1089
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 */
1095
1096     default:
1097         SetLastError( ERROR_BAD_FORMAT );
1098         break;
1099     }
1100     CloseHandle( hFile );
1101
1102  done:
1103     if (tidy_cmdline != lpCommandLine) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1104     return retv;
1105 }
1106
1107 /**********************************************************************
1108  *       CreateProcessW          (KERNEL32.172)
1109  * NOTES
1110  *  lpReserved is not converted
1111  */
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;
1121     
1122     LPSTR lpApplicationNameA = HEAP_strdupWtoA (GetProcessHeap(),0,lpApplicationName);
1123     LPSTR lpCommandLineA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCommandLine);
1124     LPSTR lpCurrentDirectoryA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCurrentDirectory);
1125
1126     memcpy (&StartupInfoA, lpStartupInfo, sizeof(STARTUPINFOA));
1127     StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpDesktop);
1128     StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpTitle);
1129
1130     TRACE_(win32)("(%s,%s,...)\n", debugstr_w(lpApplicationName), debugstr_w(lpCommandLine));
1131
1132     if (lpStartupInfo->lpReserved)
1133       FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n", debugstr_w(lpStartupInfo->lpReserved));
1134       
1135     ret = CreateProcessA(  lpApplicationNameA,  lpCommandLineA, 
1136                              lpProcessAttributes, lpThreadAttributes,
1137                              bInheritHandles, dwCreationFlags,
1138                              lpEnvironment, lpCurrentDirectoryA,
1139                              &StartupInfoA, lpProcessInfo );
1140
1141     HeapFree( GetProcessHeap(), 0, lpCurrentDirectoryA );
1142     HeapFree( GetProcessHeap(), 0, lpCommandLineA );
1143     HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1144     HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1145
1146     return ret;
1147 }
1148
1149 /***********************************************************************
1150  *              GetModuleHandleA         (KERNEL32.237)
1151  */
1152 HMODULE WINAPI GetModuleHandleA(LPCSTR module)
1153 {
1154     WINE_MODREF *wm;
1155
1156     if ( module == NULL )
1157         wm = PROCESS_Current()->exe_modref;
1158     else
1159         wm = MODULE_FindModule( module );
1160
1161     return wm? wm->module : 0;
1162 }
1163
1164 /***********************************************************************
1165  *              GetModuleHandleW
1166  */
1167 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
1168 {
1169     HMODULE hModule;
1170     LPSTR modulea = HEAP_strdupWtoA( GetProcessHeap(), 0, module );
1171     hModule = GetModuleHandleA( modulea );
1172     HeapFree( GetProcessHeap(), 0, modulea );
1173     return hModule;
1174 }
1175
1176
1177 /***********************************************************************
1178  *              GetModuleFileNameA      (KERNEL32.235)
1179  *
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)
1184  */
1185 DWORD WINAPI GetModuleFileNameA( 
1186         HMODULE hModule,        /* [in] module handle (32bit) */
1187         LPSTR lpFileName,       /* [out] filenamebuffer */
1188         DWORD size )            /* [in] size of filenamebuffer */
1189 {
1190     WINE_MODREF *wm;
1191
1192     EnterCriticalSection( &PROCESS_Current()->crit_section );
1193
1194     lpFileName[0] = 0;
1195     if ((wm = MODULE32_LookupHMODULE( hModule )))
1196         lstrcpynA( lpFileName, wm->filename, size );
1197
1198     LeaveCriticalSection( &PROCESS_Current()->crit_section );
1199     TRACE("%s\n", lpFileName );
1200     return strlen(lpFileName);
1201 }                   
1202  
1203
1204 /***********************************************************************
1205  *              GetModuleFileNameW      (KERNEL32.236)
1206  */
1207 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName,
1208                                    DWORD size )
1209 {
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;
1216 }
1217
1218
1219 /***********************************************************************
1220  *           LoadLibraryExA   (KERNEL32)
1221  */
1222 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
1223 {
1224         WINE_MODREF *wm;
1225
1226         if(!libname)
1227         {
1228                 SetLastError(ERROR_INVALID_PARAMETER);
1229                 return 0;
1230         }
1231
1232         if (flags & LOAD_LIBRARY_AS_DATAFILE)
1233         {
1234             char filename[256];
1235             HFILE hFile;
1236             HMODULE hmod = 0;
1237
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)
1244             {
1245                 hmod = PE_LoadImage( hFile, filename, flags );
1246                 CloseHandle( hFile );
1247             }
1248             return hmod;
1249         }
1250
1251         EnterCriticalSection(&PROCESS_Current()->crit_section);
1252
1253         wm = MODULE_LoadLibraryExA( libname, hfile, flags );
1254         if ( wm )
1255         {
1256                 if ( !MODULE_DllProcessAttach( wm, NULL ) )
1257                 {
1258                         WARN_(module)("Attach failed for module '%s', \n", libname);
1259                         MODULE_FreeLibrary(wm);
1260                         SetLastError(ERROR_DLL_INIT_FAILED);
1261                         wm = NULL;
1262                 }
1263         }
1264
1265         LeaveCriticalSection(&PROCESS_Current()->crit_section);
1266
1267         return wm ? wm->module : 0;
1268 }
1269
1270 /***********************************************************************
1271  *      MODULE_LoadLibraryExA   (internal)
1272  *
1273  * Load a PE style module according to the load order.
1274  *
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.
1279  *
1280  */
1281 WINE_MODREF *MODULE_LoadLibraryExA( LPCSTR libname, HFILE hfile, DWORD flags )
1282 {
1283         DWORD err = GetLastError();
1284         WINE_MODREF *pwm;
1285         int i;
1286         module_loadorder_t *plo;
1287         LPSTR filename, p;
1288
1289         if ( !libname ) return NULL;
1290
1291         filename = HeapAlloc ( GetProcessHeap(), 0, MAX_PATH + 1 );
1292         if ( !filename ) return NULL;
1293
1294         /* build the modules filename */
1295         if (!SearchPathA( NULL, libname, ".dll", MAX_PATH, filename, NULL ))
1296         {
1297             if ( ! GetSystemDirectoryA ( filename, MAX_PATH ) ) 
1298                 goto error;
1299
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
1303
1304                if the library name does not contain a path and can not be found, assume the 
1305                system directory is meant */
1306             
1307             if ( ! strncasecmp ( filename, libname, strlen ( filename ) ))
1308                 strcpy ( filename, libname );
1309             else
1310             {
1311                 if ( strchr ( libname, '\\' ) || strchr ( libname, ':') || strchr ( libname, '/' ) ) 
1312                     goto error;
1313                 else 
1314                 {
1315                     strcat ( filename, "\\" );
1316                     strcat ( filename, libname );
1317                 }
1318             }
1319       
1320             /* if the filename doesn't have an extension append .DLL */
1321             if (!(p = strrchr( filename, '.')) || strchr( p, '/' ) || strchr( p, '\\'))
1322                 strcat( filename, ".DLL" );
1323         }
1324
1325         EnterCriticalSection(&PROCESS_Current()->crit_section);
1326
1327         /* Check for already loaded module */
1328         if (!(pwm = MODULE_FindModule(filename)) && 
1329             /* no path in libpath */
1330             !strchr( libname, '\\' ) && !strchr( libname, ':') && !strchr( libname, '/' )) 
1331         {
1332             LPSTR       fn = HeapAlloc ( GetProcessHeap(), 0, MAX_PATH + 1 );
1333             if (fn)
1334             {
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)
1341                  */
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 );
1348             }
1349         }
1350         if (pwm)
1351         {
1352                 if(!(pwm->flags & WINE_MODREF_MARKER))
1353                         pwm->refCount++;
1354
1355                 if ((pwm->flags & WINE_MODREF_DONT_RESOLVE_REFS) &&
1356                     !(flags & DONT_RESOLVE_DLL_REFERENCES))
1357                 {
1358                     extern DWORD fixup_imports(WINE_MODREF *wm); /*FIXME*/
1359                     pwm->flags &= ~WINE_MODREF_DONT_RESOLVE_REFS;
1360                     fixup_imports( pwm );
1361                 }
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;
1366         }
1367
1368         plo = MODULE_GetLoadOrder(filename, TRUE);
1369
1370         for(i = 0; i < MODULE_LOADORDER_NTYPES; i++)
1371         {
1372                 SetLastError( ERROR_FILE_NOT_FOUND );
1373                 switch(plo->loadorder[i])
1374                 {
1375                 case MODULE_LOADORDER_DLL:
1376                         TRACE("Trying native dll '%s'\n", filename);
1377                         pwm = PE_LoadLibraryExA(filename, flags);
1378                         break;
1379
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;
1385
1386                 case MODULE_LOADORDER_BI:
1387                         TRACE("Trying built-in '%s'\n", filename);
1388                         pwm = BUILTIN32_LoadLibraryExA(filename, flags);
1389                         break;
1390
1391                 default:
1392                         ERR("Got invalid loadorder type %d (%s index %d)\n", plo->loadorder[i], plo->modulename, i);
1393                 /* Fall through */
1394
1395                 case MODULE_LOADORDER_INVALID:  /* We ignore this as it is an empty entry */
1396                         pwm = NULL;
1397                         break;
1398                 }
1399
1400                 if(pwm)
1401                 {
1402                         /* Initialize DLL just loaded */
1403                         TRACE("Loaded module '%s' at 0x%08x, \n", filename, pwm->module);
1404
1405                         /* Set the refCount here so that an attach failure will */
1406                         /* decrement the dependencies through the MODULE_FreeLibrary call. */
1407                         pwm->refCount++;
1408
1409                         LeaveCriticalSection(&PROCESS_Current()->crit_section);
1410                         SetLastError( err );  /* restore last error */
1411                         HeapFree ( GetProcessHeap(), 0, filename );
1412                         return pwm;
1413                 }
1414
1415                 if(GetLastError() != ERROR_FILE_NOT_FOUND)
1416                         break;
1417         }
1418
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;
1424 }
1425
1426 /***********************************************************************
1427  *           LoadLibraryA         (KERNEL32)
1428  */
1429 HMODULE WINAPI LoadLibraryA(LPCSTR libname) {
1430         return LoadLibraryExA(libname,0,0);
1431 }
1432
1433 /***********************************************************************
1434  *           LoadLibraryW         (KERNEL32)
1435  */
1436 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
1437 {
1438     return LoadLibraryExW(libnameW,0,0);
1439 }
1440
1441 /***********************************************************************
1442  *           LoadLibrary32_16   (KERNEL.452)
1443  */
1444 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
1445 {
1446     HMODULE hModule;
1447     DWORD count;
1448
1449     ReleaseThunkLock( &count );
1450     hModule = LoadLibraryA( libname );
1451     RestoreThunkLock( count );
1452     return hModule;
1453 }
1454
1455 /***********************************************************************
1456  *           LoadLibraryExW       (KERNEL32)
1457  */
1458 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW,HANDLE hfile,DWORD flags)
1459 {
1460     LPSTR libnameA = HEAP_strdupWtoA( GetProcessHeap(), 0, libnameW );
1461     HMODULE ret = LoadLibraryExA( libnameA , hfile, flags );
1462
1463     HeapFree( GetProcessHeap(), 0, libnameA );
1464     return ret;
1465 }
1466
1467 /***********************************************************************
1468  *           MODULE_FlushModrefs
1469  *
1470  * NOTE: Assumes that the process critical section is held!
1471  *
1472  * Remove all unused modrefs and call the internal unloading routines
1473  * for the library type.
1474  */
1475 static void MODULE_FlushModrefs(void)
1476 {
1477         WINE_MODREF *wm, *next;
1478
1479         for(wm = PROCESS_Current()->modref_list; wm; wm = next)
1480         {
1481                 next = wm->next;
1482
1483                 if(wm->refCount)
1484                         continue;
1485
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;
1493
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 );
1502         }
1503 }
1504
1505 /***********************************************************************
1506  *           FreeLibrary
1507  */
1508 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
1509 {
1510     BOOL retv = FALSE;
1511     WINE_MODREF *wm;
1512
1513     EnterCriticalSection( &PROCESS_Current()->crit_section );
1514     PROCESS_Current()->free_lib_count++;
1515
1516     wm = MODULE32_LookupHMODULE( hLibModule );
1517     if ( !wm || !hLibModule )
1518         SetLastError( ERROR_INVALID_HANDLE );
1519     else
1520         retv = MODULE_FreeLibrary( wm );
1521
1522     PROCESS_Current()->free_lib_count--;
1523     LeaveCriticalSection( &PROCESS_Current()->crit_section );
1524
1525     return retv;
1526 }
1527
1528 /***********************************************************************
1529  *           MODULE_DecRefCount
1530  *
1531  * NOTE: Assumes that the process critical section is held!
1532  */
1533 static void MODULE_DecRefCount( WINE_MODREF *wm )
1534 {
1535     int i;
1536
1537     if ( wm->flags & WINE_MODREF_MARKER )
1538         return;
1539
1540     if ( wm->refCount <= 0 )
1541         return;
1542
1543     --wm->refCount;
1544     TRACE("(%s) refCount: %d\n", wm->modname, wm->refCount );
1545
1546     if ( wm->refCount == 0 )
1547     {
1548         wm->flags |= WINE_MODREF_MARKER;
1549
1550         for ( i = 0; i < wm->nDeps; i++ )
1551             if ( wm->deps[i] )
1552                 MODULE_DecRefCount( wm->deps[i] );
1553
1554         wm->flags &= ~WINE_MODREF_MARKER;
1555     }
1556 }
1557
1558 /***********************************************************************
1559  *           MODULE_FreeLibrary
1560  *
1561  * NOTE: Assumes that the process critical section is held!
1562  */
1563 BOOL MODULE_FreeLibrary( WINE_MODREF *wm )
1564 {
1565     TRACE("(%s) - START\n", wm->modname );
1566
1567     /* Recursively decrement reference counts */
1568     MODULE_DecRefCount( wm );
1569
1570     /* Call process detach notifications */
1571     if ( PROCESS_Current()->free_lib_count <= 1 )
1572     {
1573         MODULE_DllProcessDetach( FALSE, NULL );
1574         SERVER_START_REQ
1575         {
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 );
1579         }
1580         SERVER_END_REQ;
1581         MODULE_FlushModrefs();
1582     }
1583
1584     TRACE("END\n");
1585
1586     return TRUE;
1587 }
1588
1589
1590 /***********************************************************************
1591  *           FreeLibraryAndExitThread
1592  */
1593 VOID WINAPI FreeLibraryAndExitThread(HINSTANCE hLibModule, DWORD dwExitCode)
1594 {
1595     FreeLibrary(hLibModule);
1596     ExitThread(dwExitCode);
1597 }
1598
1599 /***********************************************************************
1600  *           PrivateLoadLibrary       (KERNEL32)
1601  *
1602  * FIXME: rough guesswork, don't know what "Private" means
1603  */
1604 HINSTANCE WINAPI PrivateLoadLibrary(LPCSTR libname)
1605 {
1606         return (HINSTANCE)LoadLibrary16(libname);
1607 }
1608
1609
1610
1611 /***********************************************************************
1612  *           PrivateFreeLibrary       (KERNEL32)
1613  *
1614  * FIXME: rough guesswork, don't know what "Private" means
1615  */
1616 void WINAPI PrivateFreeLibrary(HINSTANCE handle)
1617 {
1618         FreeLibrary16((HINSTANCE16)handle);
1619 }
1620
1621
1622 /***********************************************************************
1623  *           WIN32_GetProcAddress16   (KERNEL32.36)
1624  * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
1625  */
1626 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
1627 {
1628     if (!hModule) {
1629         WARN("hModule may not be 0!\n");
1630         return (FARPROC16)0;
1631     }
1632     if (HIWORD(hModule))
1633     {
1634         WARN("hModule is Win32 handle (%08x)\n", hModule );
1635         return (FARPROC16)0;
1636     }
1637     return GetProcAddress16( hModule, name );
1638 }
1639
1640 /***********************************************************************
1641  *           GetProcAddress16   (KERNEL.50)
1642  */
1643 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, LPCSTR name )
1644 {
1645     WORD ordinal;
1646     FARPROC16 ret;
1647
1648     if (!hModule) hModule = GetCurrentTask();
1649     hModule = GetExePtr( hModule );
1650
1651     if (HIWORD(name) != 0)
1652     {
1653         ordinal = NE_GetOrdinal( hModule, name );
1654         TRACE("%04x '%s'\n", hModule, name );
1655     }
1656     else
1657     {
1658         ordinal = LOWORD(name);
1659         TRACE("%04x %04x\n", hModule, ordinal );
1660     }
1661     if (!ordinal) return (FARPROC16)0;
1662
1663     ret = NE_GetEntryPoint( hModule, ordinal );
1664
1665     TRACE("returning %08x\n", (UINT)ret );
1666     return ret;
1667 }
1668
1669
1670 /***********************************************************************
1671  *           GetProcAddress             (KERNEL32.257)
1672  */
1673 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1674 {
1675     return MODULE_GetProcAddress( hModule, function, TRUE );
1676 }
1677
1678 /***********************************************************************
1679  *           GetProcAddress32                   (KERNEL.453)
1680  */
1681 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
1682 {
1683     return MODULE_GetProcAddress( hModule, function, FALSE );
1684 }
1685
1686 /***********************************************************************
1687  *           MODULE_GetProcAddress              (internal)
1688  */
1689 FARPROC MODULE_GetProcAddress( 
1690         HMODULE hModule,        /* [in] current module handle */
1691         LPCSTR function,        /* [in] function to be looked up */
1692         BOOL snoop )
1693 {
1694     WINE_MODREF *wm;
1695     FARPROC     retproc = 0;
1696
1697     if (HIWORD(function))
1698         TRACE_(win32)("(%08lx,%s)\n",(DWORD)hModule,function);
1699     else
1700         TRACE_(win32)("(%08lx,%p)\n",(DWORD)hModule,function);
1701
1702     EnterCriticalSection( &PROCESS_Current()->crit_section );
1703     if ((wm = MODULE32_LookupHMODULE( hModule )))
1704     {
1705         retproc = wm->find_export( wm, function, snoop );
1706         if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1707     }
1708     LeaveCriticalSection( &PROCESS_Current()->crit_section );
1709     return retproc;
1710 }
1711
1712
1713 /***************************************************************************
1714  *              HasGPHandler                    (KERNEL.338)
1715  */
1716
1717 #include "pshpack1.h"
1718 typedef struct _GPHANDLERDEF
1719 {
1720     WORD selector;
1721     WORD rangeStart;
1722     WORD rangeEnd;
1723     WORD handler;
1724 } GPHANDLERDEF;
1725 #include "poppack.h"
1726
1727 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1728 {
1729     HMODULE16 hModule;
1730     int gpOrdinal;
1731     SEGPTR gpPtr;
1732     GPHANDLERDEF *gpHandler;
1733    
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 )
1739     {
1740         while (gpHandler->selector)
1741         {
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++;
1748         }
1749     }
1750
1751     return 0;
1752 }
1753