2 * Copyright 2002 Dmitry Timoshkov for Codeweavers
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
9 * This library is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with this library; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
27 #include "wine/exception.h"
29 #include "wine/debug.h"
30 #include "wine/server.h"
31 #include "ntdll_misc.h"
33 WINE_DEFAULT_DEBUG_CHANNEL(ntdll);
34 WINE_DECLARE_DEBUG_CHANNEL(module);
35 WINE_DECLARE_DEBUG_CHANNEL(module);
36 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
38 static int free_lib_count; /* recursion depth of LdrUnloadDll calls */
40 /* filter for page-fault exceptions */
41 static WINE_EXCEPTION_FILTER(page_fault)
43 if (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION)
44 return EXCEPTION_EXECUTE_HANDLER;
45 return EXCEPTION_CONTINUE_SEARCH;
48 CRITICAL_SECTION loader_section = CRITICAL_SECTION_INIT( "loader_section" );
50 /*************************************************************************
51 * MODULE32_LookupHMODULE
52 * looks for the referenced HMODULE in the current process
53 * NOTE: Assumes that the process critical section is held!
55 static WINE_MODREF *MODULE32_LookupHMODULE( HMODULE hmod )
63 ERR("tried to lookup %p in win32 module handler!\n",hmod);
66 for ( wm = MODULE_modref_list; wm; wm=wm->next )
67 if (wm->module == hmod)
72 /*************************************************************************
75 * Allocate a WINE_MODREF structure and add it to the process list
76 * NOTE: Assumes that the process critical section is held!
78 WINE_MODREF *MODULE_AllocModRef( HMODULE hModule, LPCSTR filename )
81 IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
83 DWORD long_len = strlen( filename );
84 DWORD short_len = GetShortPathNameA( filename, NULL, 0 );
86 if ((wm = RtlAllocateHeap( ntdll_get_process_heap(), HEAP_ZERO_MEMORY,
87 sizeof(*wm) + long_len + short_len + 1 )))
92 wm->filename = wm->data;
93 memcpy( wm->filename, filename, long_len + 1 );
94 if ((wm->modname = strrchr( wm->filename, '\\' ))) wm->modname++;
95 else wm->modname = wm->filename;
97 wm->short_filename = wm->filename + long_len + 1;
98 GetShortPathNameA( wm->filename, wm->short_filename, short_len + 1 );
99 if ((wm->short_modname = strrchr( wm->short_filename, '\\' ))) wm->short_modname++;
100 else wm->short_modname = wm->short_filename;
102 wm->next = MODULE_modref_list;
103 if (wm->next) wm->next->prev = wm;
104 MODULE_modref_list = wm;
106 wm->ldr.InLoadOrderModuleList.Flink = NULL;
107 wm->ldr.InLoadOrderModuleList.Blink = NULL;
108 wm->ldr.InMemoryOrderModuleList.Flink = NULL;
109 wm->ldr.InMemoryOrderModuleList.Blink = NULL;
110 wm->ldr.InInitializationOrderModuleList.Flink = NULL;
111 wm->ldr.InInitializationOrderModuleList.Blink = NULL;
112 wm->ldr.BaseAddress = hModule;
113 wm->ldr.EntryPoint = (nt->OptionalHeader.AddressOfEntryPoint) ?
114 ((char *)hModule + nt->OptionalHeader.AddressOfEntryPoint) : 0;
115 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
116 RtlCreateUnicodeStringFromAsciiz( &wm->ldr.FullDllName, wm->filename);
117 RtlCreateUnicodeStringFromAsciiz( &wm->ldr.BaseDllName, wm->modname);
119 wm->ldr.LoadCount = 0;
120 wm->ldr.TlsIndex = 0;
121 wm->ldr.SectionHandle = NULL;
122 wm->ldr.CheckSum = 0;
123 wm->ldr.TimeDateStamp = 0;
125 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL))
127 if (!exe_modref) exe_modref = wm;
128 else FIXME( "Trying to load second .EXE file: %s\n", filename );
134 /******************************************************************
135 * LdrDisableThreadCalloutsForDll (NTDLL.@)
138 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
141 NTSTATUS ret = STATUS_SUCCESS;
143 RtlEnterCriticalSection( &loader_section );
145 wm = MODULE32_LookupHMODULE( hModule );
147 ret = STATUS_DLL_NOT_FOUND;
149 wm->flags |= WINE_MODREF_NO_DLL_CALLS;
151 RtlLeaveCriticalSection( &loader_section );
156 /******************************************************************
157 * LdrFindEntryForAddress (NTDLL.@)
159 * The loader_section must be locked while calling this function
161 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* mod)
165 for ( wm = MODULE_modref_list; wm; wm = wm->next )
167 if ((const void *)wm->module <= addr &&
168 (char *)addr < (char*)wm->module + wm->ldr.SizeOfImage)
171 return STATUS_SUCCESS;
174 return STATUS_NO_MORE_ENTRIES;
177 /**********************************************************************
180 * Find a (loaded) win32 module depending on path
181 * LPCSTR path: [in] pathname of module/library to be found
183 * The loader_section must be locked while calling this function
185 * the module handle if found
188 WINE_MODREF *MODULE_FindModule(LPCSTR path)
191 char dllname[260], *p;
193 /* Append .DLL to name if no extension present */
194 strcpy( dllname, path );
195 if (!(p = strrchr( dllname, '.')) || strchr( p, '/' ) || strchr( p, '\\'))
196 strcat( dllname, ".DLL" );
198 for ( wm = MODULE_modref_list; wm; wm = wm->next )
200 if ( !FILE_strcasecmp( dllname, wm->modname ) )
202 if ( !FILE_strcasecmp( dllname, wm->filename ) )
204 if ( !FILE_strcasecmp( dllname, wm->short_modname ) )
206 if ( !FILE_strcasecmp( dllname, wm->short_filename ) )
214 /******************************************************************
215 * LdrLockLoaderLock (NTDLL.@)
217 * Note: flags are not implemented.
218 * Flag 0x01 is used to raise exceptions on errors.
219 * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
221 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG *magic )
223 if (flags) FIXME( "flags %lx not supported\n", flags );
225 if (result) *result = 1;
226 if (!magic) return STATUS_INVALID_PARAMETER_3;
227 RtlEnterCriticalSection( &loader_section );
228 *magic = GetCurrentThreadId();
229 return STATUS_SUCCESS;
233 /******************************************************************
234 * LdrUnlockLoaderUnlock (NTDLL.@)
236 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG magic )
240 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
241 RtlLeaveCriticalSection( &loader_section );
243 return STATUS_SUCCESS;
247 /******************************************************************
248 * LdrGetDllHandle (NTDLL.@)
252 NTSTATUS WINAPI LdrGetDllHandle(ULONG x, ULONG y, PUNICODE_STRING name, HMODULE *base)
256 TRACE("%08lx %08lx %s %p\n",
257 x, y, name ? debugstr_wn(name->Buffer, name->Length) : NULL, base);
259 if (x != 0 || y != 0)
260 FIXME("Unknown behavior, please report\n");
262 /* FIXME: we should store module name information as unicode */
267 RtlUnicodeStringToAnsiString( &str, name, TRUE );
269 wm = MODULE_FindModule( str.Buffer );
270 RtlFreeAnsiString( &str );
278 return STATUS_DLL_NOT_FOUND;
282 return STATUS_SUCCESS;
285 /***********************************************************************
286 * MODULE_GetProcAddress (internal)
288 FARPROC MODULE_GetProcAddress(
289 HMODULE hModule, /* [in] current module handle */
290 LPCSTR function, /* [in] function to be looked up */
297 if (HIWORD(function))
298 TRACE("(%p,%s (%d))\n",hModule,function,hint);
300 TRACE("(%p,%p)\n",hModule,function);
302 RtlEnterCriticalSection( &loader_section );
303 if ((wm = MODULE32_LookupHMODULE( hModule )))
305 retproc = wm->find_export( wm, function, hint, snoop );
307 RtlLeaveCriticalSection( &loader_section );
312 /******************************************************************
313 * LdrGetProcedureAddress (NTDLL.@)
317 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE base, PANSI_STRING name, ULONG ord, PVOID *address)
319 WARN("%p %s %ld %p\n", base, name ? debugstr_an(name->Buffer, name->Length) : NULL, ord, address);
321 *address = MODULE_GetProcAddress( base, name ? name->Buffer : (LPSTR)ord, -1, TRUE );
323 return (*address) ? STATUS_SUCCESS : STATUS_PROCEDURE_NOT_FOUND;
327 /***********************************************************************
330 * helper for MODULE_LoadLibraryExA. Allocate space to hold the directory
331 * portion of the provided name and put the name in it.
334 static LPCSTR allocate_lib_dir(LPCSTR libname)
341 if ((p = strrchr( pmax, '\\' ))) pmax = p + 1;
342 if ((p = strrchr( pmax, '/' ))) pmax = p + 1; /* Naughty. MSDN says don't */
343 if (pmax == libname && pmax[0] && pmax[1] == ':') pmax += 2;
345 length = pmax - libname;
347 result = RtlAllocateHeap (ntdll_get_process_heap(), 0, length+1);
351 strncpy (result, libname, length);
352 result [length] = '\0';
358 /***********************************************************************
359 * MODULE_LoadLibraryExA (internal)
361 * Load a PE style module according to the load order.
363 * libdir is used to support LOAD_WITH_ALTERED_SEARCH_PATH during the recursion
364 * on this function. When first called from LoadLibraryExA it will be
365 * NULL but thereafter it may point to a buffer containing the path
366 * portion of the library name. Note that the recursion all occurs
367 * within a Critical section (see LoadLibraryExA) so the use of a
368 * static is acceptable.
369 * (We have to use a static variable at some point anyway, to pass the
370 * information from BUILTIN32_dlopen through dlopen and the builtin's
371 * init function into load_library).
372 * allocated_libdir is TRUE in the stack frame that allocated libdir
374 NTSTATUS MODULE_LoadLibraryExA( LPCSTR libname, DWORD flags, WINE_MODREF** pwm)
377 enum loadorder_type loadorder[LOADORDER_NTYPES];
379 const char *filetype = "";
381 BOOL allocated_libdir = FALSE;
382 static LPCSTR libdir = NULL; /* See above */
383 NTSTATUS nts = STATUS_SUCCESS;
386 if ( !libname ) return STATUS_DLL_NOT_FOUND; /* FIXME ? */
388 filename = RtlAllocateHeap ( ntdll_get_process_heap(), 0, MAX_PATH + 1 );
389 if ( !filename ) return STATUS_NO_MEMORY;
390 *filename = 0; /* Just in case we don't set it before goto error */
392 RtlEnterCriticalSection( &loader_section );
394 if ((flags & LOAD_WITH_ALTERED_SEARCH_PATH) && FILE_contains_path(libname))
396 if (!(libdir = allocate_lib_dir(libname)))
398 nts = STATUS_NO_MEMORY;
401 allocated_libdir = TRUE;
404 if (!libdir || allocated_libdir)
405 found = SearchPathA(NULL, libname, ".dll", MAX_PATH, filename, NULL);
407 found = DIR_SearchAlternatePath(libdir, libname, ".dll", MAX_PATH, filename, NULL);
409 /* build the modules filename */
412 if (!MODULE_GetBuiltinPath( libname, ".dll", filename, MAX_PATH ))
414 nts = STATUS_INTERNAL_ERROR;
419 /* Check for already loaded module */
420 if (!(*pwm = MODULE_FindModule(filename)) && !FILE_contains_path(libname))
422 LPSTR fn = RtlAllocateHeap ( ntdll_get_process_heap(), 0, MAX_PATH + 1 );
425 /* since the default loading mechanism uses a more detailed algorithm
426 * than SearchPath (like using PATH, which can even be modified between
427 * two attempts of loading the same DLL), the look-up above (with
428 * SearchPath) can have put the file in system directory, whereas it
429 * has already been loaded but with a different path. So do a specific
430 * look-up with filename (without any path)
432 strcpy ( fn, libname );
433 /* if the filename doesn't have an extension append .DLL */
434 if (!strrchr( fn, '.')) strcat( fn, ".dll" );
435 if ((*pwm = MODULE_FindModule( fn )) != NULL)
436 strcpy( filename, fn );
437 RtlFreeHeap( ntdll_get_process_heap(), 0, fn );
444 if (((*pwm)->flags & WINE_MODREF_DONT_RESOLVE_REFS) &&
445 !(flags & DONT_RESOLVE_DLL_REFERENCES))
447 (*pwm)->flags &= ~WINE_MODREF_DONT_RESOLVE_REFS;
448 PE_fixup_imports( *pwm );
450 TRACE("Already loaded module '%s' at %p, count=%d\n", filename, (*pwm)->module, (*pwm)->refCount);
451 if (allocated_libdir)
453 RtlFreeHeap( ntdll_get_process_heap(), 0, (LPSTR)libdir );
456 RtlLeaveCriticalSection( &loader_section );
457 RtlFreeHeap( ntdll_get_process_heap(), 0, filename );
458 return STATUS_SUCCESS;
461 MODULE_GetLoadOrder( loadorder, filename, TRUE);
463 for (i = 0; i < LOADORDER_NTYPES; i++)
465 if (loadorder[i] == LOADORDER_INVALID) break;
467 switch (loadorder[i])
470 TRACE("Trying native dll '%s'\n", filename);
471 nts = PE_LoadLibraryExA(filename, flags, pwm);
476 TRACE("Trying built-in '%s'\n", filename);
477 nts = BUILTIN32_LoadLibraryExA(filename, flags, pwm);
478 filetype = "builtin";
482 nts = STATUS_INTERNAL_ERROR;
486 if (nts == STATUS_SUCCESS)
488 /* Initialize DLL just loaded */
489 TRACE("Loaded module '%s' at %p\n", filename, (*pwm)->module);
490 if (!TRACE_ON(module))
491 TRACE_(loaddll)("Loaded module '%s' : %s\n", filename, filetype);
492 /* Set the refCount here so that an attach failure will */
493 /* decrement the dependencies through the MODULE_FreeLibrary call. */
494 (*pwm)->refCount = 1;
496 if (allocated_libdir)
498 RtlFreeHeap( ntdll_get_process_heap(), 0, (LPSTR)libdir );
501 RtlLeaveCriticalSection( &loader_section );
502 RtlFreeHeap( ntdll_get_process_heap(), 0, filename );
506 if (nts != STATUS_NO_SUCH_FILE)
508 WARN("Loading of %s DLL %s failed (status %ld).\n",
509 filetype, filename, nts);
515 if (allocated_libdir)
517 RtlFreeHeap( ntdll_get_process_heap(), 0, (LPSTR)libdir );
520 RtlLeaveCriticalSection( &loader_section );
521 WARN("Failed to load module '%s'; status=%ld\n", filename, nts);
522 RtlFreeHeap( ntdll_get_process_heap(), 0, filename );
526 /******************************************************************
527 * LdrLoadDll (NTDLL.@)
529 NTSTATUS WINAPI LdrLoadDll(LPCWSTR path_name, DWORD flags, PUNICODE_STRING libname, HMODULE* hModule)
532 NTSTATUS nts = STATUS_SUCCESS;
535 RtlUnicodeStringToAnsiString(&str, libname, TRUE);
537 RtlEnterCriticalSection( &loader_section );
539 switch (nts = MODULE_LoadLibraryExA( str.Buffer, flags, &wm ))
542 if ( !MODULE_DllProcessAttach( wm, NULL ) )
544 WARN_(module)("Attach failed for module '%s'.\n", str.Buffer);
545 LdrUnloadDll(wm->module);
546 nts = STATUS_DLL_INIT_FAILED;
550 case STATUS_NO_SUCH_FILE:
551 nts = STATUS_DLL_NOT_FOUND;
553 default: /* keep error code as it is (memory...) */
557 *hModule = (wm) ? wm->module : NULL;
559 RtlLeaveCriticalSection( &loader_section );
561 RtlFreeAnsiString(&str);
566 /******************************************************************
567 * LdrShutdownProcess (NTDLL.@)
570 NTSTATUS WINAPI LdrShutdownProcess(void)
573 MODULE_DllProcessDetach( TRUE, (LPVOID)1 );
574 return STATUS_SUCCESS; /* FIXME */
577 /******************************************************************
578 * LdrShutdownThread (NTDLL.@)
581 NTSTATUS WINAPI LdrShutdownThread(void)
586 /* don't do any detach calls if process is exiting */
587 if (process_detaching) return STATUS_SUCCESS;
588 /* FIXME: there is still a race here */
590 RtlEnterCriticalSection( &loader_section );
592 for ( wm = MODULE_modref_list; wm; wm = wm->next )
594 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
596 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
599 MODULE_InitDLL( wm, DLL_THREAD_DETACH, NULL );
602 RtlLeaveCriticalSection( &loader_section );
603 return STATUS_SUCCESS; /* FIXME */
606 /***********************************************************************
607 * MODULE_FlushModrefs
609 * NOTE: Assumes that the process critical section is held!
611 * Remove all unused modrefs and call the internal unloading routines
612 * for the library type.
614 static void MODULE_FlushModrefs(void)
616 WINE_MODREF *wm, *next;
618 for (wm = MODULE_modref_list; wm; wm = next)
625 /* Unlink this modref from the chain */
627 wm->next->prev = wm->prev;
629 wm->prev->next = wm->next;
630 if (wm == MODULE_modref_list)
631 MODULE_modref_list = wm->next;
633 TRACE(" unloading %s\n", wm->filename);
634 if (!TRACE_ON(module))
635 TRACE_(loaddll)("Unloaded module '%s' : %s\n", wm->filename,
636 wm->dlhandle ? "builtin" : "native" );
638 SERVER_START_REQ( unload_dll )
640 req->base = (void *)wm->module;
641 wine_server_call( req );
645 if (wm->dlhandle) wine_dll_unload( wm->dlhandle );
646 else UnmapViewOfFile( (LPVOID)wm->module );
647 FreeLibrary16( wm->hDummyMod );
648 RtlFreeHeap( ntdll_get_process_heap(), 0, wm->deps );
649 RtlFreeHeap( ntdll_get_process_heap(), 0, wm );
653 /***********************************************************************
656 * NOTE: Assumes that the process critical section is held!
658 static void MODULE_DecRefCount( WINE_MODREF *wm )
662 if ( wm->flags & WINE_MODREF_MARKER )
665 if ( wm->refCount <= 0 )
669 TRACE("(%s) refCount: %d\n", wm->modname, wm->refCount );
671 if ( wm->refCount == 0 )
673 wm->flags |= WINE_MODREF_MARKER;
675 for ( i = 0; i < wm->nDeps; i++ )
677 MODULE_DecRefCount( wm->deps[i] );
679 wm->flags &= ~WINE_MODREF_MARKER;
683 /******************************************************************
684 * LdrUnloadDll (NTDLL.@)
688 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
690 NTSTATUS retv = STATUS_SUCCESS;
692 TRACE("(%p)\n", hModule);
694 RtlEnterCriticalSection( &loader_section );
696 /* if we're stopping the whole process (and forcing the removal of all
697 * DLLs) the library will be freed anyway
699 if (!process_detaching)
704 if ((wm = MODULE32_LookupHMODULE( hModule )) != NULL)
706 TRACE("(%s) - START\n", wm->modname);
708 /* Recursively decrement reference counts */
709 MODULE_DecRefCount( wm );
711 /* Call process detach notifications */
712 if ( free_lib_count <= 1 )
714 MODULE_DllProcessDetach( FALSE, NULL );
715 MODULE_FlushModrefs();
721 retv = STATUS_DLL_NOT_FOUND;
726 RtlLeaveCriticalSection( &loader_section );
731 /***********************************************************************
732 * RtlImageNtHeader (NTDLL.@)
734 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
736 IMAGE_NT_HEADERS *ret;
740 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
743 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
745 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
746 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
758 /***********************************************************************
759 * RtlImageDirectoryEntryToData (NTDLL.@)
761 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
763 const IMAGE_NT_HEADERS *nt;
766 if ((ULONG_PTR)module & 1) /* mapped as data file */
768 module = (HMODULE)((ULONG_PTR)module & ~1);
771 if (!(nt = RtlImageNtHeader( module ))) return NULL;
772 if (dir >= nt->OptionalHeader.NumberOfRvaAndSizes) return NULL;
773 if (!(addr = nt->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
774 *size = nt->OptionalHeader.DataDirectory[dir].Size;
775 if (image || addr < nt->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
777 /* not mapped as image, need to find the section containing the virtual address */
778 return RtlImageRvaToVa( nt, module, addr, NULL );
782 /***********************************************************************
783 * RtlImageRvaToSection (NTDLL.@)
785 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
786 HMODULE module, DWORD rva )
789 IMAGE_SECTION_HEADER *sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader +
790 nt->FileHeader.SizeOfOptionalHeader);
791 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
793 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
800 /***********************************************************************
801 * RtlImageRvaToVa (NTDLL.@)
803 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
804 DWORD rva, IMAGE_SECTION_HEADER **section )
806 IMAGE_SECTION_HEADER *sec;
808 if (section && *section) /* try this section first */
811 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
814 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
816 if (section) *section = sec;
817 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);