Use the exe name and file handle we got from the server also when
[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 "file.h"
18 #include "module.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 WINE_MODREF *MODULE_modref_list = NULL;
28
29 static WINE_MODREF *exe_modref;
30 static int free_lib_count;   /* recursion depth of FreeLibrary calls */
31 static int process_detaching;  /* set on process detach to avoid deadlocks with thread detach */
32
33 /*************************************************************************
34  *              MODULE32_LookupHMODULE
35  * looks for the referenced HMODULE in the current process
36  * NOTE: Assumes that the process critical section is held!
37  */
38 static WINE_MODREF *MODULE32_LookupHMODULE( HMODULE hmod )
39 {
40     WINE_MODREF *wm;
41
42     if (!hmod) 
43         return exe_modref;
44
45     if (!HIWORD(hmod)) {
46         ERR("tried to lookup 0x%04x in win32 module handler!\n",hmod);
47         SetLastError( ERROR_INVALID_HANDLE );
48         return NULL;
49     }
50     for ( wm = MODULE_modref_list; wm; wm=wm->next )
51         if (wm->module == hmod)
52             return wm;
53     SetLastError( ERROR_INVALID_HANDLE );
54     return NULL;
55 }
56
57 /*************************************************************************
58  *              MODULE_AllocModRef
59  *
60  * Allocate a WINE_MODREF structure and add it to the process list
61  * NOTE: Assumes that the process critical section is held!
62  */
63 WINE_MODREF *MODULE_AllocModRef( HMODULE hModule, LPCSTR filename )
64 {
65     WINE_MODREF *wm;
66     DWORD len;
67
68     if ((wm = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(*wm) )))
69     {
70         wm->module = hModule;
71         wm->tlsindex = -1;
72
73         wm->filename = HEAP_strdupA( GetProcessHeap(), 0, filename );
74         if ((wm->modname = strrchr( wm->filename, '\\' ))) wm->modname++;
75         else wm->modname = wm->filename;
76
77         len = GetShortPathNameA( wm->filename, NULL, 0 );
78         wm->short_filename = (char *)HeapAlloc( GetProcessHeap(), 0, len+1 );
79         GetShortPathNameA( wm->filename, wm->short_filename, len+1 );
80         if ((wm->short_modname = strrchr( wm->short_filename, '\\' ))) wm->short_modname++;
81         else wm->short_modname = wm->short_filename;
82
83         wm->next = MODULE_modref_list;
84         if (wm->next) wm->next->prev = wm;
85         MODULE_modref_list = wm;
86
87         if (!(PE_HEADER(hModule)->FileHeader.Characteristics & IMAGE_FILE_DLL))
88         {
89             if (!exe_modref) exe_modref = wm;
90             else FIXME( "Trying to load second .EXE file: %s\n", filename );
91         }
92     }
93     return wm;
94 }
95
96 /*************************************************************************
97  *              MODULE_InitDLL
98  */
99 static BOOL MODULE_InitDLL( WINE_MODREF *wm, DWORD type, LPVOID lpReserved )
100 {
101     BOOL retv = TRUE;
102
103     static LPCSTR typeName[] = { "PROCESS_DETACH", "PROCESS_ATTACH", 
104                                  "THREAD_ATTACH", "THREAD_DETACH" };
105     assert( wm );
106
107     /* Skip calls for modules loaded with special load flags */
108
109     if (wm->flags & WINE_MODREF_DONT_RESOLVE_REFS) return TRUE;
110
111     TRACE("(%s,%s,%p) - CALL\n", wm->modname, typeName[type], lpReserved );
112
113     /* Call the initialization routine */
114     retv = PE_InitDLL( wm->module, type, lpReserved );
115
116     /* The state of the module list may have changed due to the call
117        to PE_InitDLL. We cannot assume that this module has not been
118        deleted.  */
119     TRACE("(%p,%s,%p) - RETURN %d\n", wm, typeName[type], lpReserved, retv );
120
121     return retv;
122 }
123
124 /*************************************************************************
125  *              MODULE_DllProcessAttach
126  * 
127  * Send the process attach notification to all DLLs the given module
128  * depends on (recursively). This is somewhat complicated due to the fact that
129  *
130  * - we have to respect the module dependencies, i.e. modules implicitly
131  *   referenced by another module have to be initialized before the module
132  *   itself can be initialized
133  * 
134  * - the initialization routine of a DLL can itself call LoadLibrary,
135  *   thereby introducing a whole new set of dependencies (even involving
136  *   the 'old' modules) at any time during the whole process
137  *
138  * (Note that this routine can be recursively entered not only directly
139  *  from itself, but also via LoadLibrary from one of the called initialization
140  *  routines.)
141  *
142  * Furthermore, we need to rearrange the main WINE_MODREF list to allow
143  * the process *detach* notifications to be sent in the correct order.
144  * This must not only take into account module dependencies, but also 
145  * 'hidden' dependencies created by modules calling LoadLibrary in their
146  * attach notification routine.
147  *
148  * The strategy is rather simple: we move a WINE_MODREF to the head of the
149  * list after the attach notification has returned.  This implies that the
150  * detach notifications are called in the reverse of the sequence the attach
151  * notifications *returned*.
152  */
153 BOOL MODULE_DllProcessAttach( WINE_MODREF *wm, LPVOID lpReserved )
154 {
155     BOOL retv = TRUE;
156     int i;
157
158     RtlAcquirePebLock();
159
160     if (!wm) wm = exe_modref;
161     assert( wm );
162
163     /* prevent infinite recursion in case of cyclical dependencies */
164     if (    ( wm->flags & WINE_MODREF_MARKER )
165          || ( wm->flags & WINE_MODREF_PROCESS_ATTACHED ) )
166         goto done;
167
168     TRACE("(%s,%p) - START\n", wm->modname, lpReserved );
169
170     /* Tag current MODREF to prevent recursive loop */
171     wm->flags |= WINE_MODREF_MARKER;
172
173     /* Recursively attach all DLLs this one depends on */
174     for ( i = 0; retv && i < wm->nDeps; i++ )
175         if ( wm->deps[i] )
176             retv = MODULE_DllProcessAttach( wm->deps[i], lpReserved );
177
178     /* Call DLL entry point */
179     if ( retv )
180     {
181         retv = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
182         if ( retv )
183             wm->flags |= WINE_MODREF_PROCESS_ATTACHED;
184     }
185
186     /* Re-insert MODREF at head of list */
187     if ( retv && wm->prev )
188     {
189         wm->prev->next = wm->next;
190         if ( wm->next ) wm->next->prev = wm->prev;
191
192         wm->prev = NULL;
193         wm->next = MODULE_modref_list;
194         MODULE_modref_list = wm->next->prev = wm;
195     }
196
197     /* Remove recursion flag */
198     wm->flags &= ~WINE_MODREF_MARKER;
199
200     TRACE("(%s,%p) - END\n", wm->modname, lpReserved );
201
202  done:
203     RtlReleasePebLock();
204     return retv;
205 }
206
207 /*************************************************************************
208  *              MODULE_DllProcessDetach
209  * 
210  * Send DLL process detach notifications.  See the comment about calling 
211  * sequence at MODULE_DllProcessAttach.  Unless the bForceDetach flag
212  * is set, only DLLs with zero refcount are notified.
213  */
214 void MODULE_DllProcessDetach( BOOL bForceDetach, LPVOID lpReserved )
215 {
216     WINE_MODREF *wm;
217
218     RtlAcquirePebLock();
219     if (bForceDetach) process_detaching = 1;
220     do
221     {
222         for ( wm = MODULE_modref_list; wm; wm = wm->next )
223         {
224             /* Check whether to detach this DLL */
225             if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
226                 continue;
227             if ( wm->refCount > 0 && !bForceDetach )
228                 continue;
229
230             /* Call detach notification */
231             wm->flags &= ~WINE_MODREF_PROCESS_ATTACHED;
232             MODULE_InitDLL( wm, DLL_PROCESS_DETACH, lpReserved );
233
234             /* Restart at head of WINE_MODREF list, as entries might have
235                been added and/or removed while performing the call ... */
236             break;
237         }
238     } while ( wm );
239
240     RtlReleasePebLock();
241 }
242
243 /*************************************************************************
244  *              MODULE_DllThreadAttach
245  * 
246  * Send DLL thread attach notifications. These are sent in the
247  * reverse sequence of process detach notification.
248  *
249  */
250 void MODULE_DllThreadAttach( LPVOID lpReserved )
251 {
252     WINE_MODREF *wm;
253
254     /* don't do any attach calls if process is exiting */
255     if (process_detaching) return;
256     /* FIXME: there is still a race here */
257
258     RtlAcquirePebLock();
259
260     for ( wm = MODULE_modref_list; wm; wm = wm->next )
261         if ( !wm->next )
262             break;
263
264     for ( ; wm; wm = wm->prev )
265     {
266         if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
267             continue;
268         if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
269             continue;
270
271         MODULE_InitDLL( wm, DLL_THREAD_ATTACH, lpReserved );
272     }
273
274     RtlReleasePebLock();
275 }
276
277 /*************************************************************************
278  *              MODULE_DllThreadDetach
279  * 
280  * Send DLL thread detach notifications. These are sent in the
281  * same sequence as process detach notification.
282  *
283  */
284 void MODULE_DllThreadDetach( LPVOID lpReserved )
285 {
286     WINE_MODREF *wm;
287
288     /* don't do any detach calls if process is exiting */
289     if (process_detaching) return;
290     /* FIXME: there is still a race here */
291
292     RtlAcquirePebLock();
293
294     for ( wm = MODULE_modref_list; wm; wm = wm->next )
295     {
296         if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
297             continue;
298         if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
299             continue;
300
301         MODULE_InitDLL( wm, DLL_THREAD_DETACH, lpReserved );
302     }
303
304     RtlReleasePebLock();
305 }
306
307 /****************************************************************************
308  *              DisableThreadLibraryCalls (KERNEL32.74)
309  *
310  * Don't call DllEntryPoint for DLL_THREAD_{ATTACH,DETACH} if set.
311  */
312 BOOL WINAPI DisableThreadLibraryCalls( HMODULE hModule )
313 {
314     WINE_MODREF *wm;
315     BOOL retval = TRUE;
316
317     RtlAcquirePebLock();
318
319     wm = MODULE32_LookupHMODULE( hModule );
320     if ( !wm )
321         retval = FALSE;
322     else
323         wm->flags |= WINE_MODREF_NO_DLL_CALLS;
324
325     RtlReleasePebLock();
326
327     return retval;
328 }
329
330
331 /***********************************************************************
332  *           MODULE_CreateDummyModule
333  *
334  * Create a dummy NE module for Win32 or Winelib.
335  */
336 HMODULE MODULE_CreateDummyModule( LPCSTR filename, HMODULE module32 )
337 {
338     HMODULE hModule;
339     NE_MODULE *pModule;
340     SEGTABLEENTRY *pSegment;
341     char *pStr,*s;
342     unsigned int len;
343     const char* basename;
344     OFSTRUCT *ofs;
345     int of_size, size;
346
347     /* Extract base filename */
348     basename = strrchr(filename, '\\');
349     if (!basename) basename = filename;
350     else basename++;
351     len = strlen(basename);
352     if ((s = strchr(basename, '.'))) len = s - basename;
353
354     /* Allocate module */
355     of_size = sizeof(OFSTRUCT) - sizeof(ofs->szPathName)
356                     + strlen(filename) + 1;
357     size = sizeof(NE_MODULE) +
358                  /* loaded file info */
359                  ((of_size + 3) & ~3) + 
360                  /* segment table: DS,CS */
361                  2 * sizeof(SEGTABLEENTRY) +
362                  /* name table */
363                  len + 2 +
364                  /* several empty tables */
365                  8;
366
367     hModule = GlobalAlloc16( GMEM_MOVEABLE | GMEM_ZEROINIT, size );
368     if (!hModule) return (HMODULE)11;  /* invalid exe */
369
370     FarSetOwner16( hModule, hModule );
371     pModule = (NE_MODULE *)GlobalLock16( hModule );
372
373     /* Set all used entries */
374     pModule->magic            = IMAGE_OS2_SIGNATURE;
375     pModule->count            = 1;
376     pModule->next             = 0;
377     pModule->flags            = 0;
378     pModule->dgroup           = 0;
379     pModule->ss               = 1;
380     pModule->cs               = 2;
381     pModule->heap_size        = 0;
382     pModule->stack_size       = 0;
383     pModule->seg_count        = 2;
384     pModule->modref_count     = 0;
385     pModule->nrname_size      = 0;
386     pModule->fileinfo         = sizeof(NE_MODULE);
387     pModule->os_flags         = NE_OSFLAGS_WINDOWS;
388     pModule->self             = hModule;
389     pModule->module32         = module32;
390
391     /* Set version and flags */
392     if (module32)
393     {
394         pModule->expected_version =
395             ((PE_HEADER(module32)->OptionalHeader.MajorSubsystemVersion & 0xff) << 8 ) |
396              (PE_HEADER(module32)->OptionalHeader.MinorSubsystemVersion & 0xff);
397         pModule->flags |= NE_FFLAGS_WIN32;
398         if (PE_HEADER(module32)->FileHeader.Characteristics & IMAGE_FILE_DLL)
399             pModule->flags |= NE_FFLAGS_LIBMODULE | NE_FFLAGS_SINGLEDATA;
400     }
401
402     /* Set loaded file information */
403     ofs = (OFSTRUCT *)(pModule + 1);
404     memset( ofs, 0, of_size );
405     ofs->cBytes = of_size < 256 ? of_size : 255;   /* FIXME */
406     strcpy( ofs->szPathName, filename );
407
408     pSegment = (SEGTABLEENTRY*)((char*)(pModule + 1) + ((of_size + 3) & ~3));
409     pModule->seg_table = (int)pSegment - (int)pModule;
410     /* Data segment */
411     pSegment->size    = 0;
412     pSegment->flags   = NE_SEGFLAGS_DATA;
413     pSegment->minsize = 0x1000;
414     pSegment++;
415     /* Code segment */
416     pSegment->flags   = 0;
417     pSegment++;
418
419     /* Module name */
420     pStr = (char *)pSegment;
421     pModule->name_table = (int)pStr - (int)pModule;
422     assert(len<256);
423     *pStr = len;
424     lstrcpynA( pStr+1, basename, len+1 );
425     pStr += len+2;
426
427     /* All tables zero terminated */
428     pModule->res_table = pModule->import_table = pModule->entry_table =
429                 (int)pStr - (int)pModule;
430
431     NE_RegisterModule( pModule );
432     return hModule;
433 }
434
435
436 /**********************************************************************
437  *          MODULE_FindModule
438  *
439  * Find a (loaded) win32 module depending on path
440  *
441  * RETURNS
442  *      the module handle if found
443  *      0 if not
444  */
445 WINE_MODREF *MODULE_FindModule(
446         LPCSTR path     /* [in] pathname of module/library to be found */
447 ) {
448     WINE_MODREF *wm;
449     char dllname[260], *p;
450
451     /* Append .DLL to name if no extension present */
452     strcpy( dllname, path );
453     if (!(p = strrchr( dllname, '.')) || strchr( p, '/' ) || strchr( p, '\\'))
454             strcat( dllname, ".DLL" );
455
456     for ( wm = MODULE_modref_list; wm; wm = wm->next )
457     {
458         if ( !FILE_strcasecmp( dllname, wm->modname ) )
459             break;
460         if ( !FILE_strcasecmp( dllname, wm->filename ) )
461             break;
462         if ( !FILE_strcasecmp( dllname, wm->short_modname ) )
463             break;
464         if ( !FILE_strcasecmp( dllname, wm->short_filename ) )
465             break;
466     }
467
468     return wm;
469 }
470
471
472 /* Check whether a file is an OS/2 or a very old Windows executable
473  * by testing on import of KERNEL.
474  *
475  * FIXME: is reading the module imports the only way of discerning
476  *        old Windows binaries from OS/2 ones ? At least it seems so...
477  */
478 static DWORD MODULE_Decide_OS2_OldWin(HANDLE hfile, IMAGE_DOS_HEADER *mz, IMAGE_OS2_HEADER *ne)
479 {
480     DWORD currpos = SetFilePointer( hfile, 0, NULL, SEEK_CUR);
481     DWORD type = SCS_OS216_BINARY;
482     LPWORD modtab = NULL;
483     LPSTR nametab = NULL;
484     DWORD len;
485     int i;
486
487     /* read modref table */
488     if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_modtab, NULL, SEEK_SET ) == -1)
489       || (!(modtab = HeapAlloc( GetProcessHeap(), 0, ne->ne_cmod*sizeof(WORD))))
490       || (!(ReadFile(hfile, modtab, ne->ne_cmod*sizeof(WORD), &len, NULL)))
491       || (len != ne->ne_cmod*sizeof(WORD)) )
492         goto broken;
493
494     /* read imported names table */
495     if ( (SetFilePointer( hfile, mz->e_lfanew + ne->ne_imptab, NULL, SEEK_SET ) == -1)
496       || (!(nametab = HeapAlloc( GetProcessHeap(), 0, ne->ne_enttab - ne->ne_imptab)))
497       || (!(ReadFile(hfile, nametab, ne->ne_enttab - ne->ne_imptab, &len, NULL)))
498       || (len != ne->ne_enttab - ne->ne_imptab) )
499         goto broken;
500
501     for (i=0; i < ne->ne_cmod; i++)
502     {
503         LPSTR module = &nametab[modtab[i]];
504         TRACE("modref: %.*s\n", module[0], &module[1]);
505         if (!(strncmp(&module[1], "KERNEL", module[0])))
506         { /* very old Windows file */
507             MESSAGE("This seems to be a very old (pre-3.0) Windows executable. Expect crashes, especially if this is a real-mode binary !\n");
508             type = SCS_WOW_BINARY;
509             goto good;
510         }
511     }
512
513 broken:
514     ERR("Hmm, an error occurred. Is this binary file broken ?\n");
515
516 good:
517     HeapFree( GetProcessHeap(), 0, modtab);
518     HeapFree( GetProcessHeap(), 0, nametab);
519     SetFilePointer( hfile, currpos, NULL, SEEK_SET); /* restore filepos */
520     return type;
521 }
522
523 /***********************************************************************
524  *           MODULE_GetBinaryType
525  *
526  * The GetBinaryType function determines whether a file is executable
527  * or not and if it is it returns what type of executable it is.
528  * The type of executable is a property that determines in which
529  * subsystem an executable file runs under.
530  *
531  * Binary types returned:
532  * SCS_32BIT_BINARY: A Win32 based application
533  * SCS_DOS_BINARY: An MS-Dos based application
534  * SCS_WOW_BINARY: A Win16 based application
535  * SCS_PIF_BINARY: A PIF file that executes an MS-Dos based app
536  * SCS_POSIX_BINARY: A POSIX based application ( Not implemented )
537  * SCS_OS216_BINARY: A 16bit OS/2 based application
538  *
539  * Returns TRUE if the file is an executable in which case
540  * the value pointed by lpBinaryType is set.
541  * Returns FALSE if the file is not an executable or if the function fails.
542  *
543  * To do so it opens the file and reads in the header information
544  * if the extended header information is not present it will
545  * assume that the file is a DOS executable.
546  * If the extended header information is present it will
547  * determine if the file is a 16 or 32 bit Windows executable
548  * by check the flags in the header.
549  *
550  * Note that .COM and .PIF files are only recognized by their
551  * file name extension; but Windows does it the same way ...
552  */
553 static BOOL MODULE_GetBinaryType( HANDLE hfile, LPCSTR filename, LPDWORD lpBinaryType )
554 {
555     IMAGE_DOS_HEADER mz_header;
556     char magic[4], *ptr;
557     DWORD len;
558
559     /* Seek to the start of the file and read the DOS header information.
560      */
561     if (    SetFilePointer( hfile, 0, NULL, SEEK_SET ) != -1  
562          && ReadFile( hfile, &mz_header, sizeof(mz_header), &len, NULL )
563          && len == sizeof(mz_header) )
564     {
565         /* Now that we have the header check the e_magic field
566          * to see if this is a dos image.
567          */
568         if ( mz_header.e_magic == IMAGE_DOS_SIGNATURE )
569         {
570             BOOL lfanewValid = FALSE;
571             /* We do have a DOS image so we will now try to seek into
572              * the file by the amount indicated by the field
573              * "Offset to extended header" and read in the
574              * "magic" field information at that location.
575              * This will tell us if there is more header information
576              * to read or not.
577              */
578             /* But before we do we will make sure that header
579              * structure encompasses the "Offset to extended header"
580              * field.
581              */
582             if ( (mz_header.e_cparhdr<<4) >= sizeof(IMAGE_DOS_HEADER) )
583                 if ( ( mz_header.e_crlc == 0 ) ||
584                      ( mz_header.e_lfarlc >= sizeof(IMAGE_DOS_HEADER) ) )
585                     if (    mz_header.e_lfanew >= sizeof(IMAGE_DOS_HEADER)
586                          && SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET ) != -1  
587                          && ReadFile( hfile, magic, sizeof(magic), &len, NULL )
588                          && len == sizeof(magic) )
589                         lfanewValid = TRUE;
590
591             if ( !lfanewValid )
592             {
593                 /* If we cannot read this "extended header" we will
594                  * assume that we have a simple DOS executable.
595                  */
596                 *lpBinaryType = SCS_DOS_BINARY;
597                 return TRUE;
598             }
599             else
600             {
601                 /* Reading the magic field succeeded so
602                  * we will try to determine what type it is.
603                  */
604                 if ( *(DWORD*)magic      == IMAGE_NT_SIGNATURE )
605                 {
606                     /* This is an NT signature.
607                      */
608                     *lpBinaryType = SCS_32BIT_BINARY;
609                     return TRUE;
610                 }
611                 else if ( *(WORD*)magic == IMAGE_OS2_SIGNATURE )
612                 {
613                     /* The IMAGE_OS2_SIGNATURE indicates that the
614                      * "extended header is a Windows executable (NE)
615                      * header."  This can mean either a 16-bit OS/2
616                      * or a 16-bit Windows or even a DOS program 
617                      * (running under a DOS extender).  To decide
618                      * which, we'll have to read the NE header.
619                      */
620
621                      IMAGE_OS2_HEADER ne;
622                      if (    SetFilePointer( hfile, mz_header.e_lfanew, NULL, SEEK_SET ) != -1  
623                           && ReadFile( hfile, &ne, sizeof(ne), &len, NULL )
624                           && len == sizeof(ne) )
625                      {
626                          switch ( ne.ne_exetyp )
627                          {
628                          case 2:  *lpBinaryType = SCS_WOW_BINARY;   return TRUE;
629                          case 5:  *lpBinaryType = SCS_DOS_BINARY;   return TRUE;
630                          default: *lpBinaryType =
631                                   MODULE_Decide_OS2_OldWin(hfile, &mz_header, &ne);
632                                   return TRUE;
633                          }
634                      }
635                      /* Couldn't read header, so abort. */
636                      return FALSE;
637                 }
638                 else
639                 {
640                     /* Unknown extended header, but this file is nonetheless
641                        DOS-executable.
642                      */
643                     *lpBinaryType = SCS_DOS_BINARY;
644                     return TRUE;
645                 }
646             }
647         }
648     }
649
650     /* If we get here, we don't even have a correct MZ header.
651      * Try to check the file extension for known types ...
652      */
653     ptr = strrchr( filename, '.' );
654     if ( ptr && !strchr( ptr, '\\' ) && !strchr( ptr, '/' ) )
655     {
656         if ( !FILE_strcasecmp( ptr, ".COM" ) )
657         {
658             *lpBinaryType = SCS_DOS_BINARY;
659             return TRUE;
660         }
661
662         if ( !FILE_strcasecmp( ptr, ".PIF" ) )
663         {
664             *lpBinaryType = SCS_PIF_BINARY;
665             return TRUE;
666         }
667     }
668
669     return FALSE;
670 }
671
672 /***********************************************************************
673  *             GetBinaryTypeA                     [KERNEL32.280]
674  */
675 BOOL WINAPI GetBinaryTypeA( LPCSTR lpApplicationName, LPDWORD lpBinaryType )
676 {
677     BOOL ret = FALSE;
678     HANDLE hfile;
679
680     TRACE_(win32)("%s\n", lpApplicationName );
681
682     /* Sanity check.
683      */
684     if ( lpApplicationName == NULL || lpBinaryType == NULL )
685         return FALSE;
686
687     /* Open the file indicated by lpApplicationName for reading.
688      */
689     hfile = CreateFileA( lpApplicationName, GENERIC_READ, FILE_SHARE_READ,
690                          NULL, OPEN_EXISTING, 0, 0 );
691     if ( hfile == INVALID_HANDLE_VALUE )
692         return FALSE;
693
694     /* Check binary type
695      */
696     ret = MODULE_GetBinaryType( hfile, lpApplicationName, lpBinaryType );
697
698     /* Close the file.
699      */
700     CloseHandle( hfile );
701
702     return ret;
703 }
704
705 /***********************************************************************
706  *             GetBinaryTypeW                      [KERNEL32.281]
707  */
708 BOOL WINAPI GetBinaryTypeW( LPCWSTR lpApplicationName, LPDWORD lpBinaryType )
709 {
710     BOOL ret = FALSE;
711     LPSTR strNew = NULL;
712
713     TRACE_(win32)("%s\n", debugstr_w(lpApplicationName) );
714
715     /* Sanity check.
716      */
717     if ( lpApplicationName == NULL || lpBinaryType == NULL )
718         return FALSE;
719
720     /* Convert the wide string to a ascii string.
721      */
722     strNew = HEAP_strdupWtoA( GetProcessHeap(), 0, lpApplicationName );
723
724     if ( strNew != NULL )
725     {
726         ret = GetBinaryTypeA( strNew, lpBinaryType );
727
728         /* Free the allocated string.
729          */
730         HeapFree( GetProcessHeap(), 0, strNew );
731     }
732
733     return ret;
734 }
735
736
737 /***********************************************************************
738  *           WinExec16   (KERNEL.166)
739  */
740 HINSTANCE16 WINAPI WinExec16( LPCSTR lpCmdLine, UINT16 nCmdShow )
741 {
742     LPCSTR p, args = NULL;
743     LPCSTR name_beg, name_end;
744     LPSTR name, cmdline;
745     int arglen;
746     HINSTANCE16 ret;
747     char buffer[MAX_PATH];
748
749     if (*lpCmdLine == '"') /* has to be only one and only at beginning ! */
750     {
751       name_beg = lpCmdLine+1;
752       p = strchr ( lpCmdLine+1, '"' );
753       if (p)
754       {
755           name_end = p;
756           args = strchr ( p, ' ' );
757       }
758       else /* yes, even valid with trailing '"' missing */
759           name_end = lpCmdLine+strlen(lpCmdLine);
760     }
761     else 
762     {
763       name_beg = lpCmdLine;
764       args = strchr( lpCmdLine, ' ' );
765       name_end = args ? args : lpCmdLine+strlen(lpCmdLine);
766     }
767
768     if ((name_beg == lpCmdLine) && (!args))
769     { /* just use the original cmdline string as file name */
770         name = (LPSTR)lpCmdLine;
771     }
772     else
773     {
774         if (!(name = HeapAlloc( GetProcessHeap(), 0, name_end - name_beg + 1 )))
775             return ERROR_NOT_ENOUGH_MEMORY;
776         memcpy( name, name_beg, name_end - name_beg );
777         name[name_end - name_beg] = '\0';
778     }
779
780     if (args)
781     {
782         args++;
783         arglen = strlen(args);
784         cmdline = SEGPTR_ALLOC( 2 + arglen );
785         cmdline[0] = (BYTE)arglen;
786         strcpy( cmdline + 1, args );
787     }
788     else
789     {
790         cmdline = SEGPTR_ALLOC( 2 );
791         cmdline[0] = cmdline[1] = 0;
792     }
793
794     TRACE("name: '%s', cmdline: '%.*s'\n", name, cmdline[0], &cmdline[1]);
795
796     if (SearchPathA( NULL, name, ".exe", sizeof(buffer), buffer, NULL ))
797     {
798         LOADPARAMS16 params;
799         WORD *showCmd = SEGPTR_ALLOC( 2*sizeof(WORD) );
800         showCmd[0] = 2;
801         showCmd[1] = nCmdShow;
802
803         params.hEnvironment = 0;
804         params.cmdLine = SEGPTR_GET(cmdline);
805         params.showCmd = SEGPTR_GET(showCmd);
806         params.reserved = 0;
807
808         ret = LoadModule16( buffer, &params );
809
810         SEGPTR_FREE( showCmd );
811         SEGPTR_FREE( cmdline );
812     }
813     else ret = GetLastError();
814
815     if (name != lpCmdLine) HeapFree( GetProcessHeap(), 0, name );
816
817     if (ret == 21)  /* 32-bit module */
818     {
819         DWORD count;
820         ReleaseThunkLock( &count );
821         ret = WinExec( lpCmdLine, nCmdShow );
822         RestoreThunkLock( count );
823     }
824     return ret;
825 }
826
827 /***********************************************************************
828  *           WinExec   (KERNEL32.566)
829  */
830 HINSTANCE WINAPI WinExec( LPCSTR lpCmdLine, UINT nCmdShow )
831 {
832     PROCESS_INFORMATION info;
833     STARTUPINFOA startup;
834     HINSTANCE hInstance;
835     char *cmdline;
836
837     memset( &startup, 0, sizeof(startup) );
838     startup.cb = sizeof(startup);
839     startup.dwFlags = STARTF_USESHOWWINDOW;
840     startup.wShowWindow = nCmdShow;
841
842     /* cmdline needs to be writeable for CreateProcess */
843     if (!(cmdline = HEAP_strdupA( GetProcessHeap(), 0, lpCmdLine ))) return 0;
844
845     if (CreateProcessA( NULL, cmdline, NULL, NULL, FALSE,
846                         0, NULL, NULL, &startup, &info ))
847     {
848         /* Give 30 seconds to the app to come up */
849         if (Callout.WaitForInputIdle &&
850             Callout.WaitForInputIdle( info.hProcess, 30000 ) == 0xFFFFFFFF)
851             WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
852         hInstance = 33;
853         /* Close off the handles */
854         CloseHandle( info.hThread );
855         CloseHandle( info.hProcess );
856     }
857     else if ((hInstance = GetLastError()) >= 32)
858     {
859         FIXME("Strange error set by CreateProcess: %d\n", hInstance );
860         hInstance = 11;
861     }
862     HeapFree( GetProcessHeap(), 0, cmdline );
863     return hInstance;
864 }
865
866 /**********************************************************************
867  *          LoadModule    (KERNEL32.499)
868  */
869 HINSTANCE WINAPI LoadModule( LPCSTR name, LPVOID paramBlock ) 
870 {
871     LOADPARAMS *params = (LOADPARAMS *)paramBlock;
872     PROCESS_INFORMATION info;
873     STARTUPINFOA startup;
874     HINSTANCE hInstance;
875     LPSTR cmdline, p;
876     char filename[MAX_PATH];
877     BYTE len;
878
879     if (!name) return ERROR_FILE_NOT_FOUND;
880
881     if (!SearchPathA( NULL, name, ".exe", sizeof(filename), filename, NULL ) &&
882         !SearchPathA( NULL, name, NULL, sizeof(filename), filename, NULL ))
883         return GetLastError();
884
885     len = (BYTE)params->lpCmdLine[0];
886     if (!(cmdline = HeapAlloc( GetProcessHeap(), 0, strlen(filename) + len + 2 )))
887         return ERROR_NOT_ENOUGH_MEMORY;
888
889     strcpy( cmdline, filename );
890     p = cmdline + strlen(cmdline);
891     *p++ = ' ';
892     memcpy( p, params->lpCmdLine + 1, len );
893     p[len] = 0;
894
895     memset( &startup, 0, sizeof(startup) );
896     startup.cb = sizeof(startup);
897     if (params->lpCmdShow)
898     {
899         startup.dwFlags = STARTF_USESHOWWINDOW;
900         startup.wShowWindow = params->lpCmdShow[1];
901     }
902     
903     if (CreateProcessA( filename, cmdline, NULL, NULL, FALSE, 0,
904                         params->lpEnvAddress, NULL, &startup, &info ))
905     {
906         /* Give 30 seconds to the app to come up */
907         if (Callout.WaitForInputIdle &&
908             Callout.WaitForInputIdle( info.hProcess, 30000 ) ==  0xFFFFFFFF )
909             WARN("WaitForInputIdle failed: Error %ld\n", GetLastError() );
910         hInstance = 33;
911         /* Close off the handles */
912         CloseHandle( info.hThread );
913         CloseHandle( info.hProcess );
914     }
915     else if ((hInstance = GetLastError()) >= 32)
916     {
917         FIXME("Strange error set by CreateProcess: %d\n", hInstance );
918         hInstance = 11;
919     }
920
921     HeapFree( GetProcessHeap(), 0, cmdline );
922     return hInstance;
923 }
924
925
926 /*************************************************************************
927  *               get_file_name
928  *
929  * Helper for CreateProcess: retrieve the file name to load from the
930  * app name and command line. Store the file name in buffer, and
931  * return a possibly modified command line.
932  */
933 static LPSTR get_file_name( LPCSTR appname, LPSTR cmdline, LPSTR buffer, int buflen )
934 {
935     char *name, *pos, *ret = NULL;
936     const char *p;
937
938     /* if we have an app name, everything is easy */
939
940     if (appname)
941     {
942         /* use the unmodified app name as file name */
943         lstrcpynA( buffer, appname, buflen );
944         if (!(ret = cmdline))
945         {
946             /* no command-line, create one */
947             if ((ret = HeapAlloc( GetProcessHeap(), 0, strlen(appname) + 3 )))
948                 sprintf( ret, "\"%s\"", appname );
949         }
950         return ret;
951     }
952
953     if (!cmdline)
954     {
955         SetLastError( ERROR_INVALID_PARAMETER );
956         return NULL;
957     }
958
959     /* first check for a quoted file name */
960
961     if ((cmdline[0] == '"') && ((p = strchr( cmdline + 1, '"' ))))
962     {
963         int len = p - cmdline - 1;
964         /* extract the quoted portion as file name */
965         if (!(name = HeapAlloc( GetProcessHeap(), 0, len + 1 ))) return NULL;
966         memcpy( name, cmdline + 1, len );
967         name[len] = 0;
968
969         if (SearchPathA( NULL, name, ".exe", buflen, buffer, NULL ) ||
970             SearchPathA( NULL, name, NULL, buflen, buffer, NULL ))
971             ret = cmdline;  /* no change necessary */
972         goto done;
973     }
974
975     /* now try the command-line word by word */
976
977     if (!(name = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 1 ))) return NULL;
978     pos = name;
979     p = cmdline;
980
981     while (*p)
982     {
983         do *pos++ = *p++; while (*p && *p != ' ');
984         *pos = 0;
985         TRACE("trying '%s'\n", name );
986         if (SearchPathA( NULL, name, ".exe", buflen, buffer, NULL ) ||
987             SearchPathA( NULL, name, NULL, buflen, buffer, NULL ))
988         {
989             ret = cmdline;
990             break;
991         }
992     }
993
994     if (!ret || !strchr( name, ' ' )) goto done;  /* no change necessary */
995
996     /* now build a new command-line with quotes */
997
998     if (!(ret = HeapAlloc( GetProcessHeap(), 0, strlen(cmdline) + 3 ))) goto done;
999     sprintf( ret, "\"%s\"%s", name, p );
1000
1001  done:
1002     HeapFree( GetProcessHeap(), 0, name );
1003     return ret;
1004 }
1005
1006
1007 /**********************************************************************
1008  *       CreateProcessA          (KERNEL32.171)
1009  */
1010 BOOL WINAPI CreateProcessA( LPCSTR lpApplicationName, LPSTR lpCommandLine, 
1011                             LPSECURITY_ATTRIBUTES lpProcessAttributes,
1012                             LPSECURITY_ATTRIBUTES lpThreadAttributes,
1013                             BOOL bInheritHandles, DWORD dwCreationFlags,
1014                             LPVOID lpEnvironment, LPCSTR lpCurrentDirectory,
1015                             LPSTARTUPINFOA lpStartupInfo,
1016                             LPPROCESS_INFORMATION lpProcessInfo )
1017 {
1018     BOOL retv = FALSE;
1019     HANDLE hFile;
1020     DWORD type;
1021     char name[MAX_PATH];
1022     LPSTR tidy_cmdline;
1023
1024     /* Process the AppName and/or CmdLine to get module name and path */
1025
1026     TRACE("app '%s' cmdline '%s'\n", lpApplicationName, lpCommandLine );
1027
1028     if (!(tidy_cmdline = get_file_name( lpApplicationName, lpCommandLine, name, sizeof(name) )))
1029         return FALSE;
1030
1031     /* Warn if unsupported features are used */
1032
1033     if (dwCreationFlags & DETACHED_PROCESS)
1034         FIXME("(%s,...): DETACHED_PROCESS ignored\n", name);
1035     if (dwCreationFlags & CREATE_NEW_CONSOLE)
1036         FIXME("(%s,...): CREATE_NEW_CONSOLE ignored\n", name);
1037     if (dwCreationFlags & NORMAL_PRIORITY_CLASS)
1038         FIXME("(%s,...): NORMAL_PRIORITY_CLASS ignored\n", name);
1039     if (dwCreationFlags & IDLE_PRIORITY_CLASS)
1040         FIXME("(%s,...): IDLE_PRIORITY_CLASS ignored\n", name);
1041     if (dwCreationFlags & HIGH_PRIORITY_CLASS)
1042         FIXME("(%s,...): HIGH_PRIORITY_CLASS ignored\n", name);
1043     if (dwCreationFlags & REALTIME_PRIORITY_CLASS)
1044         FIXME("(%s,...): REALTIME_PRIORITY_CLASS ignored\n", name);
1045     if (dwCreationFlags & CREATE_NEW_PROCESS_GROUP)
1046         FIXME("(%s,...): CREATE_NEW_PROCESS_GROUP ignored\n", name);
1047     if (dwCreationFlags & CREATE_UNICODE_ENVIRONMENT)
1048         FIXME("(%s,...): CREATE_UNICODE_ENVIRONMENT ignored\n", name);
1049     if (dwCreationFlags & CREATE_SEPARATE_WOW_VDM)
1050         FIXME("(%s,...): CREATE_SEPARATE_WOW_VDM ignored\n", name);
1051     if (dwCreationFlags & CREATE_SHARED_WOW_VDM)
1052         FIXME("(%s,...): CREATE_SHARED_WOW_VDM ignored\n", name);
1053     if (dwCreationFlags & CREATE_DEFAULT_ERROR_MODE)
1054         FIXME("(%s,...): CREATE_DEFAULT_ERROR_MODE ignored\n", name);
1055     if (dwCreationFlags & CREATE_NO_WINDOW)
1056         FIXME("(%s,...): CREATE_NO_WINDOW ignored\n", name);
1057     if (dwCreationFlags & PROFILE_USER)
1058         FIXME("(%s,...): PROFILE_USER ignored\n", name);
1059     if (dwCreationFlags & PROFILE_KERNEL)
1060         FIXME("(%s,...): PROFILE_KERNEL ignored\n", name);
1061     if (dwCreationFlags & PROFILE_SERVER)
1062         FIXME("(%s,...): PROFILE_SERVER ignored\n", name);
1063     if (lpStartupInfo->lpDesktop)
1064         FIXME("(%s,...): lpStartupInfo->lpDesktop %s ignored\n", 
1065                       name, lpStartupInfo->lpDesktop);
1066     if (lpStartupInfo->lpTitle)
1067         FIXME("(%s,...): lpStartupInfo->lpTitle %s ignored\n", 
1068                       name, lpStartupInfo->lpTitle);
1069     if (lpStartupInfo->dwFlags & STARTF_USECOUNTCHARS)
1070         FIXME("(%s,...): STARTF_USECOUNTCHARS (%ld,%ld) ignored\n", 
1071                       name, lpStartupInfo->dwXCountChars, lpStartupInfo->dwYCountChars);
1072     if (lpStartupInfo->dwFlags & STARTF_USEFILLATTRIBUTE)
1073         FIXME("(%s,...): STARTF_USEFILLATTRIBUTE %lx ignored\n", 
1074                       name, lpStartupInfo->dwFillAttribute);
1075     if (lpStartupInfo->dwFlags & STARTF_RUNFULLSCREEN)
1076         FIXME("(%s,...): STARTF_RUNFULLSCREEN ignored\n", name);
1077     if (lpStartupInfo->dwFlags & STARTF_FORCEONFEEDBACK)
1078         FIXME("(%s,...): STARTF_FORCEONFEEDBACK ignored\n", name);
1079     if (lpStartupInfo->dwFlags & STARTF_FORCEOFFFEEDBACK)
1080         FIXME("(%s,...): STARTF_FORCEOFFFEEDBACK ignored\n", name);
1081     if (lpStartupInfo->dwFlags & STARTF_USEHOTKEY)
1082         FIXME("(%s,...): STARTF_USEHOTKEY ignored\n", name);
1083
1084     /* Open file and determine executable type */
1085
1086     hFile = CreateFileA( name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0 );
1087     if (hFile == INVALID_HANDLE_VALUE) goto done;
1088
1089     if ( !MODULE_GetBinaryType( hFile, name, &type ) )
1090     {
1091         CloseHandle( hFile );
1092         retv = PROCESS_Create( 0, name, tidy_cmdline, lpEnvironment, 
1093                                lpProcessAttributes, lpThreadAttributes,
1094                                bInheritHandles, dwCreationFlags,
1095                                lpStartupInfo, lpProcessInfo, lpCurrentDirectory );
1096         goto done;
1097     }
1098
1099     /* Create process */
1100
1101     switch ( type )
1102     {
1103     case SCS_32BIT_BINARY:
1104     case SCS_WOW_BINARY:
1105     case SCS_DOS_BINARY:
1106         retv = PROCESS_Create( hFile, name, tidy_cmdline, lpEnvironment, 
1107                                lpProcessAttributes, lpThreadAttributes,
1108                                bInheritHandles, dwCreationFlags,
1109                                lpStartupInfo, lpProcessInfo, lpCurrentDirectory);
1110         break;
1111
1112     case SCS_PIF_BINARY:
1113     case SCS_POSIX_BINARY:
1114     case SCS_OS216_BINARY:
1115         FIXME("Unsupported executable type: %ld\n", type );
1116         /* fall through */
1117
1118     default:
1119         SetLastError( ERROR_BAD_FORMAT );
1120         break;
1121     }
1122     CloseHandle( hFile );
1123
1124  done:
1125     if (tidy_cmdline != lpCommandLine) HeapFree( GetProcessHeap(), 0, tidy_cmdline );
1126     return retv;
1127 }
1128
1129 /**********************************************************************
1130  *       CreateProcessW          (KERNEL32.172)
1131  * NOTES
1132  *  lpReserved is not converted
1133  */
1134 BOOL WINAPI CreateProcessW( LPCWSTR lpApplicationName, LPWSTR lpCommandLine, 
1135                                 LPSECURITY_ATTRIBUTES lpProcessAttributes,
1136                                 LPSECURITY_ATTRIBUTES lpThreadAttributes,
1137                                 BOOL bInheritHandles, DWORD dwCreationFlags,
1138                                 LPVOID lpEnvironment, LPCWSTR lpCurrentDirectory,
1139                                 LPSTARTUPINFOW lpStartupInfo,
1140                                 LPPROCESS_INFORMATION lpProcessInfo )
1141 {   BOOL ret;
1142     STARTUPINFOA StartupInfoA;
1143     
1144     LPSTR lpApplicationNameA = HEAP_strdupWtoA (GetProcessHeap(),0,lpApplicationName);
1145     LPSTR lpCommandLineA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCommandLine);
1146     LPSTR lpCurrentDirectoryA = HEAP_strdupWtoA (GetProcessHeap(),0,lpCurrentDirectory);
1147
1148     memcpy (&StartupInfoA, lpStartupInfo, sizeof(STARTUPINFOA));
1149     StartupInfoA.lpDesktop = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpDesktop);
1150     StartupInfoA.lpTitle = HEAP_strdupWtoA (GetProcessHeap(),0,lpStartupInfo->lpTitle);
1151
1152     TRACE_(win32)("(%s,%s,...)\n", debugstr_w(lpApplicationName), debugstr_w(lpCommandLine));
1153
1154     if (lpStartupInfo->lpReserved)
1155       FIXME_(win32)("StartupInfo.lpReserved is used, please report (%s)\n", debugstr_w(lpStartupInfo->lpReserved));
1156       
1157     ret = CreateProcessA(  lpApplicationNameA,  lpCommandLineA, 
1158                              lpProcessAttributes, lpThreadAttributes,
1159                              bInheritHandles, dwCreationFlags,
1160                              lpEnvironment, lpCurrentDirectoryA,
1161                              &StartupInfoA, lpProcessInfo );
1162
1163     HeapFree( GetProcessHeap(), 0, lpCurrentDirectoryA );
1164     HeapFree( GetProcessHeap(), 0, lpCommandLineA );
1165     HeapFree( GetProcessHeap(), 0, StartupInfoA.lpDesktop );
1166     HeapFree( GetProcessHeap(), 0, StartupInfoA.lpTitle );
1167
1168     return ret;
1169 }
1170
1171 /***********************************************************************
1172  *              GetModuleHandleA         (KERNEL32.237)
1173  */
1174 HMODULE WINAPI GetModuleHandleA(LPCSTR module)
1175 {
1176     WINE_MODREF *wm;
1177
1178     if ( module == NULL )
1179         wm = exe_modref;
1180     else
1181         wm = MODULE_FindModule( module );
1182
1183     return wm? wm->module : 0;
1184 }
1185
1186 /***********************************************************************
1187  *              GetModuleHandleW
1188  */
1189 HMODULE WINAPI GetModuleHandleW(LPCWSTR module)
1190 {
1191     HMODULE hModule;
1192     LPSTR modulea = HEAP_strdupWtoA( GetProcessHeap(), 0, module );
1193     hModule = GetModuleHandleA( modulea );
1194     HeapFree( GetProcessHeap(), 0, modulea );
1195     return hModule;
1196 }
1197
1198
1199 /***********************************************************************
1200  *              GetModuleFileNameA      (KERNEL32.235)
1201  *
1202  * GetModuleFileNameA seems to *always* return the long path;
1203  * it's only GetModuleFileName16 that decides between short/long path
1204  * by checking if exe version >= 4.0.
1205  * (SDK docu doesn't mention this)
1206  */
1207 DWORD WINAPI GetModuleFileNameA( 
1208         HMODULE hModule,        /* [in] module handle (32bit) */
1209         LPSTR lpFileName,       /* [out] filenamebuffer */
1210         DWORD size )            /* [in] size of filenamebuffer */
1211 {
1212     WINE_MODREF *wm;
1213
1214     RtlAcquirePebLock();
1215
1216     lpFileName[0] = 0;
1217     if ((wm = MODULE32_LookupHMODULE( hModule )))
1218         lstrcpynA( lpFileName, wm->filename, size );
1219
1220     RtlReleasePebLock();
1221     TRACE("%s\n", lpFileName );
1222     return strlen(lpFileName);
1223 }                   
1224  
1225
1226 /***********************************************************************
1227  *              GetModuleFileNameW      (KERNEL32.236)
1228  */
1229 DWORD WINAPI GetModuleFileNameW( HMODULE hModule, LPWSTR lpFileName,
1230                                    DWORD size )
1231 {
1232     LPSTR fnA = (char*)HeapAlloc( GetProcessHeap(), 0, size );
1233     DWORD res = GetModuleFileNameA( hModule, fnA, size );
1234     if (size > 0 && !MultiByteToWideChar( CP_ACP, 0, fnA, -1, lpFileName, size ))
1235         lpFileName[size-1] = 0;
1236     HeapFree( GetProcessHeap(), 0, fnA );
1237     return res;
1238 }
1239
1240
1241 /***********************************************************************
1242  *           LoadLibraryExA   (KERNEL32)
1243  */
1244 HMODULE WINAPI LoadLibraryExA(LPCSTR libname, HANDLE hfile, DWORD flags)
1245 {
1246         WINE_MODREF *wm;
1247
1248         if(!libname)
1249         {
1250                 SetLastError(ERROR_INVALID_PARAMETER);
1251                 return 0;
1252         }
1253
1254         if (flags & LOAD_LIBRARY_AS_DATAFILE)
1255         {
1256             char filename[256];
1257             HANDLE hFile;
1258             HMODULE hmod = 0;
1259
1260             if (!SearchPathA( NULL, libname, ".dll", sizeof(filename), filename, NULL ))
1261                 return 0;
1262             /* FIXME: maybe we should use the hfile parameter instead */
1263             hFile = CreateFileA( filename, GENERIC_READ, FILE_SHARE_READ,
1264                                  NULL, OPEN_EXISTING, 0, 0 );
1265             if (hFile != INVALID_HANDLE_VALUE)
1266             {
1267                 hmod = PE_LoadImage( hFile, filename, flags );
1268                 CloseHandle( hFile );
1269             }
1270             return hmod;
1271         }
1272
1273         RtlAcquirePebLock();
1274
1275         wm = MODULE_LoadLibraryExA( libname, hfile, flags );
1276         if ( wm )
1277         {
1278                 if ( !MODULE_DllProcessAttach( wm, NULL ) )
1279                 {
1280                         WARN_(module)("Attach failed for module '%s', \n", libname);
1281                         MODULE_FreeLibrary(wm);
1282                         SetLastError(ERROR_DLL_INIT_FAILED);
1283                         wm = NULL;
1284                 }
1285         }
1286
1287         RtlReleasePebLock();
1288         return wm ? wm->module : 0;
1289 }
1290
1291 /***********************************************************************
1292  *      MODULE_LoadLibraryExA   (internal)
1293  *
1294  * Load a PE style module according to the load order.
1295  *
1296  * The HFILE parameter is not used and marked reserved in the SDK. I can
1297  * only guess that it should force a file to be mapped, but I rather
1298  * ignore the parameter because it would be extremely difficult to
1299  * integrate this with different types of module represenations.
1300  *
1301  */
1302 WINE_MODREF *MODULE_LoadLibraryExA( LPCSTR libname, HFILE hfile, DWORD flags )
1303 {
1304         DWORD err = GetLastError();
1305         WINE_MODREF *pwm;
1306         int i;
1307         module_loadorder_t *plo;
1308         LPSTR filename, p;
1309
1310         if ( !libname ) return NULL;
1311
1312         filename = HeapAlloc ( GetProcessHeap(), 0, MAX_PATH + 1 );
1313         if ( !filename ) return NULL;
1314
1315         /* build the modules filename */
1316         if (!SearchPathA( NULL, libname, ".dll", MAX_PATH, filename, NULL ))
1317         {
1318             if ( ! GetSystemDirectoryA ( filename, MAX_PATH ) ) 
1319                 goto error;
1320
1321             /* if the library name contains a path and can not be found, return an error. 
1322                exception: if the path is the system directory, proceed, so that modules, 
1323                which are not PE-modules can be loaded
1324
1325                if the library name does not contain a path and can not be found, assume the 
1326                system directory is meant */
1327             
1328             if ( ! FILE_strncasecmp ( filename, libname, strlen ( filename ) ))
1329                 strcpy ( filename, libname );
1330             else
1331             {
1332                 if ( strchr ( libname, '\\' ) || strchr ( libname, ':') || strchr ( libname, '/' ) ) 
1333                     goto error;
1334                 else 
1335                 {
1336                     strcat ( filename, "\\" );
1337                     strcat ( filename, libname );
1338                 }
1339             }
1340       
1341             /* if the filename doesn't have an extension append .DLL */
1342             if (!(p = strrchr( filename, '.')) || strchr( p, '/' ) || strchr( p, '\\'))
1343                 strcat( filename, ".DLL" );
1344         }
1345
1346         RtlAcquirePebLock();
1347
1348         /* Check for already loaded module */
1349         if (!(pwm = MODULE_FindModule(filename)) && 
1350             /* no path in libpath */
1351             !strchr( libname, '\\' ) && !strchr( libname, ':') && !strchr( libname, '/' )) 
1352         {
1353             LPSTR       fn = HeapAlloc ( GetProcessHeap(), 0, MAX_PATH + 1 );
1354             if (fn)
1355             {
1356                 /* since the default loading mechanism uses a more detailed algorithm 
1357                  * than SearchPath (like using PATH, which can even be modified between
1358                  * two attempts of loading the same DLL), the look-up above (with
1359                  * SearchPath) can have put the file in system directory, whereas it
1360                  * has already been loaded but with a different path. So do a specific
1361                  * look-up with filename (without any path)
1362                  */
1363                 strcpy ( fn, libname );
1364                 /* if the filename doesn't have an extension append .DLL */
1365                 if (!strrchr( fn, '.')) strcat( fn, ".dll" );
1366                 if ((pwm = MODULE_FindModule( fn )) != NULL)
1367                    strcpy( filename, fn );
1368                 HeapFree( GetProcessHeap(), 0, fn );
1369             }
1370         }
1371         if (pwm)
1372         {
1373                 if(!(pwm->flags & WINE_MODREF_MARKER))
1374                         pwm->refCount++;
1375
1376                 if ((pwm->flags & WINE_MODREF_DONT_RESOLVE_REFS) &&
1377                     !(flags & DONT_RESOLVE_DLL_REFERENCES))
1378                 {
1379                     extern DWORD fixup_imports(WINE_MODREF *wm); /*FIXME*/
1380                     pwm->flags &= ~WINE_MODREF_DONT_RESOLVE_REFS;
1381                     fixup_imports( pwm );
1382                 }
1383                 TRACE("Already loaded module '%s' at 0x%08x, count=%d, \n", filename, pwm->module, pwm->refCount);
1384                 RtlReleasePebLock();
1385                 HeapFree ( GetProcessHeap(), 0, filename );
1386                 return pwm;
1387         }
1388
1389         plo = MODULE_GetLoadOrder(filename, TRUE);
1390
1391         for(i = 0; i < MODULE_LOADORDER_NTYPES; i++)
1392         {
1393                 SetLastError( ERROR_FILE_NOT_FOUND );
1394                 switch(plo->loadorder[i])
1395                 {
1396                 case MODULE_LOADORDER_DLL:
1397                         TRACE("Trying native dll '%s'\n", filename);
1398                         pwm = PE_LoadLibraryExA(filename, flags);
1399                         break;
1400
1401                 case MODULE_LOADORDER_SO:
1402                         TRACE("Trying so-library '%s'\n", filename);
1403                         pwm = ELF_LoadLibraryExA(filename, flags);
1404                         break;
1405
1406                 case MODULE_LOADORDER_BI:
1407                         TRACE("Trying built-in '%s'\n", filename);
1408                         pwm = BUILTIN32_LoadLibraryExA(filename, flags);
1409                         break;
1410
1411                 default:
1412                         ERR("Got invalid loadorder type %d (%s index %d)\n", plo->loadorder[i], plo->modulename, i);
1413                 /* Fall through */
1414
1415                 case MODULE_LOADORDER_INVALID:  /* We ignore this as it is an empty entry */
1416                         pwm = NULL;
1417                         break;
1418                 }
1419
1420                 if(pwm)
1421                 {
1422                         /* Initialize DLL just loaded */
1423                         TRACE("Loaded module '%s' at 0x%08x, \n", filename, pwm->module);
1424
1425                         /* Set the refCount here so that an attach failure will */
1426                         /* decrement the dependencies through the MODULE_FreeLibrary call. */
1427                         pwm->refCount++;
1428
1429                         RtlReleasePebLock();
1430                         SetLastError( err );  /* restore last error */
1431                         HeapFree ( GetProcessHeap(), 0, filename );
1432                         return pwm;
1433                 }
1434
1435                 if(GetLastError() != ERROR_FILE_NOT_FOUND)
1436                         break;
1437         }
1438
1439         RtlReleasePebLock();
1440  error:
1441         WARN("Failed to load module '%s'; error=0x%08lx, \n", filename, GetLastError());
1442         HeapFree ( GetProcessHeap(), 0, filename );
1443         return NULL;
1444 }
1445
1446 /***********************************************************************
1447  *           LoadLibraryA         (KERNEL32)
1448  */
1449 HMODULE WINAPI LoadLibraryA(LPCSTR libname) {
1450         return LoadLibraryExA(libname,0,0);
1451 }
1452
1453 /***********************************************************************
1454  *           LoadLibraryW         (KERNEL32)
1455  */
1456 HMODULE WINAPI LoadLibraryW(LPCWSTR libnameW)
1457 {
1458     return LoadLibraryExW(libnameW,0,0);
1459 }
1460
1461 /***********************************************************************
1462  *           LoadLibrary32_16   (KERNEL.452)
1463  */
1464 HMODULE WINAPI LoadLibrary32_16( LPCSTR libname )
1465 {
1466     HMODULE hModule;
1467     DWORD count;
1468
1469     ReleaseThunkLock( &count );
1470     hModule = LoadLibraryA( libname );
1471     RestoreThunkLock( count );
1472     return hModule;
1473 }
1474
1475 /***********************************************************************
1476  *           LoadLibraryExW       (KERNEL32)
1477  */
1478 HMODULE WINAPI LoadLibraryExW(LPCWSTR libnameW,HANDLE hfile,DWORD flags)
1479 {
1480     LPSTR libnameA = HEAP_strdupWtoA( GetProcessHeap(), 0, libnameW );
1481     HMODULE ret = LoadLibraryExA( libnameA , hfile, flags );
1482
1483     HeapFree( GetProcessHeap(), 0, libnameA );
1484     return ret;
1485 }
1486
1487 /***********************************************************************
1488  *           MODULE_FlushModrefs
1489  *
1490  * NOTE: Assumes that the process critical section is held!
1491  *
1492  * Remove all unused modrefs and call the internal unloading routines
1493  * for the library type.
1494  */
1495 static void MODULE_FlushModrefs(void)
1496 {
1497         WINE_MODREF *wm, *next;
1498
1499         for(wm = MODULE_modref_list; wm; wm = next)
1500         {
1501                 next = wm->next;
1502
1503                 if(wm->refCount)
1504                         continue;
1505
1506                 /* Unlink this modref from the chain */
1507                 if(wm->next)
1508                         wm->next->prev = wm->prev;
1509                 if(wm->prev)
1510                         wm->prev->next = wm->next;
1511                 if(wm == MODULE_modref_list)
1512                         MODULE_modref_list = wm->next;
1513
1514                 TRACE(" unloading %s\n", wm->filename);
1515                 /* VirtualFree( (LPVOID)wm->module, 0, MEM_RELEASE ); */  /* FIXME */
1516                 /* if (wm->dlhandle) wine_dlclose( wm->dlhandle, NULL, 0 ); */  /* FIXME */
1517                 FreeLibrary16(wm->hDummyMod);
1518                 HeapFree( GetProcessHeap(), 0, wm->deps );
1519                 HeapFree( GetProcessHeap(), 0, wm->filename );
1520                 HeapFree( GetProcessHeap(), 0, wm->short_filename );
1521                 HeapFree( GetProcessHeap(), 0, wm );
1522         }
1523 }
1524
1525 /***********************************************************************
1526  *           FreeLibrary
1527  */
1528 BOOL WINAPI FreeLibrary(HINSTANCE hLibModule)
1529 {
1530     BOOL retv = FALSE;
1531     WINE_MODREF *wm;
1532
1533     RtlAcquirePebLock();
1534     free_lib_count++;
1535
1536     wm = MODULE32_LookupHMODULE( hLibModule );
1537     if ( !wm || !hLibModule )
1538         SetLastError( ERROR_INVALID_HANDLE );
1539     else
1540         retv = MODULE_FreeLibrary( wm );
1541
1542     free_lib_count--;
1543     RtlReleasePebLock();
1544
1545     return retv;
1546 }
1547
1548 /***********************************************************************
1549  *           MODULE_DecRefCount
1550  *
1551  * NOTE: Assumes that the process critical section is held!
1552  */
1553 static void MODULE_DecRefCount( WINE_MODREF *wm )
1554 {
1555     int i;
1556
1557     if ( wm->flags & WINE_MODREF_MARKER )
1558         return;
1559
1560     if ( wm->refCount <= 0 )
1561         return;
1562
1563     --wm->refCount;
1564     TRACE("(%s) refCount: %d\n", wm->modname, wm->refCount );
1565
1566     if ( wm->refCount == 0 )
1567     {
1568         wm->flags |= WINE_MODREF_MARKER;
1569
1570         for ( i = 0; i < wm->nDeps; i++ )
1571             if ( wm->deps[i] )
1572                 MODULE_DecRefCount( wm->deps[i] );
1573
1574         wm->flags &= ~WINE_MODREF_MARKER;
1575     }
1576 }
1577
1578 /***********************************************************************
1579  *           MODULE_FreeLibrary
1580  *
1581  * NOTE: Assumes that the process critical section is held!
1582  */
1583 BOOL MODULE_FreeLibrary( WINE_MODREF *wm )
1584 {
1585     TRACE("(%s) - START\n", wm->modname );
1586
1587     /* Recursively decrement reference counts */
1588     MODULE_DecRefCount( wm );
1589
1590     /* Call process detach notifications */
1591     if ( free_lib_count <= 1 )
1592     {
1593         MODULE_DllProcessDetach( FALSE, NULL );
1594         SERVER_START_REQ
1595         {
1596             struct unload_dll_request *req = server_alloc_req( sizeof(*req), 0 );
1597             req->base = (void *)wm->module;
1598             server_call_noerr( REQ_UNLOAD_DLL );
1599         }
1600         SERVER_END_REQ;
1601         MODULE_FlushModrefs();
1602     }
1603
1604     TRACE("END\n");
1605
1606     return TRUE;
1607 }
1608
1609
1610 /***********************************************************************
1611  *           FreeLibraryAndExitThread
1612  */
1613 VOID WINAPI FreeLibraryAndExitThread(HINSTANCE hLibModule, DWORD dwExitCode)
1614 {
1615     FreeLibrary(hLibModule);
1616     ExitThread(dwExitCode);
1617 }
1618
1619 /***********************************************************************
1620  *           PrivateLoadLibrary       (KERNEL32)
1621  *
1622  * FIXME: rough guesswork, don't know what "Private" means
1623  */
1624 HINSTANCE WINAPI PrivateLoadLibrary(LPCSTR libname)
1625 {
1626         return (HINSTANCE)LoadLibrary16(libname);
1627 }
1628
1629
1630
1631 /***********************************************************************
1632  *           PrivateFreeLibrary       (KERNEL32)
1633  *
1634  * FIXME: rough guesswork, don't know what "Private" means
1635  */
1636 void WINAPI PrivateFreeLibrary(HINSTANCE handle)
1637 {
1638         FreeLibrary16((HINSTANCE16)handle);
1639 }
1640
1641
1642 /***********************************************************************
1643  *           WIN32_GetProcAddress16   (KERNEL32.36)
1644  * Get procaddress in 16bit module from win32... (kernel32 undoc. ordinal func)
1645  */
1646 FARPROC16 WINAPI WIN32_GetProcAddress16( HMODULE hModule, LPCSTR name )
1647 {
1648     if (!hModule) {
1649         WARN("hModule may not be 0!\n");
1650         return (FARPROC16)0;
1651     }
1652     if (HIWORD(hModule))
1653     {
1654         WARN("hModule is Win32 handle (%08x)\n", hModule );
1655         return (FARPROC16)0;
1656     }
1657     return GetProcAddress16( hModule, name );
1658 }
1659
1660 /***********************************************************************
1661  *           GetProcAddress16   (KERNEL.50)
1662  */
1663 FARPROC16 WINAPI GetProcAddress16( HMODULE16 hModule, LPCSTR name )
1664 {
1665     WORD ordinal;
1666     FARPROC16 ret;
1667
1668     if (!hModule) hModule = GetCurrentTask();
1669     hModule = GetExePtr( hModule );
1670
1671     if (HIWORD(name) != 0)
1672     {
1673         ordinal = NE_GetOrdinal( hModule, name );
1674         TRACE("%04x '%s'\n", hModule, name );
1675     }
1676     else
1677     {
1678         ordinal = LOWORD(name);
1679         TRACE("%04x %04x\n", hModule, ordinal );
1680     }
1681     if (!ordinal) return (FARPROC16)0;
1682
1683     ret = NE_GetEntryPoint( hModule, ordinal );
1684
1685     TRACE("returning %08x\n", (UINT)ret );
1686     return ret;
1687 }
1688
1689
1690 /***********************************************************************
1691  *           GetProcAddress             (KERNEL32.257)
1692  */
1693 FARPROC WINAPI GetProcAddress( HMODULE hModule, LPCSTR function )
1694 {
1695     return MODULE_GetProcAddress( hModule, function, TRUE );
1696 }
1697
1698 /***********************************************************************
1699  *           GetProcAddress32                   (KERNEL.453)
1700  */
1701 FARPROC WINAPI GetProcAddress32_16( HMODULE hModule, LPCSTR function )
1702 {
1703     return MODULE_GetProcAddress( hModule, function, FALSE );
1704 }
1705
1706 /***********************************************************************
1707  *           MODULE_GetProcAddress              (internal)
1708  */
1709 FARPROC MODULE_GetProcAddress( 
1710         HMODULE hModule,        /* [in] current module handle */
1711         LPCSTR function,        /* [in] function to be looked up */
1712         BOOL snoop )
1713 {
1714     WINE_MODREF *wm;
1715     FARPROC     retproc = 0;
1716
1717     if (HIWORD(function))
1718         TRACE_(win32)("(%08lx,%s)\n",(DWORD)hModule,function);
1719     else
1720         TRACE_(win32)("(%08lx,%p)\n",(DWORD)hModule,function);
1721
1722     RtlAcquirePebLock();
1723     if ((wm = MODULE32_LookupHMODULE( hModule )))
1724     {
1725         retproc = wm->find_export( wm, function, snoop );
1726         if (!retproc) SetLastError(ERROR_PROC_NOT_FOUND);
1727     }
1728     RtlReleasePebLock();
1729     return retproc;
1730 }
1731
1732
1733 /***************************************************************************
1734  *              HasGPHandler                    (KERNEL.338)
1735  */
1736
1737 #include "pshpack1.h"
1738 typedef struct _GPHANDLERDEF
1739 {
1740     WORD selector;
1741     WORD rangeStart;
1742     WORD rangeEnd;
1743     WORD handler;
1744 } GPHANDLERDEF;
1745 #include "poppack.h"
1746
1747 SEGPTR WINAPI HasGPHandler16( SEGPTR address )
1748 {
1749     HMODULE16 hModule;
1750     int gpOrdinal;
1751     SEGPTR gpPtr;
1752     GPHANDLERDEF *gpHandler;
1753    
1754     if (    (hModule = FarGetOwner16( SELECTOROF(address) )) != 0
1755          && (gpOrdinal = NE_GetOrdinal( hModule, "__GP" )) != 0
1756          && (gpPtr = (SEGPTR)NE_GetEntryPointEx( hModule, gpOrdinal, FALSE )) != 0
1757          && !IsBadReadPtr16( gpPtr, sizeof(GPHANDLERDEF) )
1758          && (gpHandler = MapSL( gpPtr )) != NULL )
1759     {
1760         while (gpHandler->selector)
1761         {
1762             if (    SELECTOROF(address) == gpHandler->selector
1763                  && OFFSETOF(address)   >= gpHandler->rangeStart
1764                  && OFFSETOF(address)   <  gpHandler->rangeEnd  )
1765                 return MAKESEGPTR( gpHandler->selector, gpHandler->handler );
1766             gpHandler++;
1767         }
1768     }
1769
1770     return 0;
1771 }
1772