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