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 ) )
213 /******************************************************************
214 * LdrGetDllHandle (NTDLL.@)
218 NTSTATUS WINAPI LdrGetDllHandle(ULONG x, ULONG y, PUNICODE_STRING name, HMODULE *base)
222 TRACE("%08lx %08lx %s %p\n",
223 x, y, name ? debugstr_wn(name->Buffer, name->Length) : NULL, base);
225 if (x != 0 || y != 0)
226 FIXME("Unknown behavior, please report\n");
228 /* FIXME: we should store module name information as unicode */
233 RtlUnicodeStringToAnsiString( &str, name, TRUE );
235 wm = MODULE_FindModule( str.Buffer );
236 RtlFreeAnsiString( &str );
244 return STATUS_DLL_NOT_FOUND;
248 return STATUS_SUCCESS;
251 /***********************************************************************
252 * MODULE_GetProcAddress (internal)
254 FARPROC MODULE_GetProcAddress(
255 HMODULE hModule, /* [in] current module handle */
256 LPCSTR function, /* [in] function to be looked up */
263 if (HIWORD(function))
264 TRACE("(%p,%s (%d))\n",hModule,function,hint);
266 TRACE("(%p,%p)\n",hModule,function);
268 RtlEnterCriticalSection( &loader_section );
269 if ((wm = MODULE32_LookupHMODULE( hModule )))
271 retproc = wm->find_export( wm, function, hint, snoop );
273 RtlLeaveCriticalSection( &loader_section );
278 /******************************************************************
279 * LdrGetProcedureAddress (NTDLL.@)
283 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE base, PANSI_STRING name, ULONG ord, PVOID *address)
285 WARN("%p %s %ld %p\n", base, name ? debugstr_an(name->Buffer, name->Length) : NULL, ord, address);
287 *address = MODULE_GetProcAddress( base, name ? name->Buffer : (LPSTR)ord, -1, TRUE );
289 return (*address) ? STATUS_SUCCESS : STATUS_PROCEDURE_NOT_FOUND;
293 /***********************************************************************
296 * helper for MODULE_LoadLibraryExA. Allocate space to hold the directory
297 * portion of the provided name and put the name in it.
300 static LPCSTR allocate_lib_dir(LPCSTR libname)
307 if ((p = strrchr( pmax, '\\' ))) pmax = p + 1;
308 if ((p = strrchr( pmax, '/' ))) pmax = p + 1; /* Naughty. MSDN says don't */
309 if (pmax == libname && pmax[0] && pmax[1] == ':') pmax += 2;
311 length = pmax - libname;
313 result = RtlAllocateHeap (ntdll_get_process_heap(), 0, length+1);
317 strncpy (result, libname, length);
318 result [length] = '\0';
324 /***********************************************************************
325 * MODULE_LoadLibraryExA (internal)
327 * Load a PE style module according to the load order.
329 * libdir is used to support LOAD_WITH_ALTERED_SEARCH_PATH during the recursion
330 * on this function. When first called from LoadLibraryExA it will be
331 * NULL but thereafter it may point to a buffer containing the path
332 * portion of the library name. Note that the recursion all occurs
333 * within a Critical section (see LoadLibraryExA) so the use of a
334 * static is acceptable.
335 * (We have to use a static variable at some point anyway, to pass the
336 * information from BUILTIN32_dlopen through dlopen and the builtin's
337 * init function into load_library).
338 * allocated_libdir is TRUE in the stack frame that allocated libdir
340 NTSTATUS MODULE_LoadLibraryExA( LPCSTR libname, DWORD flags, WINE_MODREF** pwm)
343 enum loadorder_type loadorder[LOADORDER_NTYPES];
345 const char *filetype = "";
347 BOOL allocated_libdir = FALSE;
348 static LPCSTR libdir = NULL; /* See above */
349 NTSTATUS nts = STATUS_SUCCESS;
352 if ( !libname ) return STATUS_DLL_NOT_FOUND; /* FIXME ? */
354 filename = RtlAllocateHeap ( ntdll_get_process_heap(), 0, MAX_PATH + 1 );
355 if ( !filename ) return STATUS_NO_MEMORY;
356 *filename = 0; /* Just in case we don't set it before goto error */
358 RtlEnterCriticalSection( &loader_section );
360 if ((flags & LOAD_WITH_ALTERED_SEARCH_PATH) && FILE_contains_path(libname))
362 if (!(libdir = allocate_lib_dir(libname)))
364 nts = STATUS_NO_MEMORY;
367 allocated_libdir = TRUE;
370 if (!libdir || allocated_libdir)
371 found = SearchPathA(NULL, libname, ".dll", MAX_PATH, filename, NULL);
373 found = DIR_SearchAlternatePath(libdir, libname, ".dll", MAX_PATH, filename, NULL);
375 /* build the modules filename */
378 if (!MODULE_GetBuiltinPath( libname, ".dll", filename, MAX_PATH ))
380 nts = STATUS_INTERNAL_ERROR;
385 /* Check for already loaded module */
386 if (!(*pwm = MODULE_FindModule(filename)) && !FILE_contains_path(libname))
388 LPSTR fn = RtlAllocateHeap ( ntdll_get_process_heap(), 0, MAX_PATH + 1 );
391 /* since the default loading mechanism uses a more detailed algorithm
392 * than SearchPath (like using PATH, which can even be modified between
393 * two attempts of loading the same DLL), the look-up above (with
394 * SearchPath) can have put the file in system directory, whereas it
395 * has already been loaded but with a different path. So do a specific
396 * look-up with filename (without any path)
398 strcpy ( fn, libname );
399 /* if the filename doesn't have an extension append .DLL */
400 if (!strrchr( fn, '.')) strcat( fn, ".dll" );
401 if ((*pwm = MODULE_FindModule( fn )) != NULL)
402 strcpy( filename, fn );
403 RtlFreeHeap( ntdll_get_process_heap(), 0, fn );
410 if (((*pwm)->flags & WINE_MODREF_DONT_RESOLVE_REFS) &&
411 !(flags & DONT_RESOLVE_DLL_REFERENCES))
413 (*pwm)->flags &= ~WINE_MODREF_DONT_RESOLVE_REFS;
414 PE_fixup_imports( *pwm );
416 TRACE("Already loaded module '%s' at %p, count=%d\n", filename, (*pwm)->module, (*pwm)->refCount);
417 if (allocated_libdir)
419 RtlFreeHeap( ntdll_get_process_heap(), 0, (LPSTR)libdir );
422 RtlLeaveCriticalSection( &loader_section );
423 RtlFreeHeap( ntdll_get_process_heap(), 0, filename );
424 return STATUS_SUCCESS;
427 MODULE_GetLoadOrder( loadorder, filename, TRUE);
429 for (i = 0; i < LOADORDER_NTYPES; i++)
431 if (loadorder[i] == LOADORDER_INVALID) break;
433 switch (loadorder[i])
436 TRACE("Trying native dll '%s'\n", filename);
437 nts = PE_LoadLibraryExA(filename, flags, pwm);
442 TRACE("Trying built-in '%s'\n", filename);
443 nts = BUILTIN32_LoadLibraryExA(filename, flags, pwm);
444 filetype = "builtin";
448 nts = STATUS_INTERNAL_ERROR;
452 if (nts == STATUS_SUCCESS)
454 /* Initialize DLL just loaded */
455 TRACE("Loaded module '%s' at %p\n", filename, (*pwm)->module);
456 if (!TRACE_ON(module))
457 TRACE_(loaddll)("Loaded module '%s' : %s\n", filename, filetype);
458 /* Set the refCount here so that an attach failure will */
459 /* decrement the dependencies through the MODULE_FreeLibrary call. */
460 (*pwm)->refCount = 1;
462 if (allocated_libdir)
464 RtlFreeHeap( ntdll_get_process_heap(), 0, (LPSTR)libdir );
467 RtlLeaveCriticalSection( &loader_section );
468 RtlFreeHeap( ntdll_get_process_heap(), 0, filename );
472 if (nts != STATUS_NO_SUCH_FILE)
474 WARN("Loading of %s DLL %s failed (status %ld).\n",
475 filetype, filename, nts);
481 if (allocated_libdir)
483 RtlFreeHeap( ntdll_get_process_heap(), 0, (LPSTR)libdir );
486 RtlLeaveCriticalSection( &loader_section );
487 WARN("Failed to load module '%s'; status=%ld\n", filename, nts);
488 RtlFreeHeap( ntdll_get_process_heap(), 0, filename );
492 /******************************************************************
493 * LdrLoadDll (NTDLL.@)
495 NTSTATUS WINAPI LdrLoadDll(LPCWSTR path_name, DWORD flags, PUNICODE_STRING libname, HMODULE* hModule)
498 NTSTATUS nts = STATUS_SUCCESS;
501 RtlUnicodeStringToAnsiString(&str, libname, TRUE);
503 RtlEnterCriticalSection( &loader_section );
505 switch (nts = MODULE_LoadLibraryExA( str.Buffer, flags, &wm ))
508 if ( !MODULE_DllProcessAttach( wm, NULL ) )
510 WARN_(module)("Attach failed for module '%s'.\n", str.Buffer);
511 LdrUnloadDll(wm->module);
512 nts = STATUS_DLL_INIT_FAILED;
516 case STATUS_NO_SUCH_FILE:
517 nts = STATUS_DLL_NOT_FOUND;
519 default: /* keep error code as it is (memory...) */
523 *hModule = (wm) ? wm->module : NULL;
525 RtlLeaveCriticalSection( &loader_section );
527 RtlFreeAnsiString(&str);
532 /******************************************************************
533 * LdrShutdownProcess (NTDLL.@)
536 NTSTATUS WINAPI LdrShutdownProcess(void)
539 MODULE_DllProcessDetach( TRUE, (LPVOID)1 );
540 return STATUS_SUCCESS; /* FIXME */
543 /******************************************************************
544 * LdrShutdownThread (NTDLL.@)
547 NTSTATUS WINAPI LdrShutdownThread(void)
552 /* don't do any detach calls if process is exiting */
553 if (process_detaching) return STATUS_SUCCESS;
554 /* FIXME: there is still a race here */
556 RtlEnterCriticalSection( &loader_section );
558 for ( wm = MODULE_modref_list; wm; wm = wm->next )
560 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
562 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
565 MODULE_InitDLL( wm, DLL_THREAD_DETACH, NULL );
568 RtlLeaveCriticalSection( &loader_section );
569 return STATUS_SUCCESS; /* FIXME */
572 /***********************************************************************
573 * MODULE_FlushModrefs
575 * NOTE: Assumes that the process critical section is held!
577 * Remove all unused modrefs and call the internal unloading routines
578 * for the library type.
580 static void MODULE_FlushModrefs(void)
582 WINE_MODREF *wm, *next;
584 for (wm = MODULE_modref_list; wm; wm = next)
591 /* Unlink this modref from the chain */
593 wm->next->prev = wm->prev;
595 wm->prev->next = wm->next;
596 if (wm == MODULE_modref_list)
597 MODULE_modref_list = wm->next;
599 TRACE(" unloading %s\n", wm->filename);
600 if (!TRACE_ON(module))
601 TRACE_(loaddll)("Unloaded module '%s' : %s\n", wm->filename,
602 wm->dlhandle ? "builtin" : "native" );
604 SERVER_START_REQ( unload_dll )
606 req->base = (void *)wm->module;
607 wine_server_call( req );
611 if (wm->dlhandle) wine_dll_unload( wm->dlhandle );
612 else UnmapViewOfFile( (LPVOID)wm->module );
613 FreeLibrary16( wm->hDummyMod );
614 RtlFreeHeap( ntdll_get_process_heap(), 0, wm->deps );
615 RtlFreeHeap( ntdll_get_process_heap(), 0, wm );
619 /***********************************************************************
622 * NOTE: Assumes that the process critical section is held!
624 static void MODULE_DecRefCount( WINE_MODREF *wm )
628 if ( wm->flags & WINE_MODREF_MARKER )
631 if ( wm->refCount <= 0 )
635 TRACE("(%s) refCount: %d\n", wm->modname, wm->refCount );
637 if ( wm->refCount == 0 )
639 wm->flags |= WINE_MODREF_MARKER;
641 for ( i = 0; i < wm->nDeps; i++ )
643 MODULE_DecRefCount( wm->deps[i] );
645 wm->flags &= ~WINE_MODREF_MARKER;
649 /******************************************************************
650 * LdrUnloadDll (NTDLL.@)
654 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
656 NTSTATUS retv = STATUS_SUCCESS;
658 TRACE("(%p)\n", hModule);
660 RtlEnterCriticalSection( &loader_section );
662 /* if we're stopping the whole process (and forcing the removal of all
663 * DLLs) the library will be freed anyway
665 if (!process_detaching)
670 if ((wm = MODULE32_LookupHMODULE( hModule )) != NULL)
672 TRACE("(%s) - START\n", wm->modname);
674 /* Recursively decrement reference counts */
675 MODULE_DecRefCount( wm );
677 /* Call process detach notifications */
678 if ( free_lib_count <= 1 )
680 MODULE_DllProcessDetach( FALSE, NULL );
681 MODULE_FlushModrefs();
687 retv = STATUS_DLL_NOT_FOUND;
692 RtlLeaveCriticalSection( &loader_section );
697 /***********************************************************************
698 * RtlImageNtHeader (NTDLL.@)
700 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
702 IMAGE_NT_HEADERS *ret;
706 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
709 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
711 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
712 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
724 /***********************************************************************
725 * RtlImageDirectoryEntryToData (NTDLL.@)
727 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
729 const IMAGE_NT_HEADERS *nt;
732 if ((ULONG_PTR)module & 1) /* mapped as data file */
734 module = (HMODULE)((ULONG_PTR)module & ~1);
737 if (!(nt = RtlImageNtHeader( module ))) return NULL;
738 if (dir >= nt->OptionalHeader.NumberOfRvaAndSizes) return NULL;
739 if (!(addr = nt->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
740 *size = nt->OptionalHeader.DataDirectory[dir].Size;
741 if (image || addr < nt->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
743 /* not mapped as image, need to find the section containing the virtual address */
744 return RtlImageRvaToVa( nt, module, addr, NULL );
748 /***********************************************************************
749 * RtlImageRvaToSection (NTDLL.@)
751 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
752 HMODULE module, DWORD rva )
755 IMAGE_SECTION_HEADER *sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader +
756 nt->FileHeader.SizeOfOptionalHeader);
757 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
759 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
766 /***********************************************************************
767 * RtlImageRvaToVa (NTDLL.@)
769 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
770 DWORD rva, IMAGE_SECTION_HEADER **section )
772 IMAGE_SECTION_HEADER *sec;
774 if (section && *section) /* try this section first */
777 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
780 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
782 if (section) *section = sec;
783 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);