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
25 #include "wine/exception.h"
27 #include "wine/debug.h"
28 #include "wine/server.h"
29 #include "ntdll_misc.h"
31 WINE_DEFAULT_DEBUG_CHANNEL(ntdll);
32 WINE_DECLARE_DEBUG_CHANNEL(module);
33 WINE_DECLARE_DEBUG_CHANNEL(module);
34 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
36 static int free_lib_count; /* recursion depth of FreeLibrary calls */
38 /* filter for page-fault exceptions */
39 static WINE_EXCEPTION_FILTER(page_fault)
41 if (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION)
42 return EXCEPTION_EXECUTE_HANDLER;
43 return EXCEPTION_CONTINUE_SEARCH;
47 /*************************************************************************
50 * Allocate a WINE_MODREF structure and add it to the process list
51 * NOTE: Assumes that the process critical section is held!
53 WINE_MODREF *MODULE_AllocModRef( HMODULE hModule, LPCSTR filename )
57 DWORD long_len = strlen( filename );
58 DWORD short_len = GetShortPathNameA( filename, NULL, 0 );
60 if ((wm = RtlAllocateHeap( ntdll_get_process_heap(), HEAP_ZERO_MEMORY,
61 sizeof(*wm) + long_len + short_len + 1 )))
66 wm->filename = wm->data;
67 memcpy( wm->filename, filename, long_len + 1 );
68 if ((wm->modname = strrchr( wm->filename, '\\' ))) wm->modname++;
69 else wm->modname = wm->filename;
71 wm->short_filename = wm->filename + long_len + 1;
72 GetShortPathNameA( wm->filename, wm->short_filename, short_len + 1 );
73 if ((wm->short_modname = strrchr( wm->short_filename, '\\' ))) wm->short_modname++;
74 else wm->short_modname = wm->short_filename;
76 wm->next = MODULE_modref_list;
77 if (wm->next) wm->next->prev = wm;
78 MODULE_modref_list = wm;
80 if (!(RtlImageNtHeader(hModule)->FileHeader.Characteristics & IMAGE_FILE_DLL))
82 if (!exe_modref) exe_modref = wm;
83 else FIXME( "Trying to load second .EXE file: %s\n", filename );
89 /******************************************************************
90 * LdrDisableThreadCalloutsForDll (NTDLL.@)
93 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
96 NTSTATUS ret = STATUS_SUCCESS;
98 RtlEnterCriticalSection( &loader_section );
100 wm = MODULE32_LookupHMODULE( hModule );
102 ret = STATUS_DLL_NOT_FOUND;
104 wm->flags |= WINE_MODREF_NO_DLL_CALLS;
106 RtlLeaveCriticalSection( &loader_section );
111 /**********************************************************************
114 * Find a (loaded) win32 module depending on path
115 * LPCSTR path: [in] pathname of module/library to be found
117 * The loader_section must be locked while calling this function
119 * the module handle if found
122 WINE_MODREF *MODULE_FindModule(LPCSTR path)
125 char dllname[260], *p;
127 /* Append .DLL to name if no extension present */
128 strcpy( dllname, path );
129 if (!(p = strrchr( dllname, '.')) || strchr( p, '/' ) || strchr( p, '\\'))
130 strcat( dllname, ".DLL" );
132 for ( wm = MODULE_modref_list; wm; wm = wm->next )
134 if ( !FILE_strcasecmp( dllname, wm->modname ) )
136 if ( !FILE_strcasecmp( dllname, wm->filename ) )
138 if ( !FILE_strcasecmp( dllname, wm->short_modname ) )
140 if ( !FILE_strcasecmp( dllname, wm->short_filename ) )
147 /******************************************************************
148 * LdrGetDllHandle (NTDLL.@)
152 NTSTATUS WINAPI LdrGetDllHandle(ULONG x, ULONG y, PUNICODE_STRING name, HMODULE *base)
156 TRACE("%08lx %08lx %s %p\n",
157 x, y, name ? debugstr_wn(name->Buffer, name->Length) : NULL, base);
159 if (x != 0 || y != 0)
160 FIXME("Unknown behavior, please report\n");
162 /* FIXME: we should store module name information as unicode */
167 RtlUnicodeStringToAnsiString( &str, name, TRUE );
169 wm = MODULE_FindModule( str.Buffer );
170 RtlFreeAnsiString( &str );
178 return STATUS_DLL_NOT_FOUND;
182 return STATUS_SUCCESS;
185 /***********************************************************************
186 * MODULE_GetProcAddress (internal)
188 FARPROC MODULE_GetProcAddress(
189 HMODULE hModule, /* [in] current module handle */
190 LPCSTR function, /* [in] function to be looked up */
197 if (HIWORD(function))
198 TRACE("(%p,%s (%d))\n",hModule,function,hint);
200 TRACE("(%p,%p)\n",hModule,function);
202 RtlEnterCriticalSection( &loader_section );
203 if ((wm = MODULE32_LookupHMODULE( hModule )))
205 retproc = wm->find_export( wm, function, hint, snoop );
207 RtlLeaveCriticalSection( &loader_section );
212 /******************************************************************
213 * LdrGetProcedureAddress (NTDLL.@)
217 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE base, PANSI_STRING name, ULONG ord, PVOID *address)
219 WARN("%p %s %ld %p\n", base, name ? debugstr_an(name->Buffer, name->Length) : NULL, ord, address);
221 *address = MODULE_GetProcAddress( base, name ? name->Buffer : (LPSTR)ord, -1, TRUE );
223 return (*address) ? STATUS_SUCCESS : STATUS_PROCEDURE_NOT_FOUND;
227 /***********************************************************************
230 * helper for MODULE_LoadLibraryExA. Allocate space to hold the directory
231 * portion of the provided name and put the name in it.
234 static LPCSTR allocate_lib_dir(LPCSTR libname)
241 if ((p = strrchr( pmax, '\\' ))) pmax = p + 1;
242 if ((p = strrchr( pmax, '/' ))) pmax = p + 1; /* Naughty. MSDN says don't */
243 if (pmax == libname && pmax[0] && pmax[1] == ':') pmax += 2;
245 length = pmax - libname;
247 result = RtlAllocateHeap (ntdll_get_process_heap(), 0, length+1);
251 strncpy (result, libname, length);
252 result [length] = '\0';
258 /***********************************************************************
259 * MODULE_LoadLibraryExA (internal)
261 * Load a PE style module according to the load order.
263 * libdir is used to support LOAD_WITH_ALTERED_SEARCH_PATH during the recursion
264 * on this function. When first called from LoadLibraryExA it will be
265 * NULL but thereafter it may point to a buffer containing the path
266 * portion of the library name. Note that the recursion all occurs
267 * within a Critical section (see LoadLibraryExA) so the use of a
268 * static is acceptable.
269 * (We have to use a static variable at some point anyway, to pass the
270 * information from BUILTIN32_dlopen through dlopen and the builtin's
271 * init function into load_library).
272 * allocated_libdir is TRUE in the stack frame that allocated libdir
274 NTSTATUS MODULE_LoadLibraryExA( LPCSTR libname, DWORD flags, WINE_MODREF** pwm)
277 enum loadorder_type loadorder[LOADORDER_NTYPES];
279 const char *filetype = "";
281 BOOL allocated_libdir = FALSE;
282 static LPCSTR libdir = NULL; /* See above */
283 NTSTATUS nts = STATUS_SUCCESS;
286 if ( !libname ) return STATUS_DLL_NOT_FOUND; /* FIXME ? */
288 filename = RtlAllocateHeap ( ntdll_get_process_heap(), 0, MAX_PATH + 1 );
289 if ( !filename ) return STATUS_NO_MEMORY;
290 *filename = 0; /* Just in case we don't set it before goto error */
292 RtlEnterCriticalSection( &loader_section );
294 if ((flags & LOAD_WITH_ALTERED_SEARCH_PATH) && FILE_contains_path(libname))
296 if (!(libdir = allocate_lib_dir(libname)))
298 nts = STATUS_NO_MEMORY;
301 allocated_libdir = TRUE;
304 if (!libdir || allocated_libdir)
305 found = SearchPathA(NULL, libname, ".dll", MAX_PATH, filename, NULL);
307 found = DIR_SearchAlternatePath(libdir, libname, ".dll", MAX_PATH, filename, NULL);
309 /* build the modules filename */
312 if (!MODULE_GetBuiltinPath( libname, ".dll", filename, MAX_PATH ))
314 nts = STATUS_INTERNAL_ERROR;
319 /* Check for already loaded module */
320 if (!(*pwm = MODULE_FindModule(filename)) && !FILE_contains_path(libname))
322 LPSTR fn = RtlAllocateHeap ( ntdll_get_process_heap(), 0, MAX_PATH + 1 );
325 /* since the default loading mechanism uses a more detailed algorithm
326 * than SearchPath (like using PATH, which can even be modified between
327 * two attempts of loading the same DLL), the look-up above (with
328 * SearchPath) can have put the file in system directory, whereas it
329 * has already been loaded but with a different path. So do a specific
330 * look-up with filename (without any path)
332 strcpy ( fn, libname );
333 /* if the filename doesn't have an extension append .DLL */
334 if (!strrchr( fn, '.')) strcat( fn, ".dll" );
335 if ((*pwm = MODULE_FindModule( fn )) != NULL)
336 strcpy( filename, fn );
337 RtlFreeHeap( ntdll_get_process_heap(), 0, fn );
344 if (((*pwm)->flags & WINE_MODREF_DONT_RESOLVE_REFS) &&
345 !(flags & DONT_RESOLVE_DLL_REFERENCES))
347 (*pwm)->flags &= ~WINE_MODREF_DONT_RESOLVE_REFS;
348 PE_fixup_imports( *pwm );
350 TRACE("Already loaded module '%s' at %p, count=%d\n", filename, (*pwm)->module, (*pwm)->refCount);
351 if (allocated_libdir)
353 RtlFreeHeap( ntdll_get_process_heap(), 0, (LPSTR)libdir );
356 RtlLeaveCriticalSection( &loader_section );
357 RtlFreeHeap( ntdll_get_process_heap(), 0, filename );
358 return STATUS_SUCCESS;
361 MODULE_GetLoadOrder( loadorder, filename, TRUE);
363 for (i = 0; i < LOADORDER_NTYPES; i++)
365 if (loadorder[i] == LOADORDER_INVALID) break;
367 switch (loadorder[i])
370 TRACE("Trying native dll '%s'\n", filename);
371 nts = PE_LoadLibraryExA(filename, flags, pwm);
376 TRACE("Trying built-in '%s'\n", filename);
377 nts = BUILTIN32_LoadLibraryExA(filename, flags, pwm);
378 filetype = "builtin";
382 nts = STATUS_INTERNAL_ERROR;
386 if (nts == STATUS_SUCCESS)
388 /* Initialize DLL just loaded */
389 TRACE("Loaded module '%s' at %p\n", filename, (*pwm)->module);
390 if (!TRACE_ON(module))
391 TRACE_(loaddll)("Loaded module '%s' : %s\n", filename, filetype);
392 /* Set the refCount here so that an attach failure will */
393 /* decrement the dependencies through the MODULE_FreeLibrary call. */
394 (*pwm)->refCount = 1;
396 if (allocated_libdir)
398 RtlFreeHeap( ntdll_get_process_heap(), 0, (LPSTR)libdir );
401 RtlLeaveCriticalSection( &loader_section );
402 RtlFreeHeap( ntdll_get_process_heap(), 0, filename );
406 if (nts != STATUS_NO_SUCH_FILE)
408 WARN("Loading of %s DLL %s failed (status %ld).\n",
409 filetype, filename, nts);
415 if (allocated_libdir)
417 RtlFreeHeap( ntdll_get_process_heap(), 0, (LPSTR)libdir );
420 RtlLeaveCriticalSection( &loader_section );
421 WARN("Failed to load module '%s'; status=%ld\n", filename, nts);
422 RtlFreeHeap( ntdll_get_process_heap(), 0, filename );
426 /******************************************************************
427 * LdrLoadDll (NTDLL.@)
429 NTSTATUS WINAPI LdrLoadDll(LPCWSTR path_name, DWORD flags, PUNICODE_STRING libname, HMODULE* hModule)
432 NTSTATUS nts = STATUS_SUCCESS;
435 RtlUnicodeStringToAnsiString(&str, libname, TRUE);
437 RtlEnterCriticalSection( &loader_section );
439 switch (nts = MODULE_LoadLibraryExA( str.Buffer, flags, &wm ))
442 if ( !MODULE_DllProcessAttach( wm, NULL ) )
444 WARN_(module)("Attach failed for module '%s'.\n", str.Buffer);
445 LdrUnloadDll(wm->module);
446 nts = STATUS_DLL_INIT_FAILED;
450 case STATUS_NO_SUCH_FILE:
451 nts = STATUS_DLL_NOT_FOUND;
453 default: /* keep error code as it is (memory...) */
457 *hModule = (wm) ? wm->module : NULL;
459 RtlLeaveCriticalSection( &loader_section );
461 RtlFreeAnsiString(&str);
466 /******************************************************************
467 * LdrShutdownProcess (NTDLL.@)
470 NTSTATUS WINAPI LdrShutdownProcess(void)
473 MODULE_DllProcessDetach( TRUE, (LPVOID)1 );
474 return STATUS_SUCCESS; /* FIXME */
477 /******************************************************************
478 * LdrShutdownThread (NTDLL.@)
481 NTSTATUS WINAPI LdrShutdownThread(void)
486 /* don't do any detach calls if process is exiting */
487 if (process_detaching) return STATUS_SUCCESS;
488 /* FIXME: there is still a race here */
490 RtlEnterCriticalSection( &loader_section );
492 for ( wm = MODULE_modref_list; wm; wm = wm->next )
494 if ( !(wm->flags & WINE_MODREF_PROCESS_ATTACHED) )
496 if ( wm->flags & WINE_MODREF_NO_DLL_CALLS )
499 MODULE_InitDLL( wm, DLL_THREAD_DETACH, NULL );
502 RtlLeaveCriticalSection( &loader_section );
503 return STATUS_SUCCESS; /* FIXME */
506 /***********************************************************************
507 * MODULE_FlushModrefs
509 * NOTE: Assumes that the process critical section is held!
511 * Remove all unused modrefs and call the internal unloading routines
512 * for the library type.
514 static void MODULE_FlushModrefs(void)
516 WINE_MODREF *wm, *next;
518 for (wm = MODULE_modref_list; wm; wm = next)
525 /* Unlink this modref from the chain */
527 wm->next->prev = wm->prev;
529 wm->prev->next = wm->next;
530 if (wm == MODULE_modref_list)
531 MODULE_modref_list = wm->next;
533 TRACE(" unloading %s\n", wm->filename);
534 if (!TRACE_ON(module))
535 TRACE_(loaddll)("Unloaded module '%s' : %s\n", wm->filename,
536 wm->dlhandle ? "builtin" : "native" );
538 SERVER_START_REQ( unload_dll )
540 req->base = (void *)wm->module;
541 wine_server_call( req );
545 if (wm->dlhandle) wine_dll_unload( wm->dlhandle );
546 else UnmapViewOfFile( (LPVOID)wm->module );
547 FreeLibrary16( wm->hDummyMod );
548 RtlFreeHeap( ntdll_get_process_heap(), 0, wm->deps );
549 RtlFreeHeap( ntdll_get_process_heap(), 0, wm );
553 /***********************************************************************
556 * NOTE: Assumes that the process critical section is held!
558 static void MODULE_DecRefCount( WINE_MODREF *wm )
562 if ( wm->flags & WINE_MODREF_MARKER )
565 if ( wm->refCount <= 0 )
569 TRACE("(%s) refCount: %d\n", wm->modname, wm->refCount );
571 if ( wm->refCount == 0 )
573 wm->flags |= WINE_MODREF_MARKER;
575 for ( i = 0; i < wm->nDeps; i++ )
577 MODULE_DecRefCount( wm->deps[i] );
579 wm->flags &= ~WINE_MODREF_MARKER;
583 /******************************************************************
584 * LdrUnloadDll (NTDLL.@)
588 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
590 NTSTATUS retv = STATUS_SUCCESS;
592 TRACE("(%p)\n", hModule);
594 RtlEnterCriticalSection( &loader_section );
596 /* if we're stopping the whole process (and forcing the removal of all
597 * DLLs) the library will be freed anyway
599 if (!process_detaching)
604 if ((wm = MODULE32_LookupHMODULE( hModule )) != NULL)
606 TRACE("(%s) - START\n", wm->modname);
608 /* Recursively decrement reference counts */
609 MODULE_DecRefCount( wm );
611 /* Call process detach notifications */
612 if ( free_lib_count <= 1 )
614 MODULE_DllProcessDetach( FALSE, NULL );
615 MODULE_FlushModrefs();
621 retv = STATUS_DLL_NOT_FOUND;
626 RtlLeaveCriticalSection( &loader_section );
631 /***********************************************************************
632 * RtlImageNtHeader (NTDLL.@)
634 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
636 IMAGE_NT_HEADERS *ret;
640 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
643 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
645 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
646 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
658 /***********************************************************************
659 * RtlImageDirectoryEntryToData (NTDLL.@)
661 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
663 const IMAGE_NT_HEADERS *nt;
666 if ((ULONG_PTR)module & 1) /* mapped as data file */
668 module = (HMODULE)((ULONG_PTR)module & ~1);
671 if (!(nt = RtlImageNtHeader( module ))) return NULL;
672 if (dir >= nt->OptionalHeader.NumberOfRvaAndSizes) return NULL;
673 if (!(addr = nt->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
674 *size = nt->OptionalHeader.DataDirectory[dir].Size;
675 if (image || addr < nt->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
677 /* not mapped as image, need to find the section containing the virtual address */
678 return RtlImageRvaToVa( nt, module, addr, NULL );
682 /***********************************************************************
683 * RtlImageRvaToSection (NTDLL.@)
685 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
686 HMODULE module, DWORD rva )
689 IMAGE_SECTION_HEADER *sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader +
690 nt->FileHeader.SizeOfOptionalHeader);
691 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
693 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
700 /***********************************************************************
701 * RtlImageRvaToVa (NTDLL.@)
703 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
704 DWORD rva, IMAGE_SECTION_HEADER **section )
706 IMAGE_SECTION_HEADER *sec;
708 if (section && *section) /* try this section first */
711 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
714 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
716 if (section) *section = sec;
717 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);