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