4 * Copyright 1995 Alexandre Julliard
5 * Copyright 2002 Dmitry Timoshkov for Codeweavers
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.
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.
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
30 #include "wine/exception.h"
32 #include "wine/debug.h"
33 #include "wine/server.h"
34 #include "ntdll_misc.h"
36 WINE_DEFAULT_DEBUG_CHANNEL(ntdll);
37 WINE_DECLARE_DEBUG_CHANNEL(module);
38 WINE_DECLARE_DEBUG_CHANNEL(module);
39 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
41 WINE_MODREF *MODULE_modref_list = NULL;
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 */
47 /* filter for page-fault exceptions */
48 static WINE_EXCEPTION_FILTER(page_fault)
50 if (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION)
51 return EXCEPTION_EXECUTE_HANDLER;
52 return EXCEPTION_CONTINUE_SEARCH;
55 static CRITICAL_SECTION loader_section = CRITICAL_SECTION_INIT( "loader_section" );
57 /*************************************************************************
58 * MODULE32_LookupHMODULE
59 * looks for the referenced HMODULE in the current process
60 * NOTE: Assumes that the process critical section is held!
62 static WINE_MODREF *MODULE32_LookupHMODULE( HMODULE hmod )
70 ERR("tried to lookup %p in win32 module handler!\n",hmod);
73 for ( wm = MODULE_modref_list; wm; wm=wm->next )
74 if (wm->module == hmod)
79 /*************************************************************************
82 * Allocate a WINE_MODREF structure and add it to the process list
83 * NOTE: Assumes that the process critical section is held!
85 WINE_MODREF *MODULE_AllocModRef( HMODULE hModule, LPCSTR filename )
88 IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
90 DWORD long_len = strlen( filename );
91 DWORD short_len = GetShortPathNameA( filename, NULL, 0 );
93 if ((wm = RtlAllocateHeap( ntdll_get_process_heap(), HEAP_ZERO_MEMORY,
94 sizeof(*wm) + long_len + short_len + 1 )))
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;
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;
109 wm->next = MODULE_modref_list;
110 if (wm->next) wm->next->prev = wm;
111 MODULE_modref_list = wm;
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);
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;
132 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL))
134 if (!exe_modref) exe_modref = wm;
135 else FIXME( "Trying to load second .EXE file: %s\n", filename );
141 /*************************************************************************
144 static BOOL MODULE_InitDLL( WINE_MODREF *wm, DWORD type, LPVOID lpReserved )
146 static const char * const typeName[] = { "PROCESS_DETACH", "PROCESS_ATTACH",
147 "THREAD_ATTACH", "THREAD_DETACH" };
150 /* Skip calls for modules loaded with special load flags */
152 if (wm->flags & WINE_MODREF_DONT_RESOLVE_REFS) return TRUE;
154 TRACE("(%s,%s,%p) - CALL\n", wm->modname, typeName[type], lpReserved );
156 /* Call the initialization routine */
157 retv = PE_InitDLL( wm->module, type, lpReserved );
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
162 TRACE("(%p,%s,%p) - RETURN %d\n", wm, typeName[type], lpReserved, retv );
168 /*************************************************************************
169 * MODULE_DllProcessAttach
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
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
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
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
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.
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*.
197 BOOL MODULE_DllProcessAttach( WINE_MODREF *wm, LPVOID lpReserved )
202 RtlEnterCriticalSection( &loader_section );
211 /* prevent infinite recursion in case of cyclical dependencies */
212 if ( ( wm->flags & WINE_MODREF_MARKER )
213 || ( wm->flags & WINE_MODREF_PROCESS_ATTACHED ) )
216 TRACE("(%s,%p) - START\n", wm->modname, lpReserved );
218 /* Tag current MODREF to prevent recursive loop */
219 wm->flags |= WINE_MODREF_MARKER;
221 /* Recursively attach all DLLs this one depends on */
222 for ( i = 0; retv && i < wm->nDeps; i++ )
224 retv = MODULE_DllProcessAttach( wm->deps[i], lpReserved );
226 /* Call DLL entry point */
229 retv = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
231 wm->flags |= WINE_MODREF_PROCESS_ATTACHED;
234 /* Re-insert MODREF at head of list */
235 if ( retv && wm->prev )
237 wm->prev->next = wm->next;
238 if ( wm->next ) wm->next->prev = wm->prev;
241 wm->next = MODULE_modref_list;
242 MODULE_modref_list = wm->next->prev = wm;
245 /* Remove recursion flag */
246 wm->flags &= ~WINE_MODREF_MARKER;
248 TRACE("(%s,%p) - END\n", wm->modname, lpReserved );
251 RtlLeaveCriticalSection( &loader_section );
255 /*************************************************************************
256 * MODULE_DllProcessDetach
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.
262 void MODULE_DllProcessDetach( BOOL bForceDetach, LPVOID lpReserved )
266 RtlEnterCriticalSection( &loader_section );
267 if (bForceDetach) process_detaching = 1;
270 for ( wm = MODULE_modref_list; wm; wm = wm->next )
272 /* Check whether to detach this DLL */
273 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
275 if ( wm->refCount > 0 && !bForceDetach )
278 /* Call detach notification */
279 wm->flags &= ~WINE_MODREF_PROCESS_ATTACHED;
280 MODULE_InitDLL( wm, DLL_PROCESS_DETACH, lpReserved );
282 /* Restart at head of WINE_MODREF list, as entries might have
283 been added and/or removed while performing the call ... */
288 RtlLeaveCriticalSection( &loader_section );
291 /*************************************************************************
292 * MODULE_DllThreadAttach
294 * Send DLL thread attach notifications. These are sent in the
295 * reverse sequence of process detach notification.
298 void MODULE_DllThreadAttach( LPVOID lpReserved )
302 /* don't do any attach calls if process is exiting */
303 if (process_detaching) return;
304 /* FIXME: there is still a race here */
306 RtlEnterCriticalSection( &loader_section );
310 for ( wm = MODULE_modref_list; wm; wm = wm->next )
314 for ( ; wm; wm = wm->prev )
316 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
318 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
321 MODULE_InitDLL( wm, DLL_THREAD_ATTACH, lpReserved );
324 RtlLeaveCriticalSection( &loader_section );
327 /******************************************************************
328 * LdrDisableThreadCalloutsForDll (NTDLL.@)
331 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
334 NTSTATUS ret = STATUS_SUCCESS;
336 RtlEnterCriticalSection( &loader_section );
338 wm = MODULE32_LookupHMODULE( hModule );
340 ret = STATUS_DLL_NOT_FOUND;
342 wm->flags |= WINE_MODREF_NO_DLL_CALLS;
344 RtlLeaveCriticalSection( &loader_section );
349 /******************************************************************
350 * LdrFindEntryForAddress (NTDLL.@)
352 * The loader_section must be locked while calling this function
354 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* mod)
358 for ( wm = MODULE_modref_list; wm; wm = wm->next )
360 if ((const void *)wm->module <= addr &&
361 (char *)addr < (char*)wm->module + wm->ldr.SizeOfImage)
364 return STATUS_SUCCESS;
367 return STATUS_NO_MORE_ENTRIES;
370 /**********************************************************************
373 * Find a (loaded) win32 module depending on path
374 * LPCSTR path: [in] pathname of module/library to be found
376 * The loader_section must be locked while calling this function
378 * the module handle if found
381 WINE_MODREF *MODULE_FindModule(LPCSTR path)
384 char dllname[260], *p;
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" );
391 for ( wm = MODULE_modref_list; wm; wm = wm->next )
393 if ( !FILE_strcasecmp( dllname, wm->modname ) )
395 if ( !FILE_strcasecmp( dllname, wm->filename ) )
397 if ( !FILE_strcasecmp( dllname, wm->short_modname ) )
399 if ( !FILE_strcasecmp( dllname, wm->short_filename ) )
407 /******************************************************************
408 * LdrLockLoaderLock (NTDLL.@)
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).
414 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG *magic )
416 if (flags) FIXME( "flags %lx not supported\n", flags );
418 if (result) *result = 1;
419 if (!magic) return STATUS_INVALID_PARAMETER_3;
420 RtlEnterCriticalSection( &loader_section );
421 *magic = GetCurrentThreadId();
422 return STATUS_SUCCESS;
426 /******************************************************************
427 * LdrUnlockLoaderUnlock (NTDLL.@)
429 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG magic )
433 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
434 RtlLeaveCriticalSection( &loader_section );
436 return STATUS_SUCCESS;
440 /******************************************************************
441 * LdrGetDllHandle (NTDLL.@)
445 NTSTATUS WINAPI LdrGetDllHandle(ULONG x, ULONG y, PUNICODE_STRING name, HMODULE *base)
449 TRACE("%08lx %08lx %s %p\n",
450 x, y, name ? debugstr_wn(name->Buffer, name->Length) : NULL, base);
452 if (x != 0 || y != 0)
453 FIXME("Unknown behavior, please report\n");
455 /* FIXME: we should store module name information as unicode */
460 RtlUnicodeStringToAnsiString( &str, name, TRUE );
462 wm = MODULE_FindModule( str.Buffer );
463 RtlFreeAnsiString( &str );
471 return STATUS_DLL_NOT_FOUND;
475 return STATUS_SUCCESS;
478 /***********************************************************************
479 * MODULE_GetProcAddress (internal)
481 FARPROC MODULE_GetProcAddress(
482 HMODULE hModule, /* [in] current module handle */
483 LPCSTR function, /* [in] function to be looked up */
490 if (HIWORD(function))
491 TRACE("(%p,%s (%d))\n",hModule,function,hint);
493 TRACE("(%p,%p)\n",hModule,function);
495 RtlEnterCriticalSection( &loader_section );
496 if ((wm = MODULE32_LookupHMODULE( hModule )))
498 retproc = wm->find_export( wm, function, hint, snoop );
500 RtlLeaveCriticalSection( &loader_section );
505 /******************************************************************
506 * LdrGetProcedureAddress (NTDLL.@)
510 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE base, PANSI_STRING name, ULONG ord, PVOID *address)
512 WARN("%p %s %ld %p\n", base, name ? debugstr_an(name->Buffer, name->Length) : NULL, ord, address);
514 *address = MODULE_GetProcAddress( base, name ? name->Buffer : (LPSTR)ord, -1, TRUE );
516 return (*address) ? STATUS_SUCCESS : STATUS_PROCEDURE_NOT_FOUND;
520 /***********************************************************************
523 * helper for MODULE_LoadLibraryExA. Allocate space to hold the directory
524 * portion of the provided name and put the name in it.
527 static LPCSTR allocate_lib_dir(LPCSTR 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;
538 length = pmax - libname;
540 result = RtlAllocateHeap (ntdll_get_process_heap(), 0, length+1);
544 strncpy (result, libname, length);
545 result [length] = '\0';
551 /***********************************************************************
552 * MODULE_LoadLibraryExA (internal)
554 * Load a PE style module according to the load order.
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
567 NTSTATUS MODULE_LoadLibraryExA( LPCSTR libname, DWORD flags, WINE_MODREF** pwm)
570 enum loadorder_type loadorder[LOADORDER_NTYPES];
572 const char *filetype = "";
574 BOOL allocated_libdir = FALSE;
575 static LPCSTR libdir = NULL; /* See above */
576 NTSTATUS nts = STATUS_SUCCESS;
579 if ( !libname ) return STATUS_DLL_NOT_FOUND; /* FIXME ? */
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 */
585 RtlEnterCriticalSection( &loader_section );
587 if ((flags & LOAD_WITH_ALTERED_SEARCH_PATH) && FILE_contains_path(libname))
589 if (!(libdir = allocate_lib_dir(libname)))
591 nts = STATUS_NO_MEMORY;
594 allocated_libdir = TRUE;
597 if (!libdir || allocated_libdir)
598 found = SearchPathA(NULL, libname, ".dll", MAX_PATH, filename, NULL);
600 found = DIR_SearchAlternatePath(libdir, libname, ".dll", MAX_PATH, filename, NULL);
602 /* build the modules filename */
605 if (!MODULE_GetBuiltinPath( libname, ".dll", filename, MAX_PATH ))
607 nts = STATUS_INTERNAL_ERROR;
612 /* Check for already loaded module */
613 if (!(*pwm = MODULE_FindModule(filename)) && !FILE_contains_path(libname))
615 LPSTR fn = RtlAllocateHeap ( ntdll_get_process_heap(), 0, MAX_PATH + 1 );
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)
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 );
637 if (((*pwm)->flags & WINE_MODREF_DONT_RESOLVE_REFS) &&
638 !(flags & DONT_RESOLVE_DLL_REFERENCES))
640 (*pwm)->flags &= ~WINE_MODREF_DONT_RESOLVE_REFS;
641 PE_fixup_imports( *pwm );
643 TRACE("Already loaded module '%s' at %p, count=%d\n", filename, (*pwm)->module, (*pwm)->refCount);
644 if (allocated_libdir)
646 RtlFreeHeap( ntdll_get_process_heap(), 0, (LPSTR)libdir );
649 RtlLeaveCriticalSection( &loader_section );
650 RtlFreeHeap( ntdll_get_process_heap(), 0, filename );
651 return STATUS_SUCCESS;
654 MODULE_GetLoadOrder( loadorder, filename, TRUE);
656 for (i = 0; i < LOADORDER_NTYPES; i++)
658 if (loadorder[i] == LOADORDER_INVALID) break;
660 switch (loadorder[i])
663 TRACE("Trying native dll '%s'\n", filename);
664 nts = PE_LoadLibraryExA(filename, flags, pwm);
669 TRACE("Trying built-in '%s'\n", filename);
670 nts = BUILTIN32_LoadLibraryExA(filename, flags, pwm);
671 filetype = "builtin";
675 nts = STATUS_INTERNAL_ERROR;
679 if (nts == STATUS_SUCCESS)
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;
689 if (allocated_libdir)
691 RtlFreeHeap( ntdll_get_process_heap(), 0, (LPSTR)libdir );
694 RtlLeaveCriticalSection( &loader_section );
695 RtlFreeHeap( ntdll_get_process_heap(), 0, filename );
699 if (nts != STATUS_NO_SUCH_FILE)
701 WARN("Loading of %s DLL %s failed (status %ld).\n",
702 filetype, filename, nts);
708 if (allocated_libdir)
710 RtlFreeHeap( ntdll_get_process_heap(), 0, (LPSTR)libdir );
713 RtlLeaveCriticalSection( &loader_section );
714 WARN("Failed to load module '%s'; status=%ld\n", filename, nts);
715 RtlFreeHeap( ntdll_get_process_heap(), 0, filename );
719 /******************************************************************
720 * LdrLoadDll (NTDLL.@)
722 NTSTATUS WINAPI LdrLoadDll(LPCWSTR path_name, DWORD flags, PUNICODE_STRING libname, HMODULE* hModule)
725 NTSTATUS nts = STATUS_SUCCESS;
728 RtlUnicodeStringToAnsiString(&str, libname, TRUE);
730 RtlEnterCriticalSection( &loader_section );
732 switch (nts = MODULE_LoadLibraryExA( str.Buffer, flags, &wm ))
735 if ( !MODULE_DllProcessAttach( wm, NULL ) )
737 WARN_(module)("Attach failed for module '%s'.\n", str.Buffer);
738 LdrUnloadDll(wm->module);
739 nts = STATUS_DLL_INIT_FAILED;
743 case STATUS_NO_SUCH_FILE:
744 nts = STATUS_DLL_NOT_FOUND;
746 default: /* keep error code as it is (memory...) */
750 *hModule = (wm) ? wm->module : NULL;
752 RtlLeaveCriticalSection( &loader_section );
754 RtlFreeAnsiString(&str);
759 /******************************************************************
760 * LdrShutdownProcess (NTDLL.@)
763 NTSTATUS WINAPI LdrShutdownProcess(void)
766 MODULE_DllProcessDetach( TRUE, (LPVOID)1 );
767 return STATUS_SUCCESS; /* FIXME */
770 /******************************************************************
771 * LdrShutdownThread (NTDLL.@)
774 NTSTATUS WINAPI LdrShutdownThread(void)
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 */
783 RtlEnterCriticalSection( &loader_section );
785 for ( wm = MODULE_modref_list; wm; wm = wm->next )
787 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
789 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
792 MODULE_InitDLL( wm, DLL_THREAD_DETACH, NULL );
795 RtlLeaveCriticalSection( &loader_section );
796 return STATUS_SUCCESS; /* FIXME */
799 /***********************************************************************
800 * MODULE_FlushModrefs
802 * NOTE: Assumes that the process critical section is held!
804 * Remove all unused modrefs and call the internal unloading routines
805 * for the library type.
807 static void MODULE_FlushModrefs(void)
809 WINE_MODREF *wm, *next;
811 for (wm = MODULE_modref_list; wm; wm = next)
818 /* Unlink this modref from the chain */
820 wm->next->prev = wm->prev;
822 wm->prev->next = wm->next;
823 if (wm == MODULE_modref_list)
824 MODULE_modref_list = wm->next;
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" );
831 SERVER_START_REQ( unload_dll )
833 req->base = (void *)wm->module;
834 wine_server_call( req );
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 );
846 /***********************************************************************
849 * NOTE: Assumes that the process critical section is held!
851 static void MODULE_DecRefCount( WINE_MODREF *wm )
855 if ( wm->flags & WINE_MODREF_MARKER )
858 if ( wm->refCount <= 0 )
862 TRACE("(%s) refCount: %d\n", wm->modname, wm->refCount );
864 if ( wm->refCount == 0 )
866 wm->flags |= WINE_MODREF_MARKER;
868 for ( i = 0; i < wm->nDeps; i++ )
870 MODULE_DecRefCount( wm->deps[i] );
872 wm->flags &= ~WINE_MODREF_MARKER;
876 /******************************************************************
877 * LdrUnloadDll (NTDLL.@)
881 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
883 NTSTATUS retv = STATUS_SUCCESS;
885 TRACE("(%p)\n", hModule);
887 RtlEnterCriticalSection( &loader_section );
889 /* if we're stopping the whole process (and forcing the removal of all
890 * DLLs) the library will be freed anyway
892 if (!process_detaching)
897 if ((wm = MODULE32_LookupHMODULE( hModule )) != NULL)
899 TRACE("(%s) - START\n", wm->modname);
901 /* Recursively decrement reference counts */
902 MODULE_DecRefCount( wm );
904 /* Call process detach notifications */
905 if ( free_lib_count <= 1 )
907 MODULE_DllProcessDetach( FALSE, NULL );
908 MODULE_FlushModrefs();
914 retv = STATUS_DLL_NOT_FOUND;
919 RtlLeaveCriticalSection( &loader_section );
924 /***********************************************************************
925 * RtlImageNtHeader (NTDLL.@)
927 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
929 IMAGE_NT_HEADERS *ret;
933 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
936 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
938 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
939 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
951 /***********************************************************************
952 * RtlImageDirectoryEntryToData (NTDLL.@)
954 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
956 const IMAGE_NT_HEADERS *nt;
959 if ((ULONG_PTR)module & 1) /* mapped as data file */
961 module = (HMODULE)((ULONG_PTR)module & ~1);
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;
970 /* not mapped as image, need to find the section containing the virtual address */
971 return RtlImageRvaToVa( nt, module, addr, NULL );
975 /***********************************************************************
976 * RtlImageRvaToSection (NTDLL.@)
978 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
979 HMODULE module, DWORD rva )
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++)
986 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
993 /***********************************************************************
994 * RtlImageRvaToVa (NTDLL.@)
996 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
997 DWORD rva, IMAGE_SECTION_HEADER **section )
999 IMAGE_SECTION_HEADER *sec;
1001 if (section && *section) /* try this section first */
1004 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
1007 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
1009 if (section) *section = sec;
1010 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);