Removed FIXME when loading second exe file.
[wine] / dlls / ntdll / loader.c
1 /*
2  * Loader functions
3  *
4  * Copyright 1995, 2003 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 "snoop.h"
33 #include "wine/debug.h"
34 #include "wine/server.h"
35 #include "ntdll_misc.h"
36
37 WINE_DEFAULT_DEBUG_CHANNEL(module);
38 WINE_DECLARE_DEBUG_CHANNEL(relay);
39 WINE_DECLARE_DEBUG_CHANNEL(snoop);
40 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
41
42 typedef DWORD (CALLBACK *DLLENTRYPROC)(HMODULE,DWORD,LPVOID);
43
44 WINE_MODREF *MODULE_modref_list = NULL;
45
46 static WINE_MODREF *exe_modref;
47 static int process_detaching = 0;  /* set on process detach to avoid deadlocks with thread detach */
48 static int free_lib_count;   /* recursion depth of LdrUnloadDll calls */
49
50 /* filter for page-fault exceptions */
51 static WINE_EXCEPTION_FILTER(page_fault)
52 {
53     if (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION)
54         return EXCEPTION_EXECUTE_HANDLER;
55     return EXCEPTION_CONTINUE_SEARCH;
56 }
57
58 static const char * const reason_names[] =
59 {
60     "PROCESS_DETACH",
61     "PROCESS_ATTACH",
62     "THREAD_ATTACH",
63     "THREAD_DETACH"
64 };
65
66 static UINT tls_module_count;      /* number of modules with TLS directory */
67 static UINT tls_total_size;        /* total size of TLS storage */
68 static const IMAGE_TLS_DIRECTORY **tls_dirs;  /* array of TLS directories */
69
70 static CRITICAL_SECTION loader_section = CRITICAL_SECTION_INIT( "loader_section" );
71 static WINE_MODREF *cached_modref;
72 static WINE_MODREF *current_modref;
73
74 static NTSTATUS load_dll( LPCSTR libname, DWORD flags, WINE_MODREF** pwm );
75 static FARPROC find_named_export( HMODULE module, IMAGE_EXPORT_DIRECTORY *exports,
76                                   DWORD exp_size, const char *name, int hint );
77
78 /* convert PE image VirtualAddress to Real Address */
79 inline static void *get_rva( HMODULE module, DWORD va )
80 {
81     return (void *)((char *)module + va);
82 }
83
84 /*************************************************************************
85  *              get_modref
86  *
87  * Looks for the referenced HMODULE in the current process
88  * The loader_section must be locked while calling this function.
89  */
90 static WINE_MODREF *get_modref( HMODULE hmod )
91 {
92     WINE_MODREF *wm;
93
94     if (cached_modref && cached_modref->ldr.BaseAddress == hmod) return cached_modref;
95
96     for ( wm = MODULE_modref_list; wm; wm=wm->next )
97     {
98         if (wm->ldr.BaseAddress == hmod)
99         {
100             cached_modref = wm;
101             break;
102         }
103     }
104     return wm;
105 }
106
107
108 /*************************************************************************
109  *              find_forwarded_export
110  *
111  * Find the final function pointer for a forwarded function.
112  * The loader_section must be locked while calling this function.
113  */
114 static FARPROC find_forwarded_export( HMODULE module, const char *forward )
115 {
116     IMAGE_EXPORT_DIRECTORY *exports;
117     DWORD exp_size;
118     WINE_MODREF *wm;
119     char mod_name[256];
120     char *end = strchr(forward, '.');
121     FARPROC proc = NULL;
122
123     if (!end) return NULL;
124     if (end - forward >= sizeof(mod_name)) return NULL;
125     memcpy( mod_name, forward, end - forward );
126     mod_name[end-forward] = 0;
127
128     if (!(wm = MODULE_FindModule( mod_name )))
129     {
130         ERR("module not found for forward '%s' used by '%s'\n",
131             forward, get_modref(module)->filename );
132         return NULL;
133     }
134     if ((exports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
135                                                  IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
136         proc = find_named_export( wm->ldr.BaseAddress, exports, exp_size, end + 1, -1 );
137
138     if (!proc)
139     {
140         ERR("function not found for forward '%s' used by '%s'."
141             " If you are using builtin '%s', try using the native one instead.\n",
142             forward, get_modref(module)->filename, get_modref(module)->modname );
143     }
144     return proc;
145 }
146
147
148 /*************************************************************************
149  *              find_ordinal_export
150  *
151  * Find an exported function by ordinal.
152  * The exports base must have been subtracted from the ordinal already.
153  * The loader_section must be locked while calling this function.
154  */
155 static FARPROC find_ordinal_export( HMODULE module, IMAGE_EXPORT_DIRECTORY *exports,
156                                     DWORD exp_size, int ordinal )
157 {
158     FARPROC proc;
159     DWORD *functions = get_rva( module, exports->AddressOfFunctions );
160
161     if (ordinal >= exports->NumberOfFunctions)
162     {
163         TRACE(" ordinal %ld out of range!\n", ordinal + exports->Base );
164         return NULL;
165     }
166     if (!functions[ordinal]) return NULL;
167
168     proc = get_rva( module, functions[ordinal] );
169
170     /* if the address falls into the export dir, it's a forward */
171     if (((char *)proc >= (char *)exports) && ((char *)proc < (char *)exports + exp_size))
172         return find_forwarded_export( module, (char *)proc );
173
174     if (TRACE_ON(snoop))
175     {
176         proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal );
177     }
178     if (TRACE_ON(relay) && current_modref)
179     {
180         proc = RELAY_GetProcAddress( module, exports, exp_size, proc, current_modref->modname );
181     }
182     return proc;
183 }
184
185
186 /*************************************************************************
187  *              find_named_export
188  *
189  * Find an exported function by name.
190  * The loader_section must be locked while calling this function.
191  */
192 static FARPROC find_named_export( HMODULE module, IMAGE_EXPORT_DIRECTORY *exports,
193                                   DWORD exp_size, const char *name, int hint )
194 {
195     WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
196     DWORD *names = get_rva( module, exports->AddressOfNames );
197     int min = 0, max = exports->NumberOfNames - 1;
198
199     /* first check the hint */
200     if (hint >= 0 && hint <= max)
201     {
202         char *ename = get_rva( module, names[hint] );
203         if (!strcmp( ename, name ))
204             return find_ordinal_export( module, exports, exp_size, ordinals[hint] );
205     }
206
207     /* then do a binary search */
208     while (min <= max)
209     {
210         int res, pos = (min + max) / 2;
211         char *ename = get_rva( module, names[pos] );
212         if (!(res = strcmp( ename, name )))
213             return find_ordinal_export( module, exports, exp_size, ordinals[pos] );
214         if (res > 0) max = pos - 1;
215         else min = pos + 1;
216     }
217     return NULL;
218
219 }
220
221
222 /*************************************************************************
223  *              import_dll
224  *
225  * Import the dll specified by the given import descriptor.
226  * The loader_section must be locked while calling this function.
227  */
228 static WINE_MODREF *import_dll( HMODULE module, IMAGE_IMPORT_DESCRIPTOR *descr )
229 {
230     NTSTATUS status;
231     WINE_MODREF *wmImp;
232     HMODULE imp_mod;
233     IMAGE_EXPORT_DIRECTORY *exports;
234     DWORD exp_size;
235     IMAGE_THUNK_DATA *import_list, *thunk_list;
236     char *name = get_rva( module, descr->Name );
237
238     status = load_dll( name, 0, &wmImp );
239     if (status)
240     {
241         if (status == STATUS_NO_SUCH_FILE)
242             ERR("Module (file) %s (which is needed by %s) not found\n",
243                 name, current_modref->filename);
244         else
245             ERR("Loading module (file) %s (which is needed by %s) failed (error %ld).\n",
246                 name, current_modref->filename, status);
247         return NULL;
248     }
249
250     imp_mod = wmImp->ldr.BaseAddress;
251     if (!(exports = RtlImageDirectoryEntryToData( imp_mod, TRUE,
252                                                   IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
253         return NULL;
254
255     thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
256     if (descr->u.OriginalFirstThunk)
257         import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
258     else
259         import_list = thunk_list;
260
261     while (import_list->u1.Ordinal)
262     {
263         if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
264         {
265             int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
266
267             TRACE("--- Ordinal %s,%d\n", name, ordinal);
268             thunk_list->u1.Function = (PDWORD)find_ordinal_export( imp_mod, exports, exp_size,
269                                                                    ordinal - exports->Base );
270             if (!thunk_list->u1.Function)
271             {
272                 ERR("No implementation for %s.%d imported from %s, setting to 0xdeadbeef\n",
273                     name, ordinal, current_modref->filename );
274                 thunk_list->u1.Function = (PDWORD)0xdeadbeef;
275             }
276         }
277         else  /* import by name */
278         {
279             IMAGE_IMPORT_BY_NAME *pe_name;
280             pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
281             TRACE("--- %s %s.%d\n", pe_name->Name, name, pe_name->Hint);
282             thunk_list->u1.Function = (PDWORD)find_named_export( imp_mod, exports, exp_size,
283                                                                  pe_name->Name, pe_name->Hint );
284             if (!thunk_list->u1.Function)
285             {
286                 ERR("No implementation for %s.%s imported from %s, setting to 0xdeadbeef\n",
287                     name, pe_name->Name, current_modref->filename );
288                 thunk_list->u1.Function = (PDWORD)0xdeadbeef;
289             }
290         }
291         import_list++;
292         thunk_list++;
293     }
294     return wmImp;
295 }
296
297
298 /****************************************************************
299  *      PE_fixup_imports
300  *
301  * Fixup all imports of a given module.
302  * The loader_section must be locked while calling this function.
303  */
304 DWORD PE_fixup_imports( WINE_MODREF *wm )
305 {
306     int i, nb_imports;
307     IMAGE_IMPORT_DESCRIPTOR *imports;
308     WINE_MODREF *prev;
309     DWORD size;
310
311     if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
312                                                   IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
313         return 0;
314
315     nb_imports = size / sizeof(*imports);
316     for (i = 0; i < nb_imports; i++)
317     {
318         if (!imports[i].Name)
319         {
320             nb_imports = i;
321             break;
322         }
323     }
324     if (!nb_imports) return 0;  /* no imports */
325
326     /* Allocate module dependency list */
327     wm->nDeps = nb_imports;
328     wm->deps  = RtlAllocateHeap( ntdll_get_process_heap(), 0, nb_imports*sizeof(WINE_MODREF *) );
329
330     /* load the imported modules. They are automatically
331      * added to the modref list of the process.
332      */
333     prev = current_modref;
334     current_modref = wm;
335     for (i = 0; i < nb_imports; i++)
336     {
337         if (!(wm->deps[i] = import_dll( wm->ldr.BaseAddress, &imports[i] ))) break;
338     }
339     current_modref = prev;
340     return (i < nb_imports);
341 }
342
343
344 /*************************************************************************
345  *              MODULE_AllocModRef
346  *
347  * Allocate a WINE_MODREF structure and add it to the process list
348  * The loader_section must be locked while calling this function.
349  */
350 WINE_MODREF *MODULE_AllocModRef( HMODULE hModule, LPCSTR filename )
351 {
352     WINE_MODREF *wm;
353     IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
354
355     DWORD long_len = strlen( filename );
356     DWORD short_len = GetShortPathNameA( filename, NULL, 0 );
357
358     if ((wm = RtlAllocateHeap( ntdll_get_process_heap(), HEAP_ZERO_MEMORY,
359                                sizeof(*wm) + long_len + short_len + 1 )))
360     {
361         wm->filename = wm->data;
362         memcpy( wm->filename, filename, long_len + 1 );
363         if ((wm->modname = strrchr( wm->filename, '\\' ))) wm->modname++;
364         else wm->modname = wm->filename;
365
366         wm->short_filename = wm->filename + long_len + 1;
367         GetShortPathNameA( wm->filename, wm->short_filename, short_len + 1 );
368         if ((wm->short_modname = strrchr( wm->short_filename, '\\' ))) wm->short_modname++;
369         else wm->short_modname = wm->short_filename;
370
371         wm->next = MODULE_modref_list;
372         if (wm->next) wm->next->prev = wm;
373         MODULE_modref_list = wm;
374
375         wm->ldr.InLoadOrderModuleList.Flink = NULL;
376         wm->ldr.InLoadOrderModuleList.Blink = NULL;
377         wm->ldr.InMemoryOrderModuleList.Flink = NULL;
378         wm->ldr.InMemoryOrderModuleList.Blink = NULL;
379         wm->ldr.InInitializationOrderModuleList.Flink = NULL;
380         wm->ldr.InInitializationOrderModuleList.Blink = NULL;
381         wm->ldr.BaseAddress = hModule;
382         wm->ldr.EntryPoint = (nt->OptionalHeader.AddressOfEntryPoint) ?
383                              ((char *)hModule + nt->OptionalHeader.AddressOfEntryPoint) : 0;
384         wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
385         RtlCreateUnicodeStringFromAsciiz( &wm->ldr.FullDllName, wm->filename);
386         RtlCreateUnicodeStringFromAsciiz( &wm->ldr.BaseDllName, wm->modname);
387         wm->ldr.Flags = 0;
388         wm->ldr.LoadCount = 0;
389         wm->ldr.TlsIndex = -1;
390         wm->ldr.SectionHandle = NULL;
391         wm->ldr.CheckSum = 0;
392         wm->ldr.TimeDateStamp = 0;
393
394         if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL))
395         {
396             if (!exe_modref) exe_modref = wm;
397         }
398         else wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
399     }
400     return wm;
401 }
402
403
404 /*************************************************************************
405  *              alloc_process_tls
406  *
407  * Allocate the process-wide structure for module TLS storage.
408  */
409 static NTSTATUS alloc_process_tls(void)
410 {
411     WINE_MODREF *wm;
412     IMAGE_TLS_DIRECTORY *dir;
413     ULONG size, i;
414
415     for (wm = MODULE_modref_list; wm; wm = wm->next)
416     {
417         if (!(dir = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
418                                                   IMAGE_DIRECTORY_ENTRY_TLS, &size )))
419             continue;
420         size = (dir->EndAddressOfRawData - dir->StartAddressOfRawData) + dir->SizeOfZeroFill;
421         if (!size) continue;
422         tls_total_size += size;
423         tls_module_count++;
424     }
425     if (!tls_module_count) return STATUS_SUCCESS;
426
427     TRACE( "count %u size %u\n", tls_module_count, tls_total_size );
428
429     tls_dirs = RtlAllocateHeap( ntdll_get_process_heap(), 0, tls_module_count * sizeof(*tls_dirs) );
430     if (!tls_dirs) return STATUS_NO_MEMORY;
431
432     for (i = 0, wm = MODULE_modref_list; wm; wm = wm->next)
433     {
434         if (!(dir = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
435                                                   IMAGE_DIRECTORY_ENTRY_TLS, &size )))
436             continue;
437         tls_dirs[i] = dir;
438         *dir->AddressOfIndex = i;
439         wm->ldr.TlsIndex = i;
440         wm->ldr.LoadCount = -1;  /* can't unload it */
441         i++;
442     }
443     return STATUS_SUCCESS;
444 }
445
446
447 /*************************************************************************
448  *              alloc_thread_tls
449  *
450  * Allocate the per-thread structure for module TLS storage.
451  */
452 static NTSTATUS alloc_thread_tls(void)
453 {
454     void **pointers;
455     char *data;
456     UINT i;
457
458     if (!tls_module_count) return STATUS_SUCCESS;
459
460     if (!(pointers = RtlAllocateHeap( ntdll_get_process_heap(), 0,
461                                       tls_module_count * sizeof(*pointers) )))
462         return STATUS_NO_MEMORY;
463
464     if (!(data = RtlAllocateHeap( ntdll_get_process_heap(), 0, tls_total_size )))
465     {
466         RtlFreeHeap( ntdll_get_process_heap(), 0, pointers );
467         return STATUS_NO_MEMORY;
468     }
469
470     for (i = 0; i < tls_module_count; i++)
471     {
472         const IMAGE_TLS_DIRECTORY *dir = tls_dirs[i];
473         ULONG size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
474
475         TRACE( "thread %04lx idx %d: %ld/%ld bytes from %p to %p\n",
476                GetCurrentThreadId(), i, size, dir->SizeOfZeroFill,
477                (void *)dir->StartAddressOfRawData, data );
478
479         pointers[i] = data;
480         memcpy( data, (void *)dir->StartAddressOfRawData, size );
481         data += size;
482         memset( data, 0, dir->SizeOfZeroFill );
483         data += dir->SizeOfZeroFill;
484     }
485     NtCurrentTeb()->tls_ptr = pointers;
486     return STATUS_SUCCESS;
487 }
488
489
490 /*************************************************************************
491  *              call_tls_callbacks
492  */
493 static void call_tls_callbacks( HMODULE module, UINT reason )
494 {
495     const IMAGE_TLS_DIRECTORY *dir;
496     const PIMAGE_TLS_CALLBACK *callback;
497     ULONG dirsize;
498
499     dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
500     if (!dir || !dir->AddressOfCallBacks) return;
501
502     for (callback = dir->AddressOfCallBacks; *callback; callback++)
503     {
504         if (TRACE_ON(relay))
505             DPRINTF("%04lx:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
506                     GetCurrentThreadId(), *callback, module, reason_names[reason] );
507         (*callback)( module, reason, NULL );
508         if (TRACE_ON(relay))
509             DPRINTF("%04lx:Ret  TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
510                     GetCurrentThreadId(), *callback, module, reason_names[reason] );
511     }
512 }
513
514
515 /*************************************************************************
516  *              MODULE_InitDLL
517  */
518 static BOOL MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
519 {
520     char mod_name[32];
521     BOOL retv = TRUE;
522     DLLENTRYPROC entry = wm->ldr.EntryPoint;
523     void *module = wm->ldr.BaseAddress;
524
525     /* Skip calls for modules loaded with special load flags */
526
527     if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return TRUE;
528     if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.BaseAddress, reason );
529     if (!entry || !(wm->ldr.Flags & LDR_IMAGE_IS_DLL)) return TRUE;
530
531     if (TRACE_ON(relay))
532     {
533         size_t len = max( strlen(wm->modname), sizeof(mod_name)-1 );
534         memcpy( mod_name, wm->modname, len );
535         mod_name[len] = 0;
536         DPRINTF("%04lx:Call PE DLL (proc=%p,module=%p (%s),reason=%s,res=%p)\n",
537                 GetCurrentThreadId(), entry, module, mod_name, reason_names[reason], lpReserved );
538     }
539     else TRACE("(%p (%s),%s,%p) - CALL\n", module, wm->modname, reason_names[reason], lpReserved );
540
541     retv = entry( module, reason, lpReserved );
542
543     /* The state of the module list may have changed due to the call
544        to the dll. We cannot assume that this module has not been
545        deleted.  */
546     if (TRACE_ON(relay))
547         DPRINTF("%04lx:Ret  PE DLL (proc=%p,module=%p (%s),reason=%s,res=%p) retval=%x\n",
548                 GetCurrentThreadId(), entry, module, mod_name, reason_names[reason], lpReserved, retv );
549     else TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
550
551     return retv;
552 }
553
554
555 /*************************************************************************
556  *              MODULE_DllProcessAttach
557  *
558  * Send the process attach notification to all DLLs the given module
559  * depends on (recursively). This is somewhat complicated due to the fact that
560  *
561  * - we have to respect the module dependencies, i.e. modules implicitly
562  *   referenced by another module have to be initialized before the module
563  *   itself can be initialized
564  *
565  * - the initialization routine of a DLL can itself call LoadLibrary,
566  *   thereby introducing a whole new set of dependencies (even involving
567  *   the 'old' modules) at any time during the whole process
568  *
569  * (Note that this routine can be recursively entered not only directly
570  *  from itself, but also via LoadLibrary from one of the called initialization
571  *  routines.)
572  *
573  * Furthermore, we need to rearrange the main WINE_MODREF list to allow
574  * the process *detach* notifications to be sent in the correct order.
575  * This must not only take into account module dependencies, but also
576  * 'hidden' dependencies created by modules calling LoadLibrary in their
577  * attach notification routine.
578  *
579  * The strategy is rather simple: we move a WINE_MODREF to the head of the
580  * list after the attach notification has returned.  This implies that the
581  * detach notifications are called in the reverse of the sequence the attach
582  * notifications *returned*.
583  */
584 NTSTATUS MODULE_DllProcessAttach( WINE_MODREF *wm, LPVOID lpReserved )
585 {
586     NTSTATUS status = STATUS_SUCCESS;
587     int i;
588
589     RtlEnterCriticalSection( &loader_section );
590
591     if (!wm)
592     {
593         wm = exe_modref;
594         wm->ldr.LoadCount = -1;  /* can't unload main exe */
595         if ((status = alloc_process_tls()) != STATUS_SUCCESS) goto done;
596         if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto done;
597     }
598     assert( wm );
599
600     /* prevent infinite recursion in case of cyclical dependencies */
601     if (    ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
602          || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
603         goto done;
604
605     TRACE("(%s,%p) - START\n", wm->modname, lpReserved );
606
607     /* Tag current MODREF to prevent recursive loop */
608     wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
609
610     /* Recursively attach all DLLs this one depends on */
611     for ( i = 0; i < wm->nDeps; i++ )
612     {
613         if (!wm->deps[i]) continue;
614         if ((status = MODULE_DllProcessAttach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
615     }
616
617     /* Call DLL entry point */
618     if (status == STATUS_SUCCESS)
619     {
620         WINE_MODREF *prev = current_modref;
621         current_modref = wm;
622         if (MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved ))
623             wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
624         else
625             status = STATUS_DLL_INIT_FAILED;
626         current_modref = prev;
627     }
628
629     /* Re-insert MODREF at head of list */
630     if (status == STATUS_SUCCESS && wm->prev )
631     {
632         wm->prev->next = wm->next;
633         if ( wm->next ) wm->next->prev = wm->prev;
634
635         wm->prev = NULL;
636         wm->next = MODULE_modref_list;
637         MODULE_modref_list = wm->next->prev = wm;
638     }
639
640     /* Remove recursion flag */
641     wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
642
643     TRACE("(%s,%p) - END\n", wm->modname, lpReserved );
644
645  done:
646     RtlLeaveCriticalSection( &loader_section );
647     return status;
648 }
649
650 /*************************************************************************
651  *              MODULE_DllProcessDetach
652  *
653  * Send DLL process detach notifications.  See the comment about calling
654  * sequence at MODULE_DllProcessAttach.  Unless the bForceDetach flag
655  * is set, only DLLs with zero refcount are notified.
656  */
657 static void MODULE_DllProcessDetach( BOOL bForceDetach, LPVOID lpReserved )
658 {
659     WINE_MODREF *wm;
660
661     RtlEnterCriticalSection( &loader_section );
662     if (bForceDetach) process_detaching = 1;
663     do
664     {
665         for ( wm = MODULE_modref_list; wm; wm = wm->next )
666         {
667             /* Check whether to detach this DLL */
668             if ( !(wm->ldr.Flags & LDR_PROCESS_ATTACHED) )
669                 continue;
670             if ( wm->ldr.LoadCount && !bForceDetach )
671                 continue;
672
673             /* Call detach notification */
674             wm->ldr.Flags &= ~LDR_PROCESS_ATTACHED;
675             MODULE_InitDLL( wm, DLL_PROCESS_DETACH, lpReserved );
676
677             /* Restart at head of WINE_MODREF list, as entries might have
678                been added and/or removed while performing the call ... */
679             break;
680         }
681     } while ( wm );
682
683     RtlLeaveCriticalSection( &loader_section );
684 }
685
686 /*************************************************************************
687  *              MODULE_DllThreadAttach
688  *
689  * Send DLL thread attach notifications. These are sent in the
690  * reverse sequence of process detach notification.
691  *
692  */
693 NTSTATUS MODULE_DllThreadAttach( LPVOID lpReserved )
694 {
695     WINE_MODREF *wm;
696     NTSTATUS status;
697
698     /* don't do any attach calls if process is exiting */
699     if (process_detaching) return STATUS_SUCCESS;
700     /* FIXME: there is still a race here */
701
702     RtlEnterCriticalSection( &loader_section );
703
704     if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto done;
705
706     for ( wm = MODULE_modref_list; wm; wm = wm->next )
707         if ( !wm->next )
708             break;
709
710     for ( ; wm; wm = wm->prev )
711     {
712         if ( !(wm->ldr.Flags & LDR_PROCESS_ATTACHED) )
713             continue;
714         if ( wm->ldr.Flags & LDR_NO_DLL_CALLS )
715             continue;
716
717         MODULE_InitDLL( wm, DLL_THREAD_ATTACH, lpReserved );
718     }
719
720 done:
721     RtlLeaveCriticalSection( &loader_section );
722     return status;
723 }
724
725 /******************************************************************
726  *              LdrDisableThreadCalloutsForDll (NTDLL.@)
727  *
728  */
729 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
730 {
731     WINE_MODREF *wm;
732     NTSTATUS    ret = STATUS_SUCCESS;
733
734     RtlEnterCriticalSection( &loader_section );
735
736     wm = get_modref( hModule );
737     if (!wm || wm->ldr.TlsIndex != -1)
738         ret = STATUS_DLL_NOT_FOUND;
739     else
740         wm->ldr.Flags |= LDR_NO_DLL_CALLS;
741
742     RtlLeaveCriticalSection( &loader_section );
743
744     return ret;
745 }
746
747 /******************************************************************
748  *              LdrFindEntryForAddress (NTDLL.@)
749  *
750  * The loader_section must be locked while calling this function
751  */
752 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* mod)
753 {
754     WINE_MODREF*        wm;
755
756     for ( wm = MODULE_modref_list; wm; wm = wm->next )
757     {
758         if ((const void *)wm->ldr.BaseAddress <= addr &&
759             (char *)addr < (char*)wm->ldr.BaseAddress + wm->ldr.SizeOfImage)
760         {
761             *mod = &wm->ldr;
762             return STATUS_SUCCESS;
763         }
764     }
765     return STATUS_NO_MORE_ENTRIES;
766 }
767
768 /**********************************************************************
769  *          MODULE_FindModule
770  *
771  * Find a (loaded) win32 module depending on path
772  *      LPCSTR path: [in] pathname of module/library to be found
773  *
774  * The loader_section must be locked while calling this function
775  * RETURNS
776  *      the module handle if found
777  *      0 if not
778  */
779 WINE_MODREF *MODULE_FindModule(LPCSTR path)
780 {
781     WINE_MODREF *wm;
782     char dllname[260], *p;
783
784     /* Append .DLL to name if no extension present */
785     strcpy( dllname, path );
786     if (!(p = strrchr( dllname, '.')) || strchr( p, '/' ) || strchr( p, '\\'))
787             strcat( dllname, ".DLL" );
788
789     if ((wm = cached_modref) != NULL)
790     {
791         if ( !FILE_strcasecmp( dllname, wm->modname ) ) return wm;
792         if ( !FILE_strcasecmp( dllname, wm->filename ) ) return wm;
793         if ( !FILE_strcasecmp( dllname, wm->short_modname ) ) return wm;
794         if ( !FILE_strcasecmp( dllname, wm->short_filename ) ) return wm;
795     }
796
797     for ( wm = MODULE_modref_list; wm; wm = wm->next )
798     {
799         if ( !FILE_strcasecmp( dllname, wm->modname ) ) break;
800         if ( !FILE_strcasecmp( dllname, wm->filename ) ) break;
801         if ( !FILE_strcasecmp( dllname, wm->short_modname ) ) break;
802         if ( !FILE_strcasecmp( dllname, wm->short_filename ) ) break;
803     }
804     cached_modref = wm;
805     return wm;
806 }
807
808
809 /******************************************************************
810  *              LdrLockLoaderLock  (NTDLL.@)
811  *
812  * Note: flags are not implemented.
813  * Flag 0x01 is used to raise exceptions on errors.
814  * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
815  */
816 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG *magic )
817 {
818     if (flags) FIXME( "flags %lx not supported\n", flags );
819
820     if (result) *result = 1;
821     if (!magic) return STATUS_INVALID_PARAMETER_3;
822     RtlEnterCriticalSection( &loader_section );
823     *magic = GetCurrentThreadId();
824     return STATUS_SUCCESS;
825 }
826
827
828 /******************************************************************
829  *              LdrUnlockLoaderUnlock  (NTDLL.@)
830  */
831 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG magic )
832 {
833     if (magic)
834     {
835         if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
836         RtlLeaveCriticalSection( &loader_section );
837     }
838     return STATUS_SUCCESS;
839 }
840
841
842 /******************************************************************
843  *              LdrGetDllHandle (NTDLL.@)
844  *
845  *
846  */
847 NTSTATUS WINAPI LdrGetDllHandle(ULONG x, ULONG y, PUNICODE_STRING name, HMODULE *base)
848 {
849     WINE_MODREF *wm;
850     STRING str;
851
852     if (x != 0 || y != 0)
853         FIXME("Unknown behavior, please report\n");
854
855     /* FIXME: we should store module name information as unicode */
856     RtlUnicodeStringToAnsiString( &str, name, TRUE );
857     wm = MODULE_FindModule( str.Buffer );
858     RtlFreeAnsiString( &str );
859
860     if (!wm)
861     {
862         *base = 0;
863         return STATUS_DLL_NOT_FOUND;
864     }
865
866     *base = wm->ldr.BaseAddress;
867
868     TRACE("%lx %lx %s -> %p\n", x, y, debugstr_us(name), *base);
869
870     return STATUS_SUCCESS;
871 }
872
873
874 /******************************************************************
875  *              LdrGetProcedureAddress  (NTDLL.@)
876  */
877 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, PANSI_STRING name, ULONG ord, PVOID *address)
878 {
879     IMAGE_EXPORT_DIRECTORY *exports;
880     DWORD exp_size;
881     NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
882
883     RtlEnterCriticalSection( &loader_section );
884
885     if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
886                                                  IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
887     {
888         void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1 )
889                           : find_ordinal_export( module, exports, exp_size, ord - exports->Base );
890         if (proc)
891         {
892             *address = proc;
893             ret = STATUS_SUCCESS;
894         }
895     }
896     else
897     {
898         /* check if the module itself is invalid to return the proper error */
899         if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
900     }
901
902     RtlLeaveCriticalSection( &loader_section );
903     return ret;
904 }
905
906
907 /***********************************************************************
908  *      allocate_lib_dir
909  *
910  * helper for MODULE_LoadLibraryExA.  Allocate space to hold the directory
911  * portion of the provided name and put the name in it.
912  *
913  */
914 static LPCSTR allocate_lib_dir(LPCSTR libname)
915 {
916     LPCSTR p, pmax;
917     LPSTR result;
918     int length;
919
920     pmax = libname;
921     if ((p = strrchr( pmax, '\\' ))) pmax = p + 1;
922     if ((p = strrchr( pmax, '/' ))) pmax = p + 1; /* Naughty.  MSDN says don't */
923     if (pmax == libname && pmax[0] && pmax[1] == ':') pmax += 2;
924
925     length = pmax - libname;
926
927     result = RtlAllocateHeap (ntdll_get_process_heap(), 0, length+1);
928
929     if (result)
930     {
931         strncpy (result, libname, length);
932         result [length] = '\0';
933     }
934
935     return result;
936 }
937
938 /***********************************************************************
939  *      load_dll  (internal)
940  *
941  * Load a PE style module according to the load order.
942  *
943  * libdir is used to support LOAD_WITH_ALTERED_SEARCH_PATH during the recursion
944  *        on this function.  When first called from LoadLibraryExA it will be
945  *        NULL but thereafter it may point to a buffer containing the path
946  *        portion of the library name.  Note that the recursion all occurs
947  *        within a Critical section (see LoadLibraryExA) so the use of a
948  *        static is acceptable.
949  *        (We have to use a static variable at some point anyway, to pass the
950  *        information from BUILTIN32_dlopen through dlopen and the builtin's
951  *        init function into load_library).
952  * allocated_libdir is TRUE in the stack frame that allocated libdir
953  */
954 static NTSTATUS load_dll( LPCSTR libname, DWORD flags, WINE_MODREF** pwm )
955 {
956     int i;
957     enum loadorder_type loadorder[LOADORDER_NTYPES];
958     LPSTR filename;
959     const char *filetype = "";
960     DWORD found;
961     BOOL allocated_libdir = FALSE;
962     static LPCSTR libdir = NULL; /* See above */
963     NTSTATUS nts = STATUS_SUCCESS;
964
965     *pwm = NULL;
966     if ( !libname ) return STATUS_DLL_NOT_FOUND; /* FIXME ? */
967
968     filename = RtlAllocateHeap ( ntdll_get_process_heap(), 0, MAX_PATH + 1 );
969     if ( !filename ) return STATUS_NO_MEMORY;
970     *filename = 0; /* Just in case we don't set it before goto error */
971
972     RtlEnterCriticalSection( &loader_section );
973
974     if ((flags & LOAD_WITH_ALTERED_SEARCH_PATH) && FILE_contains_path(libname))
975     {
976         if (!(libdir = allocate_lib_dir(libname)))
977         {
978             nts = STATUS_NO_MEMORY;
979             goto error;
980         }
981         allocated_libdir = TRUE;
982     }
983
984     if (!libdir || allocated_libdir)
985         found = SearchPathA(NULL, libname, ".dll", MAX_PATH, filename, NULL);
986     else
987         found = DIR_SearchAlternatePath(libdir, libname, ".dll", MAX_PATH, filename, NULL);
988
989     /* build the modules filename */
990     if (!found)
991     {
992         if (!MODULE_GetBuiltinPath( libname, ".dll", filename, MAX_PATH ))
993         {
994             nts = STATUS_INTERNAL_ERROR;
995             goto error;
996         }
997     }
998
999     /* Check for already loaded module */
1000     if (!(*pwm = MODULE_FindModule(filename)) && !FILE_contains_path(libname))
1001     {
1002         LPSTR   fn = RtlAllocateHeap ( ntdll_get_process_heap(), 0, MAX_PATH + 1 );
1003         if (fn)
1004         {
1005             /* since the default loading mechanism uses a more detailed algorithm
1006              * than SearchPath (like using PATH, which can even be modified between
1007              * two attempts of loading the same DLL), the look-up above (with
1008              * SearchPath) can have put the file in system directory, whereas it
1009              * has already been loaded but with a different path. So do a specific
1010              * look-up with filename (without any path)
1011              */
1012             strcpy ( fn, libname );
1013             /* if the filename doesn't have an extension append .DLL */
1014             if (!strrchr( fn, '.')) strcat( fn, ".dll" );
1015             if ((*pwm = MODULE_FindModule( fn )) != NULL)
1016                 strcpy( filename, fn );
1017             RtlFreeHeap( ntdll_get_process_heap(), 0, fn );
1018         }
1019     }
1020     if (*pwm)
1021     {
1022         if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
1023
1024         if (((*pwm)->ldr.Flags & LDR_DONT_RESOLVE_REFS) &&
1025             !(flags & DONT_RESOLVE_DLL_REFERENCES))
1026         {
1027             (*pwm)->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
1028             PE_fixup_imports( *pwm );
1029         }
1030         TRACE("Already loaded module '%s' at %p, count=%d\n", filename, (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
1031         if (allocated_libdir)
1032         {
1033             RtlFreeHeap( ntdll_get_process_heap(), 0, (LPSTR)libdir );
1034             libdir = NULL;
1035         }
1036         RtlLeaveCriticalSection( &loader_section );
1037         RtlFreeHeap( ntdll_get_process_heap(), 0, filename );
1038         return STATUS_SUCCESS;
1039     }
1040
1041     MODULE_GetLoadOrder( loadorder, filename, TRUE);
1042
1043     for (i = 0; i < LOADORDER_NTYPES; i++)
1044     {
1045         if (loadorder[i] == LOADORDER_INVALID) break;
1046
1047         switch (loadorder[i])
1048         {
1049         case LOADORDER_DLL:
1050             TRACE("Trying native dll '%s'\n", filename);
1051             nts = PE_LoadLibraryExA(filename, flags, pwm);
1052             filetype = "native";
1053             break;
1054             
1055         case LOADORDER_BI:
1056             TRACE("Trying built-in '%s'\n", filename);
1057             nts = BUILTIN32_LoadLibraryExA(filename, flags, pwm);
1058             filetype = "builtin";
1059             break;
1060             
1061         default:
1062             nts = STATUS_INTERNAL_ERROR;
1063             break;
1064         }
1065
1066         if (nts == STATUS_SUCCESS)
1067         {
1068             /* Initialize DLL just loaded */
1069             TRACE("Loaded module '%s' (%s) at %p\n", filename, filetype, (*pwm)->ldr.BaseAddress);
1070             if (!TRACE_ON(module))
1071                 TRACE_(loaddll)("Loaded module '%s' : %s\n", filename, filetype);
1072             /* Set the ldr.LoadCount here so that an attach failure will */
1073             /* decrement the dependencies through the MODULE_FreeLibrary call. */
1074             (*pwm)->ldr.LoadCount = 1;
1075             
1076             if (allocated_libdir)
1077             {
1078                 RtlFreeHeap( ntdll_get_process_heap(), 0, (LPSTR)libdir );
1079                 libdir = NULL;
1080             }
1081             RtlLeaveCriticalSection( &loader_section );
1082             RtlFreeHeap( ntdll_get_process_heap(), 0, filename );
1083             return nts;
1084         }
1085
1086         if (nts != STATUS_NO_SUCH_FILE)
1087         {
1088             WARN("Loading of %s DLL %s failed (status %ld).\n",
1089                  filetype, filename, nts);
1090             break;
1091         }
1092     }
1093
1094  error:
1095     if (allocated_libdir)
1096     {
1097         RtlFreeHeap( ntdll_get_process_heap(), 0, (LPSTR)libdir );
1098         libdir = NULL;
1099     }
1100     RtlLeaveCriticalSection( &loader_section );
1101     WARN("Failed to load module '%s'; status=%ld\n", filename, nts);
1102     RtlFreeHeap( ntdll_get_process_heap(), 0, filename );
1103     return nts;
1104 }
1105
1106 /******************************************************************
1107  *              LdrLoadDll (NTDLL.@)
1108  */
1109 NTSTATUS WINAPI LdrLoadDll(LPCWSTR path_name, DWORD flags, PUNICODE_STRING libname, HMODULE* hModule)
1110 {
1111     WINE_MODREF *wm;
1112     NTSTATUS    nts = STATUS_SUCCESS;
1113     STRING      str;
1114
1115     RtlUnicodeStringToAnsiString(&str, libname, TRUE);
1116
1117     RtlEnterCriticalSection( &loader_section );
1118
1119     switch (nts = load_dll( str.Buffer, flags, &wm ))
1120     {
1121     case STATUS_SUCCESS:
1122         nts = MODULE_DllProcessAttach( wm, NULL );
1123         if (nts != STATUS_SUCCESS)
1124         {
1125             WARN("Attach failed for module '%s'.\n", str.Buffer);
1126             LdrUnloadDll(wm->ldr.BaseAddress);
1127             wm = NULL;
1128         }
1129         break;
1130     case STATUS_NO_SUCH_FILE:
1131         nts = STATUS_DLL_NOT_FOUND;
1132         break;
1133     default: /* keep error code as it is (memory...) */
1134         break;
1135     }
1136
1137     *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
1138     
1139     RtlLeaveCriticalSection( &loader_section );
1140
1141     RtlFreeAnsiString(&str);
1142
1143     return nts;
1144 }
1145
1146 /******************************************************************
1147  *              LdrQueryProcessModuleInformation
1148  *
1149  */
1150 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi, 
1151                                                  ULONG buf_size, ULONG* req_size)
1152 {
1153     SYSTEM_MODULE*      sm = &smi->Modules[0];
1154     ULONG               size = sizeof(ULONG);
1155     NTSTATUS            nts = STATUS_SUCCESS;
1156     ANSI_STRING         str;
1157     char*               ptr;
1158     WINE_MODREF*        wm;
1159
1160     smi->ModulesCount = 0;
1161
1162     RtlEnterCriticalSection( &loader_section );
1163     for ( wm = MODULE_modref_list; wm; wm = wm->next )
1164     {
1165         size += sizeof(*sm);
1166         if (size <= buf_size)
1167         {
1168             sm->Reserved1 = 0; /* FIXME */
1169             sm->Reserved2 = 0; /* FIXME */
1170             sm->ImageBaseAddress = wm->ldr.BaseAddress;
1171             sm->ImageSize = wm->ldr.SizeOfImage;
1172             sm->Flags = wm->ldr.Flags;
1173             sm->Id = 0; /* FIXME */
1174             sm->Rank = 0; /* FIXME */
1175             sm->Unknown = 0; /* FIXME */
1176             str.Length = 0;
1177             str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
1178             str.Buffer = sm->Name;
1179             RtlUnicodeStringToAnsiString(&str, &wm->ldr.FullDllName, FALSE);
1180             ptr = strrchr(sm->Name, '\\');
1181             sm->NameOffset = (ptr != NULL) ? (ptr - (char*)sm->Name + 1) : 0;
1182
1183             smi->ModulesCount++;
1184             sm++;
1185         }
1186         else nts = STATUS_INFO_LENGTH_MISMATCH;
1187     }
1188     RtlLeaveCriticalSection( &loader_section );
1189
1190     if (req_size) *req_size = size;
1191
1192     return nts;
1193 }
1194
1195 /******************************************************************
1196  *              LdrShutdownProcess (NTDLL.@)
1197  *
1198  */
1199 void WINAPI LdrShutdownProcess(void)
1200 {
1201     TRACE("()\n");
1202     MODULE_DllProcessDetach( TRUE, (LPVOID)1 );
1203 }
1204
1205 /******************************************************************
1206  *              LdrShutdownThread (NTDLL.@)
1207  *
1208  */
1209 void WINAPI LdrShutdownThread(void)
1210 {
1211     WINE_MODREF *wm;
1212     TRACE("()\n");
1213
1214     /* don't do any detach calls if process is exiting */
1215     if (process_detaching) return;
1216     /* FIXME: there is still a race here */
1217
1218     RtlEnterCriticalSection( &loader_section );
1219
1220     for ( wm = MODULE_modref_list; wm; wm = wm->next )
1221     {
1222         if ( !(wm->ldr.Flags & LDR_PROCESS_ATTACHED) )
1223             continue;
1224         if ( wm->ldr.Flags & LDR_NO_DLL_CALLS )
1225             continue;
1226
1227         MODULE_InitDLL( wm, DLL_THREAD_DETACH, NULL );
1228     }
1229
1230     RtlLeaveCriticalSection( &loader_section );
1231 }
1232
1233 /***********************************************************************
1234  *           MODULE_FlushModrefs
1235  *
1236  * Remove all unused modrefs and call the internal unloading routines
1237  * for the library type.
1238  *
1239  * The loader_section must be locked while calling this function.
1240  */
1241 static void MODULE_FlushModrefs(void)
1242 {
1243     WINE_MODREF *wm, *next;
1244
1245     for (wm = MODULE_modref_list; wm; wm = next)
1246     {
1247         next = wm->next;
1248
1249         if (wm->ldr.LoadCount)
1250             continue;
1251
1252         /* Unlink this modref from the chain */
1253         if (wm->next)
1254             wm->next->prev = wm->prev;
1255         if (wm->prev)
1256             wm->prev->next = wm->next;
1257         if (wm == MODULE_modref_list)
1258             MODULE_modref_list = wm->next;
1259
1260         TRACE(" unloading %s\n", wm->filename);
1261         if (!TRACE_ON(module))
1262             TRACE_(loaddll)("Unloaded module '%s' : %s\n", wm->filename,
1263                             wm->dlhandle ? "builtin" : "native" );
1264
1265         SERVER_START_REQ( unload_dll )
1266         {
1267             req->base = wm->ldr.BaseAddress;
1268             wine_server_call( req );
1269         }
1270         SERVER_END_REQ;
1271
1272         if (wm->dlhandle) wine_dll_unload( wm->dlhandle );
1273         else NtUnmapViewOfSection( GetCurrentProcess(), wm->ldr.BaseAddress );
1274         if (cached_modref == wm) cached_modref = NULL;
1275         RtlFreeHeap( ntdll_get_process_heap(), 0, wm->deps );
1276         RtlFreeHeap( ntdll_get_process_heap(), 0, wm );
1277     }
1278 }
1279
1280 /***********************************************************************
1281  *           MODULE_DecRefCount
1282  *
1283  * The loader_section must be locked while calling this function.
1284  */
1285 static void MODULE_DecRefCount( WINE_MODREF *wm )
1286 {
1287     int i;
1288
1289     if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
1290         return;
1291
1292     if ( wm->ldr.LoadCount <= 0 )
1293         return;
1294
1295     --wm->ldr.LoadCount;
1296     TRACE("(%s) ldr.LoadCount: %d\n", wm->modname, wm->ldr.LoadCount );
1297
1298     if ( wm->ldr.LoadCount == 0 )
1299     {
1300         wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
1301
1302         for ( i = 0; i < wm->nDeps; i++ )
1303             if ( wm->deps[i] )
1304                 MODULE_DecRefCount( wm->deps[i] );
1305
1306         wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
1307     }
1308 }
1309
1310 /******************************************************************
1311  *              LdrUnloadDll (NTDLL.@)
1312  *
1313  *
1314  */
1315 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
1316 {
1317     NTSTATUS retv = STATUS_SUCCESS;
1318
1319     TRACE("(%p)\n", hModule);
1320
1321     RtlEnterCriticalSection( &loader_section );
1322
1323     /* if we're stopping the whole process (and forcing the removal of all
1324      * DLLs) the library will be freed anyway
1325      */
1326     if (!process_detaching)
1327     {
1328         WINE_MODREF *wm;
1329
1330         free_lib_count++;
1331         if ((wm = get_modref( hModule )) != NULL)
1332         {
1333             TRACE("(%s) - START\n", wm->modname);
1334
1335             /* Recursively decrement reference counts */
1336             MODULE_DecRefCount( wm );
1337
1338             /* Call process detach notifications */
1339             if ( free_lib_count <= 1 )
1340             {
1341                 MODULE_DllProcessDetach( FALSE, NULL );
1342                 MODULE_FlushModrefs();
1343             }
1344
1345             TRACE("END\n");
1346         }
1347         else
1348             retv = STATUS_DLL_NOT_FOUND;
1349
1350         free_lib_count--;
1351     }
1352
1353     RtlLeaveCriticalSection( &loader_section );
1354
1355     return retv;
1356 }
1357
1358 /***********************************************************************
1359  *           RtlImageNtHeader   (NTDLL.@)
1360  */
1361 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
1362 {
1363     IMAGE_NT_HEADERS *ret;
1364
1365     __TRY
1366     {
1367         IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
1368
1369         ret = NULL;
1370         if (dos->e_magic == IMAGE_DOS_SIGNATURE)
1371         {
1372             ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
1373             if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
1374         }
1375     }
1376     __EXCEPT(page_fault)
1377     {
1378         return NULL;
1379     }
1380     __ENDTRY
1381     return ret;
1382 }
1383
1384
1385 /***********************************************************************
1386  *           RtlImageDirectoryEntryToData   (NTDLL.@)
1387  */
1388 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
1389 {
1390     const IMAGE_NT_HEADERS *nt;
1391     DWORD addr;
1392
1393     if ((ULONG_PTR)module & 1)  /* mapped as data file */
1394     {
1395         module = (HMODULE)((ULONG_PTR)module & ~1);
1396         image = FALSE;
1397     }
1398     if (!(nt = RtlImageNtHeader( module ))) return NULL;
1399     if (dir >= nt->OptionalHeader.NumberOfRvaAndSizes) return NULL;
1400     if (!(addr = nt->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
1401     *size = nt->OptionalHeader.DataDirectory[dir].Size;
1402     if (image || addr < nt->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
1403
1404     /* not mapped as image, need to find the section containing the virtual address */
1405     return RtlImageRvaToVa( nt, module, addr, NULL );
1406 }
1407
1408
1409 /***********************************************************************
1410  *           RtlImageRvaToSection   (NTDLL.@)
1411  */
1412 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
1413                                                    HMODULE module, DWORD rva )
1414 {
1415     int i;
1416     IMAGE_SECTION_HEADER *sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader +
1417                                                         nt->FileHeader.SizeOfOptionalHeader);
1418     for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1419     {
1420         if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
1421             return sec;
1422     }
1423     return NULL;
1424 }
1425
1426
1427 /***********************************************************************
1428  *           RtlImageRvaToVa   (NTDLL.@)
1429  */
1430 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
1431                               DWORD rva, IMAGE_SECTION_HEADER **section )
1432 {
1433     IMAGE_SECTION_HEADER *sec;
1434
1435     if (section && *section)  /* try this section first */
1436     {
1437         sec = *section;
1438         if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
1439             goto found;
1440     }
1441     if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
1442  found:
1443     if (section) *section = sec;
1444     return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
1445 }