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