4 * Copyright 1995, 2003 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"
33 #include "wine/debug.h"
34 #include "wine/server.h"
35 #include "ntdll_misc.h"
37 WINE_DEFAULT_DEBUG_CHANNEL(module);
38 WINE_DECLARE_DEBUG_CHANNEL(relay);
39 WINE_DECLARE_DEBUG_CHANNEL(snoop);
40 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
42 typedef DWORD (CALLBACK *DLLENTRYPROC)(HMODULE,DWORD,LPVOID);
44 WINE_MODREF *MODULE_modref_list = NULL;
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 */
50 /* filter for page-fault exceptions */
51 static WINE_EXCEPTION_FILTER(page_fault)
53 if (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION)
54 return EXCEPTION_EXECUTE_HANDLER;
55 return EXCEPTION_CONTINUE_SEARCH;
58 static const char * const reason_names[] =
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 */
70 static CRITICAL_SECTION loader_section = CRITICAL_SECTION_INIT( "loader_section" );
71 static WINE_MODREF *cached_modref;
72 static WINE_MODREF *current_modref;
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 );
78 /* convert PE image VirtualAddress to Real Address */
79 inline static void *get_rva( HMODULE module, DWORD va )
81 return (void *)((char *)module + va);
84 /*************************************************************************
87 * Looks for the referenced HMODULE in the current process
88 * The loader_section must be locked while calling this function.
90 static WINE_MODREF *get_modref( HMODULE hmod )
94 if (cached_modref && cached_modref->ldr.BaseAddress == hmod) return cached_modref;
96 for ( wm = MODULE_modref_list; wm; wm=wm->next )
98 if (wm->ldr.BaseAddress == hmod)
108 /*************************************************************************
109 * find_forwarded_export
111 * Find the final function pointer for a forwarded function.
112 * The loader_section must be locked while calling this function.
114 static FARPROC find_forwarded_export( HMODULE module, const char *forward )
116 IMAGE_EXPORT_DIRECTORY *exports;
120 char *end = strchr(forward, '.');
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;
128 if (!(wm = MODULE_FindModule( mod_name )))
130 ERR("module not found for forward '%s' used by '%s'\n",
131 forward, get_modref(module)->filename );
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 );
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 );
148 /*************************************************************************
149 * find_ordinal_export
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.
155 static FARPROC find_ordinal_export( HMODULE module, IMAGE_EXPORT_DIRECTORY *exports,
156 DWORD exp_size, int ordinal )
159 DWORD *functions = get_rva( module, exports->AddressOfFunctions );
161 if (ordinal >= exports->NumberOfFunctions)
163 TRACE(" ordinal %ld out of range!\n", ordinal + exports->Base );
166 if (!functions[ordinal]) return NULL;
168 proc = get_rva( module, functions[ordinal] );
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 );
176 proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal );
178 if (TRACE_ON(relay) && current_modref)
180 proc = RELAY_GetProcAddress( module, exports, exp_size, proc, current_modref->modname );
186 /*************************************************************************
189 * Find an exported function by name.
190 * The loader_section must be locked while calling this function.
192 static FARPROC find_named_export( HMODULE module, IMAGE_EXPORT_DIRECTORY *exports,
193 DWORD exp_size, const char *name, int hint )
195 WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
196 DWORD *names = get_rva( module, exports->AddressOfNames );
197 int min = 0, max = exports->NumberOfNames - 1;
199 /* first check the hint */
200 if (hint >= 0 && hint <= max)
202 char *ename = get_rva( module, names[hint] );
203 if (!strcmp( ename, name ))
204 return find_ordinal_export( module, exports, exp_size, ordinals[hint] );
207 /* then do a binary search */
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;
222 /*************************************************************************
225 * Import the dll specified by the given import descriptor.
226 * The loader_section must be locked while calling this function.
228 static WINE_MODREF *import_dll( HMODULE module, IMAGE_IMPORT_DESCRIPTOR *descr )
233 IMAGE_EXPORT_DIRECTORY *exports;
235 IMAGE_THUNK_DATA *import_list, *thunk_list;
236 char *name = get_rva( module, descr->Name );
238 status = load_dll( name, 0, &wmImp );
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);
245 ERR("Loading module (file) %s (which is needed by %s) failed (error %ld).\n",
246 name, current_modref->filename, status);
250 imp_mod = wmImp->ldr.BaseAddress;
251 if (!(exports = RtlImageDirectoryEntryToData( imp_mod, TRUE,
252 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
255 thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
256 if (descr->u.OriginalFirstThunk)
257 import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
259 import_list = thunk_list;
261 while (import_list->u1.Ordinal)
263 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
265 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
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)
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;
277 else /* import by name */
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)
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;
298 /****************************************************************
301 * Fixup all imports of a given module.
302 * The loader_section must be locked while calling this function.
304 DWORD PE_fixup_imports( WINE_MODREF *wm )
307 IMAGE_IMPORT_DESCRIPTOR *imports;
311 if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
312 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
315 nb_imports = size / sizeof(*imports);
316 for (i = 0; i < nb_imports; i++)
318 if (!imports[i].Name)
324 if (!nb_imports) return 0; /* no imports */
326 /* Allocate module dependency list */
327 wm->nDeps = nb_imports;
328 wm->deps = RtlAllocateHeap( ntdll_get_process_heap(), 0, nb_imports*sizeof(WINE_MODREF *) );
330 /* load the imported modules. They are automatically
331 * added to the modref list of the process.
333 prev = current_modref;
335 for (i = 0; i < nb_imports; i++)
337 if (!(wm->deps[i] = import_dll( wm->ldr.BaseAddress, &imports[i] ))) break;
339 current_modref = prev;
340 return (i < nb_imports);
344 /*************************************************************************
347 * Allocate a WINE_MODREF structure and add it to the process list
348 * The loader_section must be locked while calling this function.
350 WINE_MODREF *MODULE_AllocModRef( HMODULE hModule, LPCSTR filename )
353 IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
355 DWORD long_len = strlen( filename );
356 DWORD short_len = GetShortPathNameA( filename, NULL, 0 );
358 if ((wm = RtlAllocateHeap( ntdll_get_process_heap(), HEAP_ZERO_MEMORY,
359 sizeof(*wm) + long_len + short_len + 1 )))
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;
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;
371 wm->next = MODULE_modref_list;
372 if (wm->next) wm->next->prev = wm;
373 MODULE_modref_list = wm;
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);
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;
394 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL))
396 if (!exe_modref) exe_modref = wm;
398 else wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
404 /*************************************************************************
407 * Allocate the process-wide structure for module TLS storage.
409 static NTSTATUS alloc_process_tls(void)
412 IMAGE_TLS_DIRECTORY *dir;
415 for (wm = MODULE_modref_list; wm; wm = wm->next)
417 if (!(dir = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
418 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
420 size = (dir->EndAddressOfRawData - dir->StartAddressOfRawData) + dir->SizeOfZeroFill;
422 tls_total_size += size;
425 if (!tls_module_count) return STATUS_SUCCESS;
427 TRACE( "count %u size %u\n", tls_module_count, tls_total_size );
429 tls_dirs = RtlAllocateHeap( ntdll_get_process_heap(), 0, tls_module_count * sizeof(*tls_dirs) );
430 if (!tls_dirs) return STATUS_NO_MEMORY;
432 for (i = 0, wm = MODULE_modref_list; wm; wm = wm->next)
434 if (!(dir = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
435 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
438 *dir->AddressOfIndex = i;
439 wm->ldr.TlsIndex = i;
440 wm->ldr.LoadCount = -1; /* can't unload it */
443 return STATUS_SUCCESS;
447 /*************************************************************************
450 * Allocate the per-thread structure for module TLS storage.
452 static NTSTATUS alloc_thread_tls(void)
458 if (!tls_module_count) return STATUS_SUCCESS;
460 if (!(pointers = RtlAllocateHeap( ntdll_get_process_heap(), 0,
461 tls_module_count * sizeof(*pointers) )))
462 return STATUS_NO_MEMORY;
464 if (!(data = RtlAllocateHeap( ntdll_get_process_heap(), 0, tls_total_size )))
466 RtlFreeHeap( ntdll_get_process_heap(), 0, pointers );
467 return STATUS_NO_MEMORY;
470 for (i = 0; i < tls_module_count; i++)
472 const IMAGE_TLS_DIRECTORY *dir = tls_dirs[i];
473 ULONG size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
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 );
480 memcpy( data, (void *)dir->StartAddressOfRawData, size );
482 memset( data, 0, dir->SizeOfZeroFill );
483 data += dir->SizeOfZeroFill;
485 NtCurrentTeb()->tls_ptr = pointers;
486 return STATUS_SUCCESS;
490 /*************************************************************************
493 static void call_tls_callbacks( HMODULE module, UINT reason )
495 const IMAGE_TLS_DIRECTORY *dir;
496 const PIMAGE_TLS_CALLBACK *callback;
499 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
500 if (!dir || !dir->AddressOfCallBacks) return;
502 for (callback = dir->AddressOfCallBacks; *callback; callback++)
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 );
509 DPRINTF("%04lx:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
510 GetCurrentThreadId(), *callback, module, reason_names[reason] );
515 /*************************************************************************
518 static BOOL MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
522 DLLENTRYPROC entry = wm->ldr.EntryPoint;
523 void *module = wm->ldr.BaseAddress;
525 /* Skip calls for modules loaded with special load flags */
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;
533 size_t len = max( strlen(wm->modname), sizeof(mod_name)-1 );
534 memcpy( mod_name, wm->modname, len );
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 );
539 else TRACE("(%p (%s),%s,%p) - CALL\n", module, wm->modname, reason_names[reason], lpReserved );
541 retv = entry( module, reason, lpReserved );
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
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 );
555 /*************************************************************************
556 * MODULE_DllProcessAttach
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
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
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
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
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.
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*.
584 NTSTATUS MODULE_DllProcessAttach( WINE_MODREF *wm, LPVOID lpReserved )
586 NTSTATUS status = STATUS_SUCCESS;
589 RtlEnterCriticalSection( &loader_section );
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;
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 ) )
605 TRACE("(%s,%p) - START\n", wm->modname, lpReserved );
607 /* Tag current MODREF to prevent recursive loop */
608 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
610 /* Recursively attach all DLLs this one depends on */
611 for ( i = 0; i < wm->nDeps; i++ )
613 if (!wm->deps[i]) continue;
614 if ((status = MODULE_DllProcessAttach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
617 /* Call DLL entry point */
618 if (status == STATUS_SUCCESS)
620 WINE_MODREF *prev = current_modref;
622 if (MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved ))
623 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
625 status = STATUS_DLL_INIT_FAILED;
626 current_modref = prev;
629 /* Re-insert MODREF at head of list */
630 if (status == STATUS_SUCCESS && wm->prev )
632 wm->prev->next = wm->next;
633 if ( wm->next ) wm->next->prev = wm->prev;
636 wm->next = MODULE_modref_list;
637 MODULE_modref_list = wm->next->prev = wm;
640 /* Remove recursion flag */
641 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
643 TRACE("(%s,%p) - END\n", wm->modname, lpReserved );
646 RtlLeaveCriticalSection( &loader_section );
650 /*************************************************************************
651 * MODULE_DllProcessDetach
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.
657 static void MODULE_DllProcessDetach( BOOL bForceDetach, LPVOID lpReserved )
661 RtlEnterCriticalSection( &loader_section );
662 if (bForceDetach) process_detaching = 1;
665 for ( wm = MODULE_modref_list; wm; wm = wm->next )
667 /* Check whether to detach this DLL */
668 if ( !(wm->ldr.Flags & LDR_PROCESS_ATTACHED) )
670 if ( wm->ldr.LoadCount && !bForceDetach )
673 /* Call detach notification */
674 wm->ldr.Flags &= ~LDR_PROCESS_ATTACHED;
675 MODULE_InitDLL( wm, DLL_PROCESS_DETACH, lpReserved );
677 /* Restart at head of WINE_MODREF list, as entries might have
678 been added and/or removed while performing the call ... */
683 RtlLeaveCriticalSection( &loader_section );
686 /*************************************************************************
687 * MODULE_DllThreadAttach
689 * Send DLL thread attach notifications. These are sent in the
690 * reverse sequence of process detach notification.
693 NTSTATUS MODULE_DllThreadAttach( LPVOID lpReserved )
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 */
702 RtlEnterCriticalSection( &loader_section );
704 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto done;
706 for ( wm = MODULE_modref_list; wm; wm = wm->next )
710 for ( ; wm; wm = wm->prev )
712 if ( !(wm->ldr.Flags & LDR_PROCESS_ATTACHED) )
714 if ( wm->ldr.Flags & LDR_NO_DLL_CALLS )
717 MODULE_InitDLL( wm, DLL_THREAD_ATTACH, lpReserved );
721 RtlLeaveCriticalSection( &loader_section );
725 /******************************************************************
726 * LdrDisableThreadCalloutsForDll (NTDLL.@)
729 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
732 NTSTATUS ret = STATUS_SUCCESS;
734 RtlEnterCriticalSection( &loader_section );
736 wm = get_modref( hModule );
737 if (!wm || wm->ldr.TlsIndex != -1)
738 ret = STATUS_DLL_NOT_FOUND;
740 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
742 RtlLeaveCriticalSection( &loader_section );
747 /******************************************************************
748 * LdrFindEntryForAddress (NTDLL.@)
750 * The loader_section must be locked while calling this function
752 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* mod)
756 for ( wm = MODULE_modref_list; wm; wm = wm->next )
758 if ((const void *)wm->ldr.BaseAddress <= addr &&
759 (char *)addr < (char*)wm->ldr.BaseAddress + wm->ldr.SizeOfImage)
762 return STATUS_SUCCESS;
765 return STATUS_NO_MORE_ENTRIES;
768 /**********************************************************************
771 * Find a (loaded) win32 module depending on path
772 * LPCSTR path: [in] pathname of module/library to be found
774 * The loader_section must be locked while calling this function
776 * the module handle if found
779 WINE_MODREF *MODULE_FindModule(LPCSTR path)
782 char dllname[260], *p;
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" );
789 if ((wm = cached_modref) != NULL)
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;
797 for ( wm = MODULE_modref_list; wm; wm = wm->next )
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;
809 /******************************************************************
810 * LdrLockLoaderLock (NTDLL.@)
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).
816 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG *magic )
818 if (flags) FIXME( "flags %lx not supported\n", flags );
820 if (result) *result = 1;
821 if (!magic) return STATUS_INVALID_PARAMETER_3;
822 RtlEnterCriticalSection( &loader_section );
823 *magic = GetCurrentThreadId();
824 return STATUS_SUCCESS;
828 /******************************************************************
829 * LdrUnlockLoaderUnlock (NTDLL.@)
831 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG magic )
835 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
836 RtlLeaveCriticalSection( &loader_section );
838 return STATUS_SUCCESS;
842 /******************************************************************
843 * LdrGetDllHandle (NTDLL.@)
847 NTSTATUS WINAPI LdrGetDllHandle(ULONG x, ULONG y, PUNICODE_STRING name, HMODULE *base)
852 if (x != 0 || y != 0)
853 FIXME("Unknown behavior, please report\n");
855 /* FIXME: we should store module name information as unicode */
856 RtlUnicodeStringToAnsiString( &str, name, TRUE );
857 wm = MODULE_FindModule( str.Buffer );
858 RtlFreeAnsiString( &str );
863 return STATUS_DLL_NOT_FOUND;
866 *base = wm->ldr.BaseAddress;
868 TRACE("%lx %lx %s -> %p\n", x, y, debugstr_us(name), *base);
870 return STATUS_SUCCESS;
874 /******************************************************************
875 * LdrGetProcedureAddress (NTDLL.@)
877 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, PANSI_STRING name, ULONG ord, PVOID *address)
879 IMAGE_EXPORT_DIRECTORY *exports;
881 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
883 RtlEnterCriticalSection( &loader_section );
885 if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
886 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
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 );
893 ret = STATUS_SUCCESS;
898 /* check if the module itself is invalid to return the proper error */
899 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
902 RtlLeaveCriticalSection( &loader_section );
907 /***********************************************************************
910 * helper for MODULE_LoadLibraryExA. Allocate space to hold the directory
911 * portion of the provided name and put the name in it.
914 static LPCSTR allocate_lib_dir(LPCSTR 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;
925 length = pmax - libname;
927 result = RtlAllocateHeap (ntdll_get_process_heap(), 0, length+1);
931 strncpy (result, libname, length);
932 result [length] = '\0';
938 /***********************************************************************
939 * load_dll (internal)
941 * Load a PE style module according to the load order.
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
954 static NTSTATUS load_dll( LPCSTR libname, DWORD flags, WINE_MODREF** pwm )
957 enum loadorder_type loadorder[LOADORDER_NTYPES];
959 const char *filetype = "";
961 BOOL allocated_libdir = FALSE;
962 static LPCSTR libdir = NULL; /* See above */
963 NTSTATUS nts = STATUS_SUCCESS;
966 if ( !libname ) return STATUS_DLL_NOT_FOUND; /* FIXME ? */
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 */
972 RtlEnterCriticalSection( &loader_section );
974 if ((flags & LOAD_WITH_ALTERED_SEARCH_PATH) && FILE_contains_path(libname))
976 if (!(libdir = allocate_lib_dir(libname)))
978 nts = STATUS_NO_MEMORY;
981 allocated_libdir = TRUE;
984 if (!libdir || allocated_libdir)
985 found = SearchPathA(NULL, libname, ".dll", MAX_PATH, filename, NULL);
987 found = DIR_SearchAlternatePath(libdir, libname, ".dll", MAX_PATH, filename, NULL);
989 /* build the modules filename */
992 if (!MODULE_GetBuiltinPath( libname, ".dll", filename, MAX_PATH ))
994 nts = STATUS_INTERNAL_ERROR;
999 /* Check for already loaded module */
1000 if (!(*pwm = MODULE_FindModule(filename)) && !FILE_contains_path(libname))
1002 LPSTR fn = RtlAllocateHeap ( ntdll_get_process_heap(), 0, MAX_PATH + 1 );
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)
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 );
1022 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
1024 if (((*pwm)->ldr.Flags & LDR_DONT_RESOLVE_REFS) &&
1025 !(flags & DONT_RESOLVE_DLL_REFERENCES))
1027 (*pwm)->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
1028 PE_fixup_imports( *pwm );
1030 TRACE("Already loaded module '%s' at %p, count=%d\n", filename, (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
1031 if (allocated_libdir)
1033 RtlFreeHeap( ntdll_get_process_heap(), 0, (LPSTR)libdir );
1036 RtlLeaveCriticalSection( &loader_section );
1037 RtlFreeHeap( ntdll_get_process_heap(), 0, filename );
1038 return STATUS_SUCCESS;
1041 MODULE_GetLoadOrder( loadorder, filename, TRUE);
1043 for (i = 0; i < LOADORDER_NTYPES; i++)
1045 if (loadorder[i] == LOADORDER_INVALID) break;
1047 switch (loadorder[i])
1050 TRACE("Trying native dll '%s'\n", filename);
1051 nts = PE_LoadLibraryExA(filename, flags, pwm);
1052 filetype = "native";
1056 TRACE("Trying built-in '%s'\n", filename);
1057 nts = BUILTIN32_LoadLibraryExA(filename, flags, pwm);
1058 filetype = "builtin";
1062 nts = STATUS_INTERNAL_ERROR;
1066 if (nts == STATUS_SUCCESS)
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;
1076 if (allocated_libdir)
1078 RtlFreeHeap( ntdll_get_process_heap(), 0, (LPSTR)libdir );
1081 RtlLeaveCriticalSection( &loader_section );
1082 RtlFreeHeap( ntdll_get_process_heap(), 0, filename );
1086 if (nts != STATUS_NO_SUCH_FILE)
1088 WARN("Loading of %s DLL %s failed (status %ld).\n",
1089 filetype, filename, nts);
1095 if (allocated_libdir)
1097 RtlFreeHeap( ntdll_get_process_heap(), 0, (LPSTR)libdir );
1100 RtlLeaveCriticalSection( &loader_section );
1101 WARN("Failed to load module '%s'; status=%ld\n", filename, nts);
1102 RtlFreeHeap( ntdll_get_process_heap(), 0, filename );
1106 /******************************************************************
1107 * LdrLoadDll (NTDLL.@)
1109 NTSTATUS WINAPI LdrLoadDll(LPCWSTR path_name, DWORD flags, PUNICODE_STRING libname, HMODULE* hModule)
1112 NTSTATUS nts = STATUS_SUCCESS;
1115 RtlUnicodeStringToAnsiString(&str, libname, TRUE);
1117 RtlEnterCriticalSection( &loader_section );
1119 switch (nts = load_dll( str.Buffer, flags, &wm ))
1121 case STATUS_SUCCESS:
1122 nts = MODULE_DllProcessAttach( wm, NULL );
1123 if (nts != STATUS_SUCCESS)
1125 WARN("Attach failed for module '%s'.\n", str.Buffer);
1126 LdrUnloadDll(wm->ldr.BaseAddress);
1130 case STATUS_NO_SUCH_FILE:
1131 nts = STATUS_DLL_NOT_FOUND;
1133 default: /* keep error code as it is (memory...) */
1137 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
1139 RtlLeaveCriticalSection( &loader_section );
1141 RtlFreeAnsiString(&str);
1146 /******************************************************************
1147 * LdrQueryProcessModuleInformation
1150 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
1151 ULONG buf_size, ULONG* req_size)
1153 SYSTEM_MODULE* sm = &smi->Modules[0];
1154 ULONG size = sizeof(ULONG);
1155 NTSTATUS nts = STATUS_SUCCESS;
1160 smi->ModulesCount = 0;
1162 RtlEnterCriticalSection( &loader_section );
1163 for ( wm = MODULE_modref_list; wm; wm = wm->next )
1165 size += sizeof(*sm);
1166 if (size <= buf_size)
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 */
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;
1183 smi->ModulesCount++;
1186 else nts = STATUS_INFO_LENGTH_MISMATCH;
1188 RtlLeaveCriticalSection( &loader_section );
1190 if (req_size) *req_size = size;
1195 /******************************************************************
1196 * LdrShutdownProcess (NTDLL.@)
1199 void WINAPI LdrShutdownProcess(void)
1202 MODULE_DllProcessDetach( TRUE, (LPVOID)1 );
1205 /******************************************************************
1206 * LdrShutdownThread (NTDLL.@)
1209 void WINAPI LdrShutdownThread(void)
1214 /* don't do any detach calls if process is exiting */
1215 if (process_detaching) return;
1216 /* FIXME: there is still a race here */
1218 RtlEnterCriticalSection( &loader_section );
1220 for ( wm = MODULE_modref_list; wm; wm = wm->next )
1222 if ( !(wm->ldr.Flags & LDR_PROCESS_ATTACHED) )
1224 if ( wm->ldr.Flags & LDR_NO_DLL_CALLS )
1227 MODULE_InitDLL( wm, DLL_THREAD_DETACH, NULL );
1230 RtlLeaveCriticalSection( &loader_section );
1233 /***********************************************************************
1234 * MODULE_FlushModrefs
1236 * Remove all unused modrefs and call the internal unloading routines
1237 * for the library type.
1239 * The loader_section must be locked while calling this function.
1241 static void MODULE_FlushModrefs(void)
1243 WINE_MODREF *wm, *next;
1245 for (wm = MODULE_modref_list; wm; wm = next)
1249 if (wm->ldr.LoadCount)
1252 /* Unlink this modref from the chain */
1254 wm->next->prev = wm->prev;
1256 wm->prev->next = wm->next;
1257 if (wm == MODULE_modref_list)
1258 MODULE_modref_list = wm->next;
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" );
1265 SERVER_START_REQ( unload_dll )
1267 req->base = wm->ldr.BaseAddress;
1268 wine_server_call( req );
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 );
1280 /***********************************************************************
1281 * MODULE_DecRefCount
1283 * The loader_section must be locked while calling this function.
1285 static void MODULE_DecRefCount( WINE_MODREF *wm )
1289 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
1292 if ( wm->ldr.LoadCount <= 0 )
1295 --wm->ldr.LoadCount;
1296 TRACE("(%s) ldr.LoadCount: %d\n", wm->modname, wm->ldr.LoadCount );
1298 if ( wm->ldr.LoadCount == 0 )
1300 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
1302 for ( i = 0; i < wm->nDeps; i++ )
1304 MODULE_DecRefCount( wm->deps[i] );
1306 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
1310 /******************************************************************
1311 * LdrUnloadDll (NTDLL.@)
1315 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
1317 NTSTATUS retv = STATUS_SUCCESS;
1319 TRACE("(%p)\n", hModule);
1321 RtlEnterCriticalSection( &loader_section );
1323 /* if we're stopping the whole process (and forcing the removal of all
1324 * DLLs) the library will be freed anyway
1326 if (!process_detaching)
1331 if ((wm = get_modref( hModule )) != NULL)
1333 TRACE("(%s) - START\n", wm->modname);
1335 /* Recursively decrement reference counts */
1336 MODULE_DecRefCount( wm );
1338 /* Call process detach notifications */
1339 if ( free_lib_count <= 1 )
1341 MODULE_DllProcessDetach( FALSE, NULL );
1342 MODULE_FlushModrefs();
1348 retv = STATUS_DLL_NOT_FOUND;
1353 RtlLeaveCriticalSection( &loader_section );
1358 /***********************************************************************
1359 * RtlImageNtHeader (NTDLL.@)
1361 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
1363 IMAGE_NT_HEADERS *ret;
1367 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
1370 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
1372 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
1373 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
1376 __EXCEPT(page_fault)
1385 /***********************************************************************
1386 * RtlImageDirectoryEntryToData (NTDLL.@)
1388 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
1390 const IMAGE_NT_HEADERS *nt;
1393 if ((ULONG_PTR)module & 1) /* mapped as data file */
1395 module = (HMODULE)((ULONG_PTR)module & ~1);
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;
1404 /* not mapped as image, need to find the section containing the virtual address */
1405 return RtlImageRvaToVa( nt, module, addr, NULL );
1409 /***********************************************************************
1410 * RtlImageRvaToSection (NTDLL.@)
1412 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
1413 HMODULE module, DWORD rva )
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++)
1420 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
1427 /***********************************************************************
1428 * RtlImageRvaToVa (NTDLL.@)
1430 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
1431 DWORD rva, IMAGE_SECTION_HEADER **section )
1433 IMAGE_SECTION_HEADER *sec;
1435 if (section && *section) /* try this section first */
1438 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
1441 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
1443 if (section) *section = sec;
1444 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);