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
32 #include "wine/exception.h"
34 #include "wine/unicode.h"
35 #include "wine/debug.h"
36 #include "wine/server.h"
37 #include "ntdll_misc.h"
39 WINE_DEFAULT_DEBUG_CHANNEL(module);
40 WINE_DECLARE_DEBUG_CHANNEL(relay);
41 WINE_DECLARE_DEBUG_CHANNEL(snoop);
42 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
44 typedef DWORD (CALLBACK *DLLENTRYPROC)(HMODULE,DWORD,LPVOID);
46 static int process_detaching = 0; /* set on process detach to avoid deadlocks with thread detach */
47 static int free_lib_count; /* recursion depth of LdrUnloadDll calls */
49 /* filter for page-fault exceptions */
50 static WINE_EXCEPTION_FILTER(page_fault)
52 if (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION)
53 return EXCEPTION_EXECUTE_HANDLER;
54 return EXCEPTION_CONTINUE_SEARCH;
57 static const char * const reason_names[] =
65 static const WCHAR dllW[] = {'.','d','l','l',0};
67 /* internal representation of 32bit modules. per process. */
68 typedef struct _wine_modref
72 struct _wine_modref **deps;
75 /* info about the current builtin dll load */
76 /* used to keep track of things across the register_dll constructor call */
77 struct builtin_load_info
79 const WCHAR *load_path;
84 static struct builtin_load_info default_load_info;
85 static struct builtin_load_info *builtin_load_info = &default_load_info;
87 static UINT tls_module_count; /* number of modules with TLS directory */
88 static UINT tls_total_size; /* total size of TLS storage */
89 static const IMAGE_TLS_DIRECTORY **tls_dirs; /* array of TLS directories */
91 static UNICODE_STRING system_dir; /* system directory */
93 static CRITICAL_SECTION loader_section;
94 static CRITICAL_SECTION_DEBUG critsect_debug =
96 0, 0, &loader_section,
97 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
98 0, 0, { 0, (DWORD)(__FILE__ ": loader_section") }
100 static CRITICAL_SECTION loader_section = { &critsect_debug, -1, 0, 0, 0, 0 };
102 static WINE_MODREF *cached_modref;
103 static WINE_MODREF *current_modref;
105 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm );
106 static FARPROC find_named_export( HMODULE module, IMAGE_EXPORT_DIRECTORY *exports,
107 DWORD exp_size, const char *name, int hint );
109 /* convert PE image VirtualAddress to Real Address */
110 inline static void *get_rva( HMODULE module, DWORD va )
112 return (void *)((char *)module + va);
115 /* check whether the file name contains a path */
116 inline static int contains_path( LPCWSTR name )
118 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
121 /* convert from straight ASCII to Unicode without depending on the current codepage */
122 inline static void ascii_to_unicode( WCHAR *dst, const char *src, size_t len )
124 while (len--) *dst++ = (unsigned char)*src++;
127 /*************************************************************************
130 * Looks for the referenced HMODULE in the current process
131 * The loader_section must be locked while calling this function.
133 static WINE_MODREF *get_modref( HMODULE hmod )
135 PLIST_ENTRY mark, entry;
138 if (cached_modref && cached_modref->ldr.BaseAddress == hmod) return cached_modref;
140 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
141 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
143 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
144 if (mod->BaseAddress == hmod)
145 return cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
146 if (mod->BaseAddress > (void*)hmod) break;
152 /**********************************************************************
153 * find_basename_module
155 * Find a module from its base name.
156 * The loader_section must be locked while calling this function
158 static WINE_MODREF *find_basename_module( LPCWSTR name )
160 PLIST_ENTRY mark, entry;
162 if (cached_modref && !strcmpiW( name, cached_modref->ldr.BaseDllName.Buffer ))
163 return cached_modref;
165 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
166 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
168 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
169 if (!strcmpiW( name, mod->BaseDllName.Buffer ))
171 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
172 return cached_modref;
179 /**********************************************************************
180 * find_fullname_module
182 * Find a module from its full path name.
183 * The loader_section must be locked while calling this function
185 static WINE_MODREF *find_fullname_module( LPCWSTR name )
187 PLIST_ENTRY mark, entry;
189 if (cached_modref && !strcmpiW( name, cached_modref->ldr.FullDllName.Buffer ))
190 return cached_modref;
192 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
193 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
195 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
196 if (!strcmpiW( name, mod->FullDllName.Buffer ))
198 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
199 return cached_modref;
206 /*************************************************************************
207 * find_forwarded_export
209 * Find the final function pointer for a forwarded function.
210 * The loader_section must be locked while calling this function.
212 static FARPROC find_forwarded_export( HMODULE module, const char *forward )
214 IMAGE_EXPORT_DIRECTORY *exports;
218 char *end = strchr(forward, '.');
221 if (!end) return NULL;
222 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name) - sizeof(dllW)) return NULL;
223 ascii_to_unicode( mod_name, forward, end - forward );
224 memcpy( mod_name + (end - forward), dllW, sizeof(dllW) );
226 if (!(wm = find_basename_module( mod_name )))
228 ERR("module not found for forward '%s' used by %s\n",
229 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer) );
232 if ((exports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
233 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
234 proc = find_named_export( wm->ldr.BaseAddress, exports, exp_size, end + 1, -1 );
238 ERR("function not found for forward '%s' used by %s."
239 " If you are using builtin %s, try using the native one instead.\n",
240 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer),
241 debugstr_w(get_modref(module)->ldr.BaseDllName.Buffer) );
247 /*************************************************************************
248 * find_ordinal_export
250 * Find an exported function by ordinal.
251 * The exports base must have been subtracted from the ordinal already.
252 * The loader_section must be locked while calling this function.
254 static FARPROC find_ordinal_export( HMODULE module, IMAGE_EXPORT_DIRECTORY *exports,
255 DWORD exp_size, int ordinal )
258 DWORD *functions = get_rva( module, exports->AddressOfFunctions );
260 if (ordinal >= exports->NumberOfFunctions)
262 TRACE(" ordinal %ld out of range!\n", ordinal + exports->Base );
265 if (!functions[ordinal]) return NULL;
267 proc = get_rva( module, functions[ordinal] );
269 /* if the address falls into the export dir, it's a forward */
270 if (((char *)proc >= (char *)exports) && ((char *)proc < (char *)exports + exp_size))
271 return find_forwarded_export( module, (char *)proc );
275 proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal );
277 if (TRACE_ON(relay) && current_modref)
279 proc = RELAY_GetProcAddress( module, exports, exp_size, proc,
280 current_modref->ldr.BaseDllName.Buffer );
286 /*************************************************************************
289 * Find an exported function by name.
290 * The loader_section must be locked while calling this function.
292 static FARPROC find_named_export( HMODULE module, IMAGE_EXPORT_DIRECTORY *exports,
293 DWORD exp_size, const char *name, int hint )
295 WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
296 DWORD *names = get_rva( module, exports->AddressOfNames );
297 int min = 0, max = exports->NumberOfNames - 1;
299 /* first check the hint */
300 if (hint >= 0 && hint <= max)
302 char *ename = get_rva( module, names[hint] );
303 if (!strcmp( ename, name ))
304 return find_ordinal_export( module, exports, exp_size, ordinals[hint] );
307 /* then do a binary search */
310 int res, pos = (min + max) / 2;
311 char *ename = get_rva( module, names[pos] );
312 if (!(res = strcmp( ename, name )))
313 return find_ordinal_export( module, exports, exp_size, ordinals[pos] );
314 if (res > 0) max = pos - 1;
322 /*************************************************************************
325 * Import the dll specified by the given import descriptor.
326 * The loader_section must be locked while calling this function.
328 static WINE_MODREF *import_dll( HMODULE module, IMAGE_IMPORT_DESCRIPTOR *descr, LPCWSTR load_path )
333 IMAGE_EXPORT_DIRECTORY *exports;
335 IMAGE_THUNK_DATA *import_list, *thunk_list;
337 char *name = get_rva( module, descr->Name );
338 DWORD len = strlen(name) + 1;
340 thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
341 if (descr->u.OriginalFirstThunk)
342 import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
344 import_list = thunk_list;
346 if (len * sizeof(WCHAR) <= sizeof(buffer))
348 ascii_to_unicode( buffer, name, len );
349 status = load_dll( load_path, buffer, 0, &wmImp );
351 else /* need to allocate a larger buffer */
353 WCHAR *ptr = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR) );
354 if (!ptr) return NULL;
355 ascii_to_unicode( ptr, name, len );
356 status = load_dll( load_path, ptr, 0, &wmImp );
357 RtlFreeHeap( GetProcessHeap(), 0, ptr );
362 if (status == STATUS_DLL_NOT_FOUND)
363 ERR("Module (file) %s (which is needed by %s) not found\n",
364 name, debugstr_w(current_modref->ldr.FullDllName.Buffer));
366 ERR("Loading module (file) %s (which is needed by %s) failed (error %lx).\n",
367 name, debugstr_w(current_modref->ldr.FullDllName.Buffer), status);
373 imp_mod = wmImp->ldr.BaseAddress;
374 exports = RtlImageDirectoryEntryToData( imp_mod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
379 /* set all imported function to deadbeef */
380 while (import_list->u1.Ordinal)
382 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
384 ERR("No implementation for %s.%ld", name, IMAGE_ORDINAL(import_list->u1.Ordinal));
388 IMAGE_IMPORT_BY_NAME *pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
389 ERR("No implementation for %s.%s", name, pe_name->Name );
391 ERR(" imported from %s, setting to 0xdeadbeef\n",
392 debugstr_w(current_modref->ldr.FullDllName.Buffer) );
393 thunk_list->u1.Function = (PDWORD)0xdeadbeef;
401 while (import_list->u1.Ordinal)
403 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
405 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
407 thunk_list->u1.Function = (PDWORD)find_ordinal_export( imp_mod, exports, exp_size,
408 ordinal - exports->Base );
409 if (!thunk_list->u1.Function)
411 ERR("No implementation for %s.%d imported from %s, setting to 0xdeadbeef\n",
412 name, ordinal, debugstr_w(current_modref->ldr.FullDllName.Buffer) );
413 thunk_list->u1.Function = (PDWORD)0xdeadbeef;
415 TRACE("--- Ordinal %s.%d = %p\n", name, ordinal, thunk_list->u1.Function );
417 else /* import by name */
419 IMAGE_IMPORT_BY_NAME *pe_name;
420 pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
421 thunk_list->u1.Function = (PDWORD)find_named_export( imp_mod, exports, exp_size,
422 pe_name->Name, pe_name->Hint );
423 if (!thunk_list->u1.Function)
425 ERR("No implementation for %s.%s imported from %s, setting to 0xdeadbeef\n",
426 name, pe_name->Name, debugstr_w(current_modref->ldr.FullDllName.Buffer) );
427 thunk_list->u1.Function = (PDWORD)0xdeadbeef;
429 TRACE("--- %s %s.%d = %p\n", pe_name->Name, name, pe_name->Hint, thunk_list->u1.Function);
438 /****************************************************************
441 * Fixup all imports of a given module.
442 * The loader_section must be locked while calling this function.
444 static NTSTATUS fixup_imports( WINE_MODREF *wm, LPCWSTR load_path )
447 IMAGE_IMPORT_DESCRIPTOR *imports;
452 if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
453 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
454 return STATUS_SUCCESS;
456 nb_imports = size / sizeof(*imports);
457 for (i = 0; i < nb_imports; i++)
459 if (!imports[i].Name)
465 if (!nb_imports) return STATUS_SUCCESS; /* no imports */
467 /* Allocate module dependency list */
468 wm->nDeps = nb_imports;
469 wm->deps = RtlAllocateHeap( ntdll_get_process_heap(), 0, nb_imports*sizeof(WINE_MODREF *) );
471 /* load the imported modules. They are automatically
472 * added to the modref list of the process.
474 prev = current_modref;
476 status = STATUS_SUCCESS;
477 for (i = 0; i < nb_imports; i++)
479 if (!(wm->deps[i] = import_dll( wm->ldr.BaseAddress, &imports[i], load_path )))
480 status = STATUS_DLL_NOT_FOUND;
482 current_modref = prev;
487 /*************************************************************************
490 * Allocate a WINE_MODREF structure and add it to the process list
491 * The loader_section must be locked while calling this function.
493 static WINE_MODREF *alloc_module( HMODULE hModule, LPCWSTR filename )
497 IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
498 PLIST_ENTRY entry, mark;
499 BOOLEAN linked = FALSE;
502 RtlUnicodeToMultiByteSize( &len, filename, (strlenW(filename) + 1) * sizeof(WCHAR) );
503 if (!(wm = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm) + len )))
509 wm->ldr.BaseAddress = hModule;
510 wm->ldr.EntryPoint = (nt->OptionalHeader.AddressOfEntryPoint) ?
511 ((char *)hModule + nt->OptionalHeader.AddressOfEntryPoint) : 0;
512 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
514 wm->ldr.LoadCount = 0;
515 wm->ldr.TlsIndex = -1;
516 wm->ldr.SectionHandle = NULL;
517 wm->ldr.CheckSum = 0;
518 wm->ldr.TimeDateStamp = 0;
520 RtlCreateUnicodeString( &wm->ldr.FullDllName, filename );
521 if ((p = strrchrW( wm->ldr.FullDllName.Buffer, '\\' ))) p++;
522 else p = wm->ldr.FullDllName.Buffer;
523 RtlInitUnicodeString( &wm->ldr.BaseDllName, p );
525 /* this is a bit ugly, but we need to have app module first in LoadOrder
526 * list, But in wine, ntdll is loaded first, so by inserting DLLs at the tail
527 * and app module at the head we insure that order
529 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL))
531 /* is first loaded module a DLL or an exec ? */
532 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
533 if (mark->Flink == mark ||
534 (CONTAINING_RECORD(mark->Flink, LDR_MODULE, InLoadOrderModuleList)->Flags & LDR_IMAGE_IS_DLL))
536 InsertHeadList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
537 &wm->ldr.InLoadOrderModuleList);
541 else wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
544 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
545 &wm->ldr.InLoadOrderModuleList);
547 /* insert module in MemoryList, sorted in increasing base addresses */
548 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
549 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
551 if (CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList)->BaseAddress > wm->ldr.BaseAddress)
554 entry->Blink->Flink = &wm->ldr.InMemoryOrderModuleList;
555 wm->ldr.InMemoryOrderModuleList.Blink = entry->Blink;
556 wm->ldr.InMemoryOrderModuleList.Flink = entry;
557 entry->Blink = &wm->ldr.InMemoryOrderModuleList;
559 /* wait until init is called for inserting into this list */
560 wm->ldr.InInitializationOrderModuleList.Flink = NULL;
561 wm->ldr.InInitializationOrderModuleList.Blink = NULL;
566 /*************************************************************************
569 * Allocate the process-wide structure for module TLS storage.
571 static NTSTATUS alloc_process_tls(void)
573 PLIST_ENTRY mark, entry;
575 IMAGE_TLS_DIRECTORY *dir;
578 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
579 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
581 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
582 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
583 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
585 size = (dir->EndAddressOfRawData - dir->StartAddressOfRawData) + dir->SizeOfZeroFill;
587 tls_total_size += size;
590 if (!tls_module_count) return STATUS_SUCCESS;
592 TRACE( "count %u size %u\n", tls_module_count, tls_total_size );
594 tls_dirs = RtlAllocateHeap( ntdll_get_process_heap(), 0, tls_module_count * sizeof(*tls_dirs) );
595 if (!tls_dirs) return STATUS_NO_MEMORY;
597 for (i = 0, entry = mark->Flink; entry != mark; entry = entry->Flink)
599 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
600 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
601 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
604 *dir->AddressOfIndex = i;
606 mod->LoadCount = -1; /* can't unload it */
609 return STATUS_SUCCESS;
613 /*************************************************************************
616 * Allocate the per-thread structure for module TLS storage.
618 static NTSTATUS alloc_thread_tls(void)
624 if (!tls_module_count) return STATUS_SUCCESS;
626 if (!(pointers = RtlAllocateHeap( ntdll_get_process_heap(), 0,
627 tls_module_count * sizeof(*pointers) )))
628 return STATUS_NO_MEMORY;
630 if (!(data = RtlAllocateHeap( ntdll_get_process_heap(), 0, tls_total_size )))
632 RtlFreeHeap( ntdll_get_process_heap(), 0, pointers );
633 return STATUS_NO_MEMORY;
636 for (i = 0; i < tls_module_count; i++)
638 const IMAGE_TLS_DIRECTORY *dir = tls_dirs[i];
639 ULONG size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
641 TRACE( "thread %04lx idx %d: %ld/%ld bytes from %p to %p\n",
642 GetCurrentThreadId(), i, size, dir->SizeOfZeroFill,
643 (void *)dir->StartAddressOfRawData, data );
646 memcpy( data, (void *)dir->StartAddressOfRawData, size );
648 memset( data, 0, dir->SizeOfZeroFill );
649 data += dir->SizeOfZeroFill;
651 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
652 return STATUS_SUCCESS;
656 /*************************************************************************
659 static void call_tls_callbacks( HMODULE module, UINT reason )
661 const IMAGE_TLS_DIRECTORY *dir;
662 const PIMAGE_TLS_CALLBACK *callback;
665 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
666 if (!dir || !dir->AddressOfCallBacks) return;
668 for (callback = dir->AddressOfCallBacks; *callback; callback++)
671 DPRINTF("%04lx:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
672 GetCurrentThreadId(), *callback, module, reason_names[reason] );
673 (*callback)( module, reason, NULL );
675 DPRINTF("%04lx:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
676 GetCurrentThreadId(), *callback, module, reason_names[reason] );
681 /*************************************************************************
684 static BOOL MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
688 DLLENTRYPROC entry = wm->ldr.EntryPoint;
689 void *module = wm->ldr.BaseAddress;
691 /* Skip calls for modules loaded with special load flags */
693 if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return TRUE;
694 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.BaseAddress, reason );
695 if (!entry || !(wm->ldr.Flags & LDR_IMAGE_IS_DLL)) return TRUE;
699 size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
700 memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
701 mod_name[len / sizeof(WCHAR)] = 0;
702 DPRINTF("%04lx:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
703 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
704 reason_names[reason], lpReserved );
706 else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
707 reason_names[reason], lpReserved );
709 retv = entry( module, reason, lpReserved );
711 /* The state of the module list may have changed due to the call
712 to the dll. We cannot assume that this module has not been
715 DPRINTF("%04lx:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
716 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
717 reason_names[reason], lpReserved, retv );
718 else TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
724 /*************************************************************************
727 * Send the process attach notification to all DLLs the given module
728 * depends on (recursively). This is somewhat complicated due to the fact that
730 * - we have to respect the module dependencies, i.e. modules implicitly
731 * referenced by another module have to be initialized before the module
732 * itself can be initialized
734 * - the initialization routine of a DLL can itself call LoadLibrary,
735 * thereby introducing a whole new set of dependencies (even involving
736 * the 'old' modules) at any time during the whole process
738 * (Note that this routine can be recursively entered not only directly
739 * from itself, but also via LoadLibrary from one of the called initialization
742 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
743 * the process *detach* notifications to be sent in the correct order.
744 * This must not only take into account module dependencies, but also
745 * 'hidden' dependencies created by modules calling LoadLibrary in their
746 * attach notification routine.
748 * The strategy is rather simple: we move a WINE_MODREF to the head of the
749 * list after the attach notification has returned. This implies that the
750 * detach notifications are called in the reverse of the sequence the attach
751 * notifications *returned*.
753 * The loader_section must be locked while calling this function.
755 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
757 NTSTATUS status = STATUS_SUCCESS;
760 /* prevent infinite recursion in case of cyclical dependencies */
761 if ( ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
762 || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
765 TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
767 /* Tag current MODREF to prevent recursive loop */
768 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
770 /* Recursively attach all DLLs this one depends on */
771 for ( i = 0; i < wm->nDeps; i++ )
773 if (!wm->deps[i]) continue;
774 if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
777 /* Call DLL entry point */
778 if (status == STATUS_SUCCESS)
780 WINE_MODREF *prev = current_modref;
782 if (MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved ))
783 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
785 status = STATUS_DLL_INIT_FAILED;
786 current_modref = prev;
789 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
790 &wm->ldr.InInitializationOrderModuleList);
792 /* Remove recursion flag */
793 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
795 TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
799 /*************************************************************************
802 * Send DLL process detach notifications. See the comment about calling
803 * sequence at process_attach. Unless the bForceDetach flag
804 * is set, only DLLs with zero refcount are notified.
806 static void process_detach( BOOL bForceDetach, LPVOID lpReserved )
808 PLIST_ENTRY mark, entry;
811 RtlEnterCriticalSection( &loader_section );
812 if (bForceDetach) process_detaching = 1;
813 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
816 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
818 mod = CONTAINING_RECORD(entry, LDR_MODULE,
819 InInitializationOrderModuleList);
820 /* Check whether to detach this DLL */
821 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
823 if ( mod->LoadCount && !bForceDetach )
826 /* Call detach notification */
827 mod->Flags &= ~LDR_PROCESS_ATTACHED;
828 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
829 DLL_PROCESS_DETACH, lpReserved );
831 /* Restart at head of WINE_MODREF list, as entries might have
832 been added and/or removed while performing the call ... */
835 } while (entry != mark);
837 RtlLeaveCriticalSection( &loader_section );
840 /*************************************************************************
841 * MODULE_DllThreadAttach
843 * Send DLL thread attach notifications. These are sent in the
844 * reverse sequence of process detach notification.
847 NTSTATUS MODULE_DllThreadAttach( LPVOID lpReserved )
849 PLIST_ENTRY mark, entry;
853 /* don't do any attach calls if process is exiting */
854 if (process_detaching) return STATUS_SUCCESS;
855 /* FIXME: there is still a race here */
857 RtlEnterCriticalSection( &loader_section );
859 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto done;
861 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
862 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
864 mod = CONTAINING_RECORD(entry, LDR_MODULE,
865 InInitializationOrderModuleList);
866 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
868 if ( mod->Flags & LDR_NO_DLL_CALLS )
871 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
872 DLL_THREAD_ATTACH, lpReserved );
876 RtlLeaveCriticalSection( &loader_section );
880 /******************************************************************
881 * LdrDisableThreadCalloutsForDll (NTDLL.@)
884 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
887 NTSTATUS ret = STATUS_SUCCESS;
889 RtlEnterCriticalSection( &loader_section );
891 wm = get_modref( hModule );
892 if (!wm || wm->ldr.TlsIndex != -1)
893 ret = STATUS_DLL_NOT_FOUND;
895 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
897 RtlLeaveCriticalSection( &loader_section );
902 /******************************************************************
903 * LdrFindEntryForAddress (NTDLL.@)
905 * The loader_section must be locked while calling this function
907 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
909 PLIST_ENTRY mark, entry;
912 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
913 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
915 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
916 if ((const void *)mod->BaseAddress <= addr &&
917 (char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
920 return STATUS_SUCCESS;
922 if ((const void *)mod->BaseAddress > addr) break;
924 return STATUS_NO_MORE_ENTRIES;
927 /******************************************************************
928 * LdrLockLoaderLock (NTDLL.@)
930 * Note: flags are not implemented.
931 * Flag 0x01 is used to raise exceptions on errors.
932 * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
934 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG *magic )
936 if (flags) FIXME( "flags %lx not supported\n", flags );
938 if (result) *result = 1;
939 if (!magic) return STATUS_INVALID_PARAMETER_3;
940 RtlEnterCriticalSection( &loader_section );
941 *magic = GetCurrentThreadId();
942 return STATUS_SUCCESS;
946 /******************************************************************
947 * LdrUnlockLoaderUnlock (NTDLL.@)
949 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG magic )
953 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
954 RtlLeaveCriticalSection( &loader_section );
956 return STATUS_SUCCESS;
960 /******************************************************************
961 * LdrGetDllHandle (NTDLL.@)
963 NTSTATUS WINAPI LdrGetDllHandle(ULONG x, ULONG y, const UNICODE_STRING *name, HMODULE *base)
965 NTSTATUS status = STATUS_DLL_NOT_FOUND;
966 WCHAR dllname[MAX_PATH+4], *p;
968 PLIST_ENTRY mark, entry;
971 if (x != 0 || y != 0)
972 FIXME("Unknown behavior, please report\n");
974 /* Append .DLL to name if no extension present */
975 if (!(p = strrchrW( name->Buffer, '.')) || strchrW( p, '/' ) || strchrW( p, '\\'))
977 if (name->Length >= MAX_PATH) return STATUS_NAME_TOO_LONG;
978 strcpyW( dllname, name->Buffer );
979 strcatW( dllname, dllW );
980 RtlInitUnicodeString( &str, dllname );
984 RtlEnterCriticalSection( &loader_section );
988 if (RtlEqualUnicodeString( name, &cached_modref->ldr.FullDllName, TRUE ) ||
989 RtlEqualUnicodeString( name, &cached_modref->ldr.BaseDllName, TRUE ))
991 *base = cached_modref->ldr.BaseAddress;
992 status = STATUS_SUCCESS;
997 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
998 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1000 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1002 if (RtlEqualUnicodeString( name, &mod->FullDllName, TRUE ) ||
1003 RtlEqualUnicodeString( name, &mod->BaseDllName, TRUE ))
1005 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1006 *base = mod->BaseAddress;
1007 status = STATUS_SUCCESS;
1012 RtlLeaveCriticalSection( &loader_section );
1013 TRACE("%lx %lx %s -> %p\n", x, y, debugstr_us(name), status ? NULL : *base);
1018 /******************************************************************
1019 * LdrGetProcedureAddress (NTDLL.@)
1021 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1022 ULONG ord, PVOID *address)
1024 IMAGE_EXPORT_DIRECTORY *exports;
1026 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1028 RtlEnterCriticalSection( &loader_section );
1030 if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1031 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1033 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1 )
1034 : find_ordinal_export( module, exports, exp_size, ord - exports->Base );
1038 ret = STATUS_SUCCESS;
1043 /* check if the module itself is invalid to return the proper error */
1044 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1047 RtlLeaveCriticalSection( &loader_section );
1052 /***********************************************************************
1053 * load_builtin_callback
1055 * Load a library in memory; callback function for wine_dll_register
1057 static void load_builtin_callback( void *module, const char *filename )
1059 static const WCHAR emptyW[1];
1061 IMAGE_NT_HEADERS *nt;
1063 WCHAR *fullname, *p;
1064 const WCHAR *load_path;
1068 ERR("could not map image for %s\n", filename ? filename : "main exe" );
1071 if (!(nt = RtlImageNtHeader( module )))
1073 ERR( "bad module for %s\n", filename ? filename : "main exe" );
1074 builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1077 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL))
1079 /* if we already have an executable, ignore this one */
1080 if (!NtCurrentTeb()->Peb->ImageBaseAddress)
1081 NtCurrentTeb()->Peb->ImageBaseAddress = module;
1082 return; /* don't create the modref here, will be done later on */
1085 /* create the MODREF */
1087 if (!(fullname = RtlAllocateHeap( GetProcessHeap(), 0,
1088 system_dir.MaximumLength + (strlen(filename) + 1) * sizeof(WCHAR) )))
1090 ERR( "can't load %s\n", filename );
1091 builtin_load_info->status = STATUS_NO_MEMORY;
1094 memcpy( fullname, system_dir.Buffer, system_dir.Length );
1095 p = fullname + system_dir.Length / sizeof(WCHAR);
1096 if (p > fullname && p[-1] != '\\') *p++ = '\\';
1097 ascii_to_unicode( p, filename, strlen(filename) + 1 );
1099 wm = alloc_module( module, fullname );
1100 RtlFreeHeap( GetProcessHeap(), 0, fullname );
1103 ERR( "can't load %s\n", filename );
1104 builtin_load_info->status = STATUS_NO_MEMORY;
1107 wm->ldr.Flags |= LDR_WINE_INTERNAL;
1108 NtAllocateVirtualMemory( GetCurrentProcess(), &addr, module, &nt->OptionalHeader.SizeOfImage,
1109 MEM_SYSTEM | MEM_IMAGE, PAGE_EXECUTE_WRITECOPY );
1113 load_path = builtin_load_info->load_path;
1114 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1115 if (!load_path) load_path = emptyW;
1116 if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1118 /* the module has only be inserted in the load & memory order lists */
1119 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1120 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1121 /* FIXME: free the modref */
1122 builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1125 builtin_load_info->wm = wm;
1126 TRACE( "loaded %s %p %p\n", filename, wm, module );
1128 /* send the DLL load event */
1130 SERVER_START_REQ( load_dll )
1134 req->size = nt->OptionalHeader.SizeOfImage;
1135 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1136 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1137 req->name = &wm->ldr.FullDllName.Buffer;
1138 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1139 wine_server_call( req );
1143 /* setup relay debugging entry points */
1144 if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1148 /******************************************************************************
1149 * load_native_dll (internal)
1151 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1152 DWORD flags, WINE_MODREF** pwm )
1156 OBJECT_ATTRIBUTES attr;
1158 IMAGE_NT_HEADERS *nt;
1163 TRACE( "loading %s\n", debugstr_w(name) );
1165 attr.Length = sizeof(attr);
1166 attr.RootDirectory = 0;
1167 attr.ObjectName = NULL;
1168 attr.Attributes = 0;
1169 attr.SecurityDescriptor = NULL;
1170 attr.SecurityQualityOfService = NULL;
1173 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1174 &attr, &size, 0, SEC_IMAGE, file );
1175 if (status != STATUS_SUCCESS) return status;
1178 status = NtMapViewOfSection( mapping, GetCurrentProcess(),
1179 &module, 0, 0, &size, &len, ViewShare, 0, PAGE_READONLY );
1181 if (status != STATUS_SUCCESS) return status;
1183 /* create the MODREF */
1185 if (!(wm = alloc_module( module, name ))) return STATUS_NO_MEMORY;
1189 if (!(flags & DONT_RESOLVE_DLL_REFERENCES))
1191 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1193 /* the module has only be inserted in the load & memory order lists */
1194 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1195 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1197 /* FIXME: there are several more dangling references
1198 * left. Including dlls loaded by this dll before the
1199 * failed one. Unrolling is rather difficult with the
1200 * current structure and we can leave them lying
1201 * around with no problems, so we don't care.
1202 * As these might reference our wm, we don't free it.
1207 else wm->ldr.Flags |= LDR_DONT_RESOLVE_REFS;
1209 /* send DLL load event */
1211 nt = RtlImageNtHeader( module );
1213 SERVER_START_REQ( load_dll )
1217 req->size = nt->OptionalHeader.SizeOfImage;
1218 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1219 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1220 req->name = &wm->ldr.FullDllName.Buffer;
1221 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1222 wine_server_call( req );
1226 if (TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1229 return STATUS_SUCCESS;
1233 /***********************************************************************
1236 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, DWORD flags, WINE_MODREF** pwm )
1238 char error[256], dllname[MAX_PATH];
1240 const WCHAR *name, *p;
1243 struct builtin_load_info info, *prev_info;
1245 /* Fix the name in case we have a full path and extension */
1247 if ((p = strrchrW( name, '\\' ))) name = p + 1;
1248 if ((p = strrchrW( name, '/' ))) name = p + 1;
1250 /* we don't want to depend on the current codepage here */
1251 len = strlenW( name ) + 1;
1252 if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1253 for (i = 0; i < len; i++)
1255 if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1256 dllname[i] = (char)name[i];
1257 if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1260 /* load_library will modify info.status. Note also that load_library can be
1261 * called several times, if the .so file we're loading has dependencies.
1262 * info.status will gather all the errors we may get while loading all these
1265 info.load_path = load_path;
1266 info.status = STATUS_SUCCESS;
1268 prev_info = builtin_load_info;
1269 builtin_load_info = &info;
1270 handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1271 builtin_load_info = prev_info;
1277 /* The file does not exist -> WARN() */
1278 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
1279 return STATUS_DLL_NOT_FOUND;
1281 /* ERR() for all other errors (missing functions, ...) */
1282 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
1283 return STATUS_PROCEDURE_NOT_FOUND;
1285 if (info.status != STATUS_SUCCESS) return info.status;
1289 /* The constructor wasn't called, this means the .so is already
1290 * loaded under a different name. We can't support multiple names
1291 * for the same module, so return an error. */
1292 return STATUS_INVALID_IMAGE_FORMAT;
1295 info.wm->ldr.SectionHandle = handle;
1296 if (strcmpiW( info.wm->ldr.BaseDllName.Buffer, name ))
1298 ERR( "loaded .so for %s but got %s instead - probably 16-bit dll\n",
1299 debugstr_w(name), debugstr_w(info.wm->ldr.BaseDllName.Buffer) );
1300 /* wine_dll_unload( handle );*/
1301 return STATUS_INVALID_IMAGE_FORMAT;
1304 return STATUS_SUCCESS;
1308 /***********************************************************************
1311 * Find the file (or already loaded module) for a given dll name.
1313 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
1314 WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
1316 WCHAR *file_part, *ext;
1319 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
1321 /* we need to search for it */
1322 /* but first append .dll because RtlDosSearchPath extension handling is broken */
1323 if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
1327 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
1328 (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
1329 return STATUS_NO_MEMORY;
1330 strcpyW( dllname, libname );
1331 strcatW( dllname, dllW );
1332 len = RtlDosSearchPath_U( load_path, dllname, NULL, *size, filename, &file_part );
1333 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1335 else len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
1341 *size = len + sizeof(WCHAR);
1342 return STATUS_BUFFER_TOO_SMALL;
1344 if ((*pwm = find_fullname_module( filename )) != NULL) return STATUS_SUCCESS;
1346 /* check for already loaded module in a different path */
1347 if (!contains_path( libname ))
1349 if ((*pwm = find_basename_module( file_part )) != NULL) return STATUS_SUCCESS;
1351 *handle = pCreateFileW( filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0 );
1352 return STATUS_SUCCESS;
1357 if (!contains_path( libname ))
1359 /* if libname doesn't contain a path at all, we simply return the name as is,
1360 * to be loaded as builtin */
1361 len = strlenW(libname) * sizeof(WCHAR);
1362 if (len >= *size) goto overflow;
1363 strcpyW( filename, libname );
1364 if (!strchrW( filename, '.' ))
1366 len += sizeof(dllW) - sizeof(WCHAR);
1367 if (len >= *size) goto overflow;
1368 strcatW( filename, dllW );
1370 *pwm = find_basename_module( filename );
1371 return STATUS_SUCCESS;
1375 /* absolute path name, or relative path name but not found above */
1377 len = RtlGetFullPathName_U( libname, *size, filename, &file_part );
1378 if (len >= *size) goto overflow;
1379 if (file_part && !strchrW( file_part, '.' ))
1381 len += sizeof(dllW) - sizeof(WCHAR);
1382 if (len >= *size) goto overflow;
1383 strcatW( file_part, dllW );
1385 if ((*pwm = find_fullname_module( filename )) != NULL) return STATUS_SUCCESS;
1386 *handle = pCreateFileW( filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0 );
1387 return STATUS_SUCCESS;
1390 *size = len + sizeof(WCHAR);
1391 return STATUS_BUFFER_TOO_SMALL;
1395 /***********************************************************************
1396 * load_dll (internal)
1398 * Load a PE style module according to the load order.
1399 * The loader_section must be locked while calling this function.
1401 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
1404 enum loadorder_type loadorder[LOADORDER_NTYPES];
1408 const char *filetype = "";
1409 WINE_MODREF *main_exe;
1410 HANDLE handle = INVALID_HANDLE_VALUE;
1413 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
1416 size = sizeof(buffer);
1419 nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
1420 if (nts == STATUS_SUCCESS) break;
1421 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1422 if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
1423 /* grow the buffer and retry */
1424 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
1427 if (*pwm) /* found already loaded module */
1429 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
1431 if (((*pwm)->ldr.Flags & LDR_DONT_RESOLVE_REFS) &&
1432 !(flags & DONT_RESOLVE_DLL_REFERENCES))
1434 (*pwm)->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
1435 fixup_imports( *pwm, load_path );
1437 TRACE("Found loaded module %s for %s at %p, count=%d\n",
1438 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
1439 (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
1440 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1441 return STATUS_SUCCESS;
1444 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
1445 MODULE_GetLoadOrderW( loadorder, main_exe->ldr.BaseDllName.Buffer, filename, TRUE);
1447 nts = STATUS_DLL_NOT_FOUND;
1448 for (i = 0; i < LOADORDER_NTYPES; i++)
1450 if (loadorder[i] == LOADORDER_INVALID) break;
1452 switch (loadorder[i])
1455 TRACE("Trying native dll %s\n", debugstr_w(filename));
1456 if (handle == INVALID_HANDLE_VALUE) continue; /* it cannot possibly be loaded */
1457 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1458 filetype = "native";
1461 TRACE("Trying built-in %s\n", debugstr_w(filename));
1462 nts = load_builtin_dll( load_path, filename, flags, pwm );
1463 filetype = "builtin";
1466 nts = STATUS_INTERNAL_ERROR;
1470 if (nts == STATUS_SUCCESS)
1472 /* Initialize DLL just loaded */
1473 TRACE("Loaded module %s (%s) at %p\n",
1474 debugstr_w(filename), filetype, (*pwm)->ldr.BaseAddress);
1475 if (!TRACE_ON(module))
1476 TRACE_(loaddll)("Loaded module %s : %s\n", debugstr_w(filename), filetype);
1477 /* Set the ldr.LoadCount here so that an attach failure will */
1478 /* decrement the dependencies through the MODULE_FreeLibrary call. */
1479 (*pwm)->ldr.LoadCount = 1;
1480 if (handle != INVALID_HANDLE_VALUE) NtClose( handle );
1481 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1484 if (nts != STATUS_DLL_NOT_FOUND) break;
1487 WARN("Failed to load module %s; status=%lx\n", debugstr_w(libname), nts);
1488 if (handle != INVALID_HANDLE_VALUE) NtClose( handle );
1489 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1493 /******************************************************************
1494 * LdrLoadDll (NTDLL.@)
1496 NTSTATUS WINAPI LdrLoadDll(LPCWSTR path_name, DWORD flags,
1497 const UNICODE_STRING *libname, HMODULE* hModule)
1502 RtlEnterCriticalSection( &loader_section );
1504 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1505 nts = load_dll( path_name, libname->Buffer, flags, &wm );
1507 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
1509 nts = process_attach( wm, NULL );
1510 if (nts != STATUS_SUCCESS)
1512 WARN("Attach failed for module %s\n", debugstr_w(libname->Buffer));
1513 LdrUnloadDll(wm->ldr.BaseAddress);
1517 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
1519 RtlLeaveCriticalSection( &loader_section );
1523 /******************************************************************
1524 * LdrQueryProcessModuleInformation
1527 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
1528 ULONG buf_size, ULONG* req_size)
1530 SYSTEM_MODULE* sm = &smi->Modules[0];
1531 ULONG size = sizeof(ULONG);
1532 NTSTATUS nts = STATUS_SUCCESS;
1535 PLIST_ENTRY mark, entry;
1538 smi->ModulesCount = 0;
1540 RtlEnterCriticalSection( &loader_section );
1541 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1542 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1544 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1545 size += sizeof(*sm);
1546 if (size <= buf_size)
1548 sm->Reserved1 = 0; /* FIXME */
1549 sm->Reserved2 = 0; /* FIXME */
1550 sm->ImageBaseAddress = mod->BaseAddress;
1551 sm->ImageSize = mod->SizeOfImage;
1552 sm->Flags = mod->Flags;
1553 sm->Id = 0; /* FIXME */
1554 sm->Rank = 0; /* FIXME */
1555 sm->Unknown = 0; /* FIXME */
1557 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
1558 str.Buffer = sm->Name;
1559 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
1560 ptr = strrchr(sm->Name, '\\');
1561 sm->NameOffset = (ptr != NULL) ? (ptr - (char*)sm->Name + 1) : 0;
1563 smi->ModulesCount++;
1566 else nts = STATUS_INFO_LENGTH_MISMATCH;
1568 RtlLeaveCriticalSection( &loader_section );
1570 if (req_size) *req_size = size;
1575 /******************************************************************
1576 * LdrShutdownProcess (NTDLL.@)
1579 void WINAPI LdrShutdownProcess(void)
1582 process_detach( TRUE, (LPVOID)1 );
1585 /******************************************************************
1586 * LdrShutdownThread (NTDLL.@)
1589 void WINAPI LdrShutdownThread(void)
1591 PLIST_ENTRY mark, entry;
1596 /* don't do any detach calls if process is exiting */
1597 if (process_detaching) return;
1598 /* FIXME: there is still a race here */
1600 RtlEnterCriticalSection( &loader_section );
1602 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1603 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1605 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1606 InInitializationOrderModuleList);
1607 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1609 if ( mod->Flags & LDR_NO_DLL_CALLS )
1612 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1613 DLL_THREAD_DETACH, NULL );
1616 RtlLeaveCriticalSection( &loader_section );
1619 /***********************************************************************
1620 * MODULE_FlushModrefs
1622 * Remove all unused modrefs and call the internal unloading routines
1623 * for the library type.
1625 * The loader_section must be locked while calling this function.
1627 static void MODULE_FlushModrefs(void)
1629 PLIST_ENTRY mark, entry, prev;
1633 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1634 for (entry = mark->Blink; entry != mark; entry = prev)
1636 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1637 InInitializationOrderModuleList);
1638 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1640 prev = entry->Blink;
1641 if (mod->LoadCount) continue;
1643 RemoveEntryList(&mod->InLoadOrderModuleList);
1644 RemoveEntryList(&mod->InMemoryOrderModuleList);
1645 RemoveEntryList(&mod->InInitializationOrderModuleList);
1647 TRACE(" unloading %s\n", debugstr_w(mod->FullDllName.Buffer));
1648 if (!TRACE_ON(module))
1649 TRACE_(loaddll)("Unloaded module %s : %s\n",
1650 debugstr_w(mod->FullDllName.Buffer),
1651 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
1653 SERVER_START_REQ( unload_dll )
1655 req->base = mod->BaseAddress;
1656 wine_server_call( req );
1660 if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
1661 NtUnmapViewOfSection( GetCurrentProcess(), mod->BaseAddress );
1662 if (cached_modref == wm) cached_modref = NULL;
1663 RtlFreeUnicodeString( &mod->FullDllName );
1664 RtlFreeHeap( ntdll_get_process_heap(), 0, wm->deps );
1665 RtlFreeHeap( ntdll_get_process_heap(), 0, wm );
1669 /***********************************************************************
1670 * MODULE_DecRefCount
1672 * The loader_section must be locked while calling this function.
1674 static void MODULE_DecRefCount( WINE_MODREF *wm )
1678 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
1681 if ( wm->ldr.LoadCount <= 0 )
1684 --wm->ldr.LoadCount;
1685 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
1687 if ( wm->ldr.LoadCount == 0 )
1689 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
1691 for ( i = 0; i < wm->nDeps; i++ )
1693 MODULE_DecRefCount( wm->deps[i] );
1695 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
1699 /******************************************************************
1700 * LdrUnloadDll (NTDLL.@)
1704 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
1706 NTSTATUS retv = STATUS_SUCCESS;
1708 TRACE("(%p)\n", hModule);
1710 RtlEnterCriticalSection( &loader_section );
1712 /* if we're stopping the whole process (and forcing the removal of all
1713 * DLLs) the library will be freed anyway
1715 if (!process_detaching)
1720 if ((wm = get_modref( hModule )) != NULL)
1722 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
1724 /* Recursively decrement reference counts */
1725 MODULE_DecRefCount( wm );
1727 /* Call process detach notifications */
1728 if ( free_lib_count <= 1 )
1730 process_detach( FALSE, NULL );
1731 MODULE_FlushModrefs();
1737 retv = STATUS_DLL_NOT_FOUND;
1742 RtlLeaveCriticalSection( &loader_section );
1747 /***********************************************************************
1748 * RtlImageNtHeader (NTDLL.@)
1750 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
1752 IMAGE_NT_HEADERS *ret;
1756 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
1759 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
1761 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
1762 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
1765 __EXCEPT(page_fault)
1774 /******************************************************************
1775 * LdrInitializeThunk (NTDLL.@)
1777 * FIXME: the arguments are not correct, main_file and CreateFileW_ptr are Wine inventions.
1779 void WINAPI LdrInitializeThunk( HANDLE main_file, void *CreateFileW_ptr, ULONG unknown3, ULONG unknown4 )
1784 PEB *peb = NtCurrentTeb()->Peb;
1785 UNICODE_STRING *main_exe_name = &peb->ProcessParameters->ImagePathName;
1786 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
1788 pCreateFileW = CreateFileW_ptr;
1789 if (!MODULE_GetSystemDirectory( &system_dir ))
1791 ERR( "Couldn't get system dir\n");
1795 /* allocate the modref for the main exe */
1796 if (!(wm = alloc_module( peb->ImageBaseAddress, main_exe_name->Buffer )))
1798 status = STATUS_NO_MEMORY;
1801 wm->ldr.LoadCount = -1; /* can't unload main exe */
1803 /* Install signal handlers; this cannot be done before, since we cannot
1804 * send exceptions to the debugger before the create process event that
1805 * is sent by REQ_INIT_PROCESS_DONE.
1806 * We do need the handlers in place by the time the request is over, so
1807 * we set them up here. If we segfault between here and the server call
1808 * something is very wrong... */
1809 if (!SIGNAL_Init()) exit(1);
1811 /* Signal the parent process to continue */
1812 SERVER_START_REQ( init_process_done )
1814 req->module = peb->ImageBaseAddress;
1815 req->module_size = wm->ldr.SizeOfImage;
1816 req->entry = wm->ldr.EntryPoint;
1817 /* API requires a double indirection */
1818 req->name = &main_exe_name->Buffer;
1819 req->exe_file = main_file;
1820 req->gui = (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_WINDOWS_CUI);
1821 wine_server_add_data( req, main_exe_name->Buffer, main_exe_name->Length );
1822 wine_server_call( req );
1826 if (main_file) NtClose( main_file ); /* we no longer need it */
1828 if (TRACE_ON(relay) || TRACE_ON(snoop))
1830 RELAY_InitDebugLists();
1832 if (TRACE_ON(relay)) /* setup relay for already loaded dlls */
1834 LIST_ENTRY *entry, *mark = &peb->LdrData->InLoadOrderModuleList;
1835 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1837 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1838 if (mod->Flags & LDR_WINE_INTERNAL) RELAY_SetupDLL( mod->BaseAddress );
1843 RtlEnterCriticalSection( &loader_section );
1845 load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1846 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
1847 if ((status = alloc_process_tls()) != STATUS_SUCCESS) goto error;
1848 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto error;
1849 if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS) goto error;
1851 RtlLeaveCriticalSection( &loader_section );
1855 ERR( "Main exe initialization failed, status %lx\n", status );
1860 /***********************************************************************
1861 * RtlImageDirectoryEntryToData (NTDLL.@)
1863 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
1865 const IMAGE_NT_HEADERS *nt;
1868 if ((ULONG_PTR)module & 1) /* mapped as data file */
1870 module = (HMODULE)((ULONG_PTR)module & ~1);
1873 if (!(nt = RtlImageNtHeader( module ))) return NULL;
1874 if (dir >= nt->OptionalHeader.NumberOfRvaAndSizes) return NULL;
1875 if (!(addr = nt->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
1876 *size = nt->OptionalHeader.DataDirectory[dir].Size;
1877 if (image || addr < nt->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
1879 /* not mapped as image, need to find the section containing the virtual address */
1880 return RtlImageRvaToVa( nt, module, addr, NULL );
1884 /***********************************************************************
1885 * RtlImageRvaToSection (NTDLL.@)
1887 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
1888 HMODULE module, DWORD rva )
1891 IMAGE_SECTION_HEADER *sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader +
1892 nt->FileHeader.SizeOfOptionalHeader);
1893 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1895 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
1902 /***********************************************************************
1903 * RtlImageRvaToVa (NTDLL.@)
1905 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
1906 DWORD rva, IMAGE_SECTION_HEADER **section )
1908 IMAGE_SECTION_HEADER *sec;
1910 if (section && *section) /* try this section first */
1913 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
1916 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
1918 if (section) *section = sec;
1919 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
1923 /***********************************************************************
1924 * __wine_process_init
1926 void __wine_process_init( int argc, char *argv[] )
1928 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
1932 ANSI_STRING func_name;
1933 void (* DECLSPEC_NORETURN init_func)();
1937 /* setup the load callback and create ntdll modref */
1938 wine_dll_set_callback( load_builtin_callback );
1940 if ((status = load_builtin_dll( NULL, kernel32W, 0, &wm )) != STATUS_SUCCESS)
1942 MESSAGE( "wine: could not load kernel32.dll, status %lx\n", status );
1945 RtlInitAnsiString( &func_name, "__wine_kernel_init" );
1946 if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
1947 0, (void **)&init_func )) != STATUS_SUCCESS)
1949 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %lx\n", status );