Moved the module loading/unloading code and the remaining needed
[wine] / dlls / ntdll / loader.c
1 /*
2  * Loader functions
3  *
4  * Copyright 1995 Alexandre Julliard
5  * Copyright 2002 Dmitry Timoshkov for Codeweavers
6  *
7  * This library is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * This library is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this library; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 #include <assert.h>
23
24 #include "winbase.h"
25 #include "winnt.h"
26 #include "winternl.h"
27
28 #include "module.h"
29 #include "file.h"
30 #include "wine/exception.h"
31 #include "excpt.h"
32 #include "wine/debug.h"
33 #include "wine/server.h"
34 #include "ntdll_misc.h"
35
36 WINE_DEFAULT_DEBUG_CHANNEL(ntdll);
37 WINE_DECLARE_DEBUG_CHANNEL(module);
38 WINE_DECLARE_DEBUG_CHANNEL(module);
39 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
40
41 WINE_MODREF *MODULE_modref_list = NULL;
42
43 static WINE_MODREF *exe_modref;
44 static int process_detaching = 0;  /* set on process detach to avoid deadlocks with thread detach */
45 static int free_lib_count;   /* recursion depth of LdrUnloadDll calls */
46
47 /* filter for page-fault exceptions */
48 static WINE_EXCEPTION_FILTER(page_fault)
49 {
50     if (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION)
51         return EXCEPTION_EXECUTE_HANDLER;
52     return EXCEPTION_CONTINUE_SEARCH;
53 }
54
55 static CRITICAL_SECTION loader_section = CRITICAL_SECTION_INIT( "loader_section" );
56
57 /*************************************************************************
58  *              MODULE32_LookupHMODULE
59  * looks for the referenced HMODULE in the current process
60  * NOTE: Assumes that the process critical section is held!
61  */
62 static WINE_MODREF *MODULE32_LookupHMODULE( HMODULE hmod )
63 {
64     WINE_MODREF *wm;
65
66     if (!hmod)
67         return exe_modref;
68
69     if (!HIWORD(hmod)) {
70         ERR("tried to lookup %p in win32 module handler!\n",hmod);
71         return NULL;
72     }
73     for ( wm = MODULE_modref_list; wm; wm=wm->next )
74         if (wm->module == hmod)
75             return wm;
76     return NULL;
77 }
78
79 /*************************************************************************
80  *              MODULE_AllocModRef
81  *
82  * Allocate a WINE_MODREF structure and add it to the process list
83  * NOTE: Assumes that the process critical section is held!
84  */
85 WINE_MODREF *MODULE_AllocModRef( HMODULE hModule, LPCSTR filename )
86 {
87     WINE_MODREF *wm;
88     IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
89
90     DWORD long_len = strlen( filename );
91     DWORD short_len = GetShortPathNameA( filename, NULL, 0 );
92
93     if ((wm = RtlAllocateHeap( ntdll_get_process_heap(), HEAP_ZERO_MEMORY,
94                                sizeof(*wm) + long_len + short_len + 1 )))
95     {
96         wm->module = hModule;
97         wm->tlsindex = -1;
98
99         wm->filename = wm->data;
100         memcpy( wm->filename, filename, long_len + 1 );
101         if ((wm->modname = strrchr( wm->filename, '\\' ))) wm->modname++;
102         else wm->modname = wm->filename;
103
104         wm->short_filename = wm->filename + long_len + 1;
105         GetShortPathNameA( wm->filename, wm->short_filename, short_len + 1 );
106         if ((wm->short_modname = strrchr( wm->short_filename, '\\' ))) wm->short_modname++;
107         else wm->short_modname = wm->short_filename;
108
109         wm->next = MODULE_modref_list;
110         if (wm->next) wm->next->prev = wm;
111         MODULE_modref_list = wm;
112
113         wm->ldr.InLoadOrderModuleList.Flink = NULL;
114         wm->ldr.InLoadOrderModuleList.Blink = NULL;
115         wm->ldr.InMemoryOrderModuleList.Flink = NULL;
116         wm->ldr.InMemoryOrderModuleList.Blink = NULL;
117         wm->ldr.InInitializationOrderModuleList.Flink = NULL;
118         wm->ldr.InInitializationOrderModuleList.Blink = NULL;
119         wm->ldr.BaseAddress = hModule;
120         wm->ldr.EntryPoint = (nt->OptionalHeader.AddressOfEntryPoint) ?
121                              ((char *)hModule + nt->OptionalHeader.AddressOfEntryPoint) : 0;
122         wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
123         RtlCreateUnicodeStringFromAsciiz( &wm->ldr.FullDllName, wm->filename);
124         RtlCreateUnicodeStringFromAsciiz( &wm->ldr.BaseDllName, wm->modname);
125         wm->ldr.Flags = 0;
126         wm->ldr.LoadCount = 0;
127         wm->ldr.TlsIndex = 0;
128         wm->ldr.SectionHandle = NULL;
129         wm->ldr.CheckSum = 0;
130         wm->ldr.TimeDateStamp = 0;
131
132         if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL))
133         {
134             if (!exe_modref) exe_modref = wm;
135             else FIXME( "Trying to load second .EXE file: %s\n", filename );
136         }
137     }
138     return wm;
139 }
140
141 /*************************************************************************
142  *              MODULE_InitDLL
143  */
144 static BOOL MODULE_InitDLL( WINE_MODREF *wm, DWORD type, LPVOID lpReserved )
145 {
146     static const char * const typeName[] = { "PROCESS_DETACH", "PROCESS_ATTACH",
147                                              "THREAD_ATTACH", "THREAD_DETACH" };
148     BOOL retv = TRUE;
149
150     /* Skip calls for modules loaded with special load flags */
151
152     if (wm->flags & WINE_MODREF_DONT_RESOLVE_REFS) return TRUE;
153
154     TRACE("(%s,%s,%p) - CALL\n", wm->modname, typeName[type], lpReserved );
155
156     /* Call the initialization routine */
157     retv = PE_InitDLL( wm->module, type, lpReserved );
158
159     /* The state of the module list may have changed due to the call
160        to PE_InitDLL. We cannot assume that this module has not been
161        deleted.  */
162     TRACE("(%p,%s,%p) - RETURN %d\n", wm, typeName[type], lpReserved, retv );
163
164     return retv;
165 }
166
167
168 /*************************************************************************
169  *              MODULE_DllProcessAttach
170  *
171  * Send the process attach notification to all DLLs the given module
172  * depends on (recursively). This is somewhat complicated due to the fact that
173  *
174  * - we have to respect the module dependencies, i.e. modules implicitly
175  *   referenced by another module have to be initialized before the module
176  *   itself can be initialized
177  *
178  * - the initialization routine of a DLL can itself call LoadLibrary,
179  *   thereby introducing a whole new set of dependencies (even involving
180  *   the 'old' modules) at any time during the whole process
181  *
182  * (Note that this routine can be recursively entered not only directly
183  *  from itself, but also via LoadLibrary from one of the called initialization
184  *  routines.)
185  *
186  * Furthermore, we need to rearrange the main WINE_MODREF list to allow
187  * the process *detach* notifications to be sent in the correct order.
188  * This must not only take into account module dependencies, but also
189  * 'hidden' dependencies created by modules calling LoadLibrary in their
190  * attach notification routine.
191  *
192  * The strategy is rather simple: we move a WINE_MODREF to the head of the
193  * list after the attach notification has returned.  This implies that the
194  * detach notifications are called in the reverse of the sequence the attach
195  * notifications *returned*.
196  */
197 BOOL MODULE_DllProcessAttach( WINE_MODREF *wm, LPVOID lpReserved )
198 {
199     BOOL retv = TRUE;
200     int i;
201
202     RtlEnterCriticalSection( &loader_section );
203
204     if (!wm)
205     {
206         wm = exe_modref;
207         PE_InitTls();
208     }
209     assert( wm );
210
211     /* prevent infinite recursion in case of cyclical dependencies */
212     if (    ( wm->flags & WINE_MODREF_MARKER )
213          || ( wm->flags & WINE_MODREF_PROCESS_ATTACHED ) )
214         goto done;
215
216     TRACE("(%s,%p) - START\n", wm->modname, lpReserved );
217
218     /* Tag current MODREF to prevent recursive loop */
219     wm->flags |= WINE_MODREF_MARKER;
220
221     /* Recursively attach all DLLs this one depends on */
222     for ( i = 0; retv && i < wm->nDeps; i++ )
223         if ( wm->deps[i] )
224             retv = MODULE_DllProcessAttach( wm->deps[i], lpReserved );
225
226     /* Call DLL entry point */
227     if ( retv )
228     {
229         retv = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
230         if ( retv )
231             wm->flags |= WINE_MODREF_PROCESS_ATTACHED;
232     }
233
234     /* Re-insert MODREF at head of list */
235     if ( retv && wm->prev )
236     {
237         wm->prev->next = wm->next;
238         if ( wm->next ) wm->next->prev = wm->prev;
239
240         wm->prev = NULL;
241         wm->next = MODULE_modref_list;
242         MODULE_modref_list = wm->next->prev = wm;
243     }
244
245     /* Remove recursion flag */
246     wm->flags &= ~WINE_MODREF_MARKER;
247
248     TRACE("(%s,%p) - END\n", wm->modname, lpReserved );
249
250  done:
251     RtlLeaveCriticalSection( &loader_section );
252     return retv;
253 }
254
255 /*************************************************************************
256  *              MODULE_DllProcessDetach
257  *
258  * Send DLL process detach notifications.  See the comment about calling
259  * sequence at MODULE_DllProcessAttach.  Unless the bForceDetach flag
260  * is set, only DLLs with zero refcount are notified.
261  */
262 void MODULE_DllProcessDetach( BOOL bForceDetach, LPVOID lpReserved )
263 {
264     WINE_MODREF *wm;
265
266     RtlEnterCriticalSection( &loader_section );
267     if (bForceDetach) process_detaching = 1;
268     do
269     {
270         for ( wm = MODULE_modref_list; wm; wm = wm->next )
271         {
272             /* Check whether to detach this DLL */
273             if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
274                 continue;
275             if ( wm->refCount > 0 && !bForceDetach )
276                 continue;
277
278             /* Call detach notification */
279             wm->flags &= ~WINE_MODREF_PROCESS_ATTACHED;
280             MODULE_InitDLL( wm, DLL_PROCESS_DETACH, lpReserved );
281
282             /* Restart at head of WINE_MODREF list, as entries might have
283                been added and/or removed while performing the call ... */
284             break;
285         }
286     } while ( wm );
287
288     RtlLeaveCriticalSection( &loader_section );
289 }
290
291 /*************************************************************************
292  *              MODULE_DllThreadAttach
293  *
294  * Send DLL thread attach notifications. These are sent in the
295  * reverse sequence of process detach notification.
296  *
297  */
298 void MODULE_DllThreadAttach( LPVOID lpReserved )
299 {
300     WINE_MODREF *wm;
301
302     /* don't do any attach calls if process is exiting */
303     if (process_detaching) return;
304     /* FIXME: there is still a race here */
305
306     RtlEnterCriticalSection( &loader_section );
307
308     PE_InitTls();
309
310     for ( wm = MODULE_modref_list; wm; wm = wm->next )
311         if ( !wm->next )
312             break;
313
314     for ( ; wm; wm = wm->prev )
315     {
316         if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
317             continue;
318         if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
319             continue;
320
321         MODULE_InitDLL( wm, DLL_THREAD_ATTACH, lpReserved );
322     }
323
324     RtlLeaveCriticalSection( &loader_section );
325 }
326
327 /******************************************************************
328  *              LdrDisableThreadCalloutsForDll (NTDLL.@)
329  *
330  */
331 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
332 {
333     WINE_MODREF *wm;
334     NTSTATUS    ret = STATUS_SUCCESS;
335
336     RtlEnterCriticalSection( &loader_section );
337
338     wm = MODULE32_LookupHMODULE( hModule );
339     if ( !wm )
340         ret = STATUS_DLL_NOT_FOUND;
341     else
342         wm->flags |= WINE_MODREF_NO_DLL_CALLS;
343
344     RtlLeaveCriticalSection( &loader_section );
345
346     return ret;
347 }
348
349 /******************************************************************
350  *              LdrFindEntryForAddress (NTDLL.@)
351  *
352  * The loader_section must be locked while calling this function
353  */
354 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* mod)
355 {
356     WINE_MODREF*        wm;
357
358     for ( wm = MODULE_modref_list; wm; wm = wm->next )
359     {
360         if ((const void *)wm->module <= addr &&
361             (char *)addr < (char*)wm->module + wm->ldr.SizeOfImage)
362         {
363             *mod = &wm->ldr;
364             return STATUS_SUCCESS;
365         }
366     }
367     return STATUS_NO_MORE_ENTRIES;
368 }
369
370 /**********************************************************************
371  *          MODULE_FindModule
372  *
373  * Find a (loaded) win32 module depending on path
374  *      LPCSTR path: [in] pathname of module/library to be found
375  *
376  * The loader_section must be locked while calling this function
377  * RETURNS
378  *      the module handle if found
379  *      0 if not
380  */
381 WINE_MODREF *MODULE_FindModule(LPCSTR path)
382 {
383     WINE_MODREF *wm;
384     char dllname[260], *p;
385
386     /* Append .DLL to name if no extension present */
387     strcpy( dllname, path );
388     if (!(p = strrchr( dllname, '.')) || strchr( p, '/' ) || strchr( p, '\\'))
389             strcat( dllname, ".DLL" );
390
391     for ( wm = MODULE_modref_list; wm; wm = wm->next )
392     {
393         if ( !FILE_strcasecmp( dllname, wm->modname ) )
394             break;
395         if ( !FILE_strcasecmp( dllname, wm->filename ) )
396             break;
397         if ( !FILE_strcasecmp( dllname, wm->short_modname ) )
398             break;
399         if ( !FILE_strcasecmp( dllname, wm->short_filename ) )
400             break;
401     }
402
403     return wm;
404 }
405
406
407 /******************************************************************
408  *              LdrLockLoaderLock  (NTDLL.@)
409  *
410  * Note: flags are not implemented.
411  * Flag 0x01 is used to raise exceptions on errors.
412  * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
413  */
414 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG *magic )
415 {
416     if (flags) FIXME( "flags %lx not supported\n", flags );
417
418     if (result) *result = 1;
419     if (!magic) return STATUS_INVALID_PARAMETER_3;
420     RtlEnterCriticalSection( &loader_section );
421     *magic = GetCurrentThreadId();
422     return STATUS_SUCCESS;
423 }
424
425
426 /******************************************************************
427  *              LdrUnlockLoaderUnlock  (NTDLL.@)
428  */
429 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG magic )
430 {
431     if (magic)
432     {
433         if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
434         RtlLeaveCriticalSection( &loader_section );
435     }
436     return STATUS_SUCCESS;
437 }
438
439
440 /******************************************************************
441  *              LdrGetDllHandle (NTDLL.@)
442  *
443  *
444  */
445 NTSTATUS WINAPI LdrGetDllHandle(ULONG x, ULONG y, PUNICODE_STRING name, HMODULE *base)
446 {
447     WINE_MODREF *wm;
448
449     TRACE("%08lx %08lx %s %p\n",
450           x, y, name ? debugstr_wn(name->Buffer, name->Length) : NULL, base);
451
452     if (x != 0 || y != 0)
453         FIXME("Unknown behavior, please report\n");
454
455     /* FIXME: we should store module name information as unicode */
456     if (name)
457     {
458         STRING str;
459
460         RtlUnicodeStringToAnsiString( &str, name, TRUE );
461
462         wm = MODULE_FindModule( str.Buffer );
463         RtlFreeAnsiString( &str );
464     }
465     else
466         wm = exe_modref;
467
468     if (!wm)
469     {
470         *base = 0;
471         return STATUS_DLL_NOT_FOUND;
472     }
473
474     *base = wm->module;
475     return STATUS_SUCCESS;
476 }
477
478 /***********************************************************************
479  *           MODULE_GetProcAddress              (internal)
480  */
481 FARPROC MODULE_GetProcAddress(
482         HMODULE hModule,        /* [in] current module handle */
483         LPCSTR function,        /* [in] function to be looked up */
484         int hint,
485         BOOL snoop )
486 {
487     WINE_MODREF *wm;
488     FARPROC     retproc = 0;
489
490     if (HIWORD(function))
491         TRACE("(%p,%s (%d))\n",hModule,function,hint);
492     else
493         TRACE("(%p,%p)\n",hModule,function);
494
495     RtlEnterCriticalSection( &loader_section );
496     if ((wm = MODULE32_LookupHMODULE( hModule )))
497     {
498         retproc = wm->find_export( wm, function, hint, snoop );
499     }
500     RtlLeaveCriticalSection( &loader_section );
501     return retproc;
502 }
503
504
505 /******************************************************************
506  *              LdrGetProcedureAddress (NTDLL.@)
507  *
508  *
509  */
510 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE base, PANSI_STRING name, ULONG ord, PVOID *address)
511 {
512     WARN("%p %s %ld %p\n", base, name ? debugstr_an(name->Buffer, name->Length) : NULL, ord, address);
513
514     *address = MODULE_GetProcAddress( base, name ? name->Buffer : (LPSTR)ord, -1, TRUE );
515
516     return (*address) ? STATUS_SUCCESS : STATUS_PROCEDURE_NOT_FOUND;
517 }
518
519
520 /***********************************************************************
521  *      allocate_lib_dir
522  *
523  * helper for MODULE_LoadLibraryExA.  Allocate space to hold the directory
524  * portion of the provided name and put the name in it.
525  *
526  */
527 static LPCSTR allocate_lib_dir(LPCSTR libname)
528 {
529     LPCSTR p, pmax;
530     LPSTR result;
531     int length;
532
533     pmax = libname;
534     if ((p = strrchr( pmax, '\\' ))) pmax = p + 1;
535     if ((p = strrchr( pmax, '/' ))) pmax = p + 1; /* Naughty.  MSDN says don't */
536     if (pmax == libname && pmax[0] && pmax[1] == ':') pmax += 2;
537
538     length = pmax - libname;
539
540     result = RtlAllocateHeap (ntdll_get_process_heap(), 0, length+1);
541
542     if (result)
543     {
544         strncpy (result, libname, length);
545         result [length] = '\0';
546     }
547
548     return result;
549 }
550
551 /***********************************************************************
552  *      MODULE_LoadLibraryExA   (internal)
553  *
554  * Load a PE style module according to the load order.
555  *
556  * libdir is used to support LOAD_WITH_ALTERED_SEARCH_PATH during the recursion
557  *        on this function.  When first called from LoadLibraryExA it will be
558  *        NULL but thereafter it may point to a buffer containing the path
559  *        portion of the library name.  Note that the recursion all occurs
560  *        within a Critical section (see LoadLibraryExA) so the use of a
561  *        static is acceptable.
562  *        (We have to use a static variable at some point anyway, to pass the
563  *        information from BUILTIN32_dlopen through dlopen and the builtin's
564  *        init function into load_library).
565  * allocated_libdir is TRUE in the stack frame that allocated libdir
566  */
567 NTSTATUS MODULE_LoadLibraryExA( LPCSTR libname, DWORD flags, WINE_MODREF** pwm)
568 {
569     int i;
570     enum loadorder_type loadorder[LOADORDER_NTYPES];
571     LPSTR filename;
572     const char *filetype = "";
573     DWORD found;
574     BOOL allocated_libdir = FALSE;
575     static LPCSTR libdir = NULL; /* See above */
576     NTSTATUS nts = STATUS_SUCCESS;
577
578     *pwm = NULL;
579     if ( !libname ) return STATUS_DLL_NOT_FOUND; /* FIXME ? */
580
581     filename = RtlAllocateHeap ( ntdll_get_process_heap(), 0, MAX_PATH + 1 );
582     if ( !filename ) return STATUS_NO_MEMORY;
583     *filename = 0; /* Just in case we don't set it before goto error */
584
585     RtlEnterCriticalSection( &loader_section );
586
587     if ((flags & LOAD_WITH_ALTERED_SEARCH_PATH) && FILE_contains_path(libname))
588     {
589         if (!(libdir = allocate_lib_dir(libname)))
590         {
591             nts = STATUS_NO_MEMORY;
592             goto error;
593         }
594         allocated_libdir = TRUE;
595     }
596
597     if (!libdir || allocated_libdir)
598         found = SearchPathA(NULL, libname, ".dll", MAX_PATH, filename, NULL);
599     else
600         found = DIR_SearchAlternatePath(libdir, libname, ".dll", MAX_PATH, filename, NULL);
601
602     /* build the modules filename */
603     if (!found)
604     {
605         if (!MODULE_GetBuiltinPath( libname, ".dll", filename, MAX_PATH ))
606         {
607             nts = STATUS_INTERNAL_ERROR;
608             goto error;
609         }
610     }
611
612     /* Check for already loaded module */
613     if (!(*pwm = MODULE_FindModule(filename)) && !FILE_contains_path(libname))
614     {
615         LPSTR   fn = RtlAllocateHeap ( ntdll_get_process_heap(), 0, MAX_PATH + 1 );
616         if (fn)
617         {
618             /* since the default loading mechanism uses a more detailed algorithm
619              * than SearchPath (like using PATH, which can even be modified between
620              * two attempts of loading the same DLL), the look-up above (with
621              * SearchPath) can have put the file in system directory, whereas it
622              * has already been loaded but with a different path. So do a specific
623              * look-up with filename (without any path)
624              */
625             strcpy ( fn, libname );
626             /* if the filename doesn't have an extension append .DLL */
627             if (!strrchr( fn, '.')) strcat( fn, ".dll" );
628             if ((*pwm = MODULE_FindModule( fn )) != NULL)
629                 strcpy( filename, fn );
630             RtlFreeHeap( ntdll_get_process_heap(), 0, fn );
631         }
632     }
633     if (*pwm)
634     {
635         (*pwm)->refCount++;
636         
637         if (((*pwm)->flags & WINE_MODREF_DONT_RESOLVE_REFS) &&
638             !(flags & DONT_RESOLVE_DLL_REFERENCES))
639         {
640             (*pwm)->flags &= ~WINE_MODREF_DONT_RESOLVE_REFS;
641             PE_fixup_imports( *pwm );
642         }
643         TRACE("Already loaded module '%s' at %p, count=%d\n", filename, (*pwm)->module, (*pwm)->refCount);
644         if (allocated_libdir)
645         {
646             RtlFreeHeap( ntdll_get_process_heap(), 0, (LPSTR)libdir );
647             libdir = NULL;
648         }
649         RtlLeaveCriticalSection( &loader_section );
650         RtlFreeHeap( ntdll_get_process_heap(), 0, filename );
651         return STATUS_SUCCESS;
652     }
653
654     MODULE_GetLoadOrder( loadorder, filename, TRUE);
655
656     for (i = 0; i < LOADORDER_NTYPES; i++)
657     {
658         if (loadorder[i] == LOADORDER_INVALID) break;
659
660         switch (loadorder[i])
661         {
662         case LOADORDER_DLL:
663             TRACE("Trying native dll '%s'\n", filename);
664             nts = PE_LoadLibraryExA(filename, flags, pwm);
665             filetype = "native";
666             break;
667             
668         case LOADORDER_BI:
669             TRACE("Trying built-in '%s'\n", filename);
670             nts = BUILTIN32_LoadLibraryExA(filename, flags, pwm);
671             filetype = "builtin";
672             break;
673             
674         default:
675             nts = STATUS_INTERNAL_ERROR;
676             break;
677         }
678
679         if (nts == STATUS_SUCCESS)
680         {
681             /* Initialize DLL just loaded */
682             TRACE("Loaded module '%s' at %p\n", filename, (*pwm)->module);
683             if (!TRACE_ON(module))
684                 TRACE_(loaddll)("Loaded module '%s' : %s\n", filename, filetype);
685             /* Set the refCount here so that an attach failure will */
686             /* decrement the dependencies through the MODULE_FreeLibrary call. */
687             (*pwm)->refCount = 1;
688             
689             if (allocated_libdir)
690             {
691                 RtlFreeHeap( ntdll_get_process_heap(), 0, (LPSTR)libdir );
692                 libdir = NULL;
693             }
694             RtlLeaveCriticalSection( &loader_section );
695             RtlFreeHeap( ntdll_get_process_heap(), 0, filename );
696             return nts;
697         }
698
699         if (nts != STATUS_NO_SUCH_FILE)
700         {
701             WARN("Loading of %s DLL %s failed (status %ld).\n",
702                  filetype, filename, nts);
703             break;
704         }
705     }
706
707  error:
708     if (allocated_libdir)
709     {
710         RtlFreeHeap( ntdll_get_process_heap(), 0, (LPSTR)libdir );
711         libdir = NULL;
712     }
713     RtlLeaveCriticalSection( &loader_section );
714     WARN("Failed to load module '%s'; status=%ld\n", filename, nts);
715     RtlFreeHeap( ntdll_get_process_heap(), 0, filename );
716     return nts;
717 }
718
719 /******************************************************************
720  *              LdrLoadDll (NTDLL.@)
721  */
722 NTSTATUS WINAPI LdrLoadDll(LPCWSTR path_name, DWORD flags, PUNICODE_STRING libname, HMODULE* hModule)
723 {
724     WINE_MODREF *wm;
725     NTSTATUS    nts = STATUS_SUCCESS;
726     STRING      str;
727
728     RtlUnicodeStringToAnsiString(&str, libname, TRUE);
729
730     RtlEnterCriticalSection( &loader_section );
731
732     switch (nts = MODULE_LoadLibraryExA( str.Buffer, flags, &wm ))
733     {
734     case STATUS_SUCCESS:
735         if ( !MODULE_DllProcessAttach( wm, NULL ) )
736         {
737             WARN_(module)("Attach failed for module '%s'.\n", str.Buffer);
738             LdrUnloadDll(wm->module);
739             nts = STATUS_DLL_INIT_FAILED;
740             wm = NULL;
741         }
742         break;
743     case STATUS_NO_SUCH_FILE:
744         nts = STATUS_DLL_NOT_FOUND;
745         break;
746     default: /* keep error code as it is (memory...) */
747         break;
748     }
749
750     *hModule = (wm) ? wm->module : NULL;
751     
752     RtlLeaveCriticalSection( &loader_section );
753
754     RtlFreeAnsiString(&str);
755
756     return nts;
757 }
758
759 /******************************************************************
760  *              LdrShutdownProcess (NTDLL.@)
761  *
762  */
763 NTSTATUS    WINAPI  LdrShutdownProcess(void)
764 {
765     TRACE("()\n");
766     MODULE_DllProcessDetach( TRUE, (LPVOID)1 );
767     return STATUS_SUCCESS; /* FIXME */
768 }
769
770 /******************************************************************
771  *              LdrShutdownThread (NTDLL.@)
772  *
773  */
774 NTSTATUS WINAPI LdrShutdownThread(void)
775 {
776     WINE_MODREF *wm;
777     TRACE("()\n");
778
779     /* don't do any detach calls if process is exiting */
780     if (process_detaching) return STATUS_SUCCESS;
781     /* FIXME: there is still a race here */
782
783     RtlEnterCriticalSection( &loader_section );
784
785     for ( wm = MODULE_modref_list; wm; wm = wm->next )
786     {
787         if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
788             continue;
789         if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
790             continue;
791
792         MODULE_InitDLL( wm, DLL_THREAD_DETACH, NULL );
793     }
794
795     RtlLeaveCriticalSection( &loader_section );
796     return STATUS_SUCCESS; /* FIXME */
797 }
798
799 /***********************************************************************
800  *           MODULE_FlushModrefs
801  *
802  * NOTE: Assumes that the process critical section is held!
803  *
804  * Remove all unused modrefs and call the internal unloading routines
805  * for the library type.
806  */
807 static void MODULE_FlushModrefs(void)
808 {
809     WINE_MODREF *wm, *next;
810
811     for (wm = MODULE_modref_list; wm; wm = next)
812     {
813         next = wm->next;
814
815         if (wm->refCount)
816             continue;
817
818         /* Unlink this modref from the chain */
819         if (wm->next)
820             wm->next->prev = wm->prev;
821         if (wm->prev)
822             wm->prev->next = wm->next;
823         if (wm == MODULE_modref_list)
824             MODULE_modref_list = wm->next;
825
826         TRACE(" unloading %s\n", wm->filename);
827         if (!TRACE_ON(module))
828             TRACE_(loaddll)("Unloaded module '%s' : %s\n", wm->filename,
829                             wm->dlhandle ? "builtin" : "native" );
830
831         SERVER_START_REQ( unload_dll )
832         {
833             req->base = (void *)wm->module;
834             wine_server_call( req );
835         }
836         SERVER_END_REQ;
837
838         if (wm->dlhandle) wine_dll_unload( wm->dlhandle );
839         else UnmapViewOfFile( (LPVOID)wm->module );
840         FreeLibrary16( wm->hDummyMod );
841         RtlFreeHeap( ntdll_get_process_heap(), 0, wm->deps );
842         RtlFreeHeap( ntdll_get_process_heap(), 0, wm );
843     }
844 }
845
846 /***********************************************************************
847  *           MODULE_DecRefCount
848  *
849  * NOTE: Assumes that the process critical section is held!
850  */
851 static void MODULE_DecRefCount( WINE_MODREF *wm )
852 {
853     int i;
854
855     if ( wm->flags & WINE_MODREF_MARKER )
856         return;
857
858     if ( wm->refCount <= 0 )
859         return;
860
861     --wm->refCount;
862     TRACE("(%s) refCount: %d\n", wm->modname, wm->refCount );
863
864     if ( wm->refCount == 0 )
865     {
866         wm->flags |= WINE_MODREF_MARKER;
867
868         for ( i = 0; i < wm->nDeps; i++ )
869             if ( wm->deps[i] )
870                 MODULE_DecRefCount( wm->deps[i] );
871
872         wm->flags &= ~WINE_MODREF_MARKER;
873     }
874 }
875
876 /******************************************************************
877  *              LdrUnloadDll (NTDLL.@)
878  *
879  *
880  */
881 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
882 {
883     NTSTATUS retv = STATUS_SUCCESS;
884
885     TRACE("(%p)\n", hModule);
886
887     RtlEnterCriticalSection( &loader_section );
888
889     /* if we're stopping the whole process (and forcing the removal of all
890      * DLLs) the library will be freed anyway
891      */
892     if (!process_detaching)
893     {
894         WINE_MODREF *wm;
895
896         free_lib_count++;
897         if ((wm = MODULE32_LookupHMODULE( hModule )) != NULL)
898         {
899             TRACE("(%s) - START\n", wm->modname);
900
901             /* Recursively decrement reference counts */
902             MODULE_DecRefCount( wm );
903
904             /* Call process detach notifications */
905             if ( free_lib_count <= 1 )
906             {
907                 MODULE_DllProcessDetach( FALSE, NULL );
908                 MODULE_FlushModrefs();
909             }
910
911             TRACE("END\n");
912         }
913         else
914             retv = STATUS_DLL_NOT_FOUND;
915
916         free_lib_count--;
917     }
918
919     RtlLeaveCriticalSection( &loader_section );
920
921     return retv;
922 }
923
924 /***********************************************************************
925  *           RtlImageNtHeader   (NTDLL.@)
926  */
927 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
928 {
929     IMAGE_NT_HEADERS *ret;
930
931     __TRY
932     {
933         IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
934
935         ret = NULL;
936         if (dos->e_magic == IMAGE_DOS_SIGNATURE)
937         {
938             ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
939             if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
940         }
941     }
942     __EXCEPT(page_fault)
943     {
944         return NULL;
945     }
946     __ENDTRY
947     return ret;
948 }
949
950
951 /***********************************************************************
952  *           RtlImageDirectoryEntryToData   (NTDLL.@)
953  */
954 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
955 {
956     const IMAGE_NT_HEADERS *nt;
957     DWORD addr;
958
959     if ((ULONG_PTR)module & 1)  /* mapped as data file */
960     {
961         module = (HMODULE)((ULONG_PTR)module & ~1);
962         image = FALSE;
963     }
964     if (!(nt = RtlImageNtHeader( module ))) return NULL;
965     if (dir >= nt->OptionalHeader.NumberOfRvaAndSizes) return NULL;
966     if (!(addr = nt->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
967     *size = nt->OptionalHeader.DataDirectory[dir].Size;
968     if (image || addr < nt->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
969
970     /* not mapped as image, need to find the section containing the virtual address */
971     return RtlImageRvaToVa( nt, module, addr, NULL );
972 }
973
974
975 /***********************************************************************
976  *           RtlImageRvaToSection   (NTDLL.@)
977  */
978 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
979                                                    HMODULE module, DWORD rva )
980 {
981     int i;
982     IMAGE_SECTION_HEADER *sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader +
983                                                         nt->FileHeader.SizeOfOptionalHeader);
984     for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
985     {
986         if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
987             return sec;
988     }
989     return NULL;
990 }
991
992
993 /***********************************************************************
994  *           RtlImageRvaToVa   (NTDLL.@)
995  */
996 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
997                               DWORD rva, IMAGE_SECTION_HEADER **section )
998 {
999     IMAGE_SECTION_HEADER *sec;
1000
1001     if (section && *section)  /* try this section first */
1002     {
1003         sec = *section;
1004         if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
1005             goto found;
1006     }
1007     if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
1008  found:
1009     if (section) *section = sec;
1010     return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
1011 }