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
33 #include "wine/exception.h"
35 #include "wine/unicode.h"
36 #include "wine/debug.h"
37 #include "wine/server.h"
38 #include "ntdll_misc.h"
40 WINE_DEFAULT_DEBUG_CHANNEL(module
);
41 WINE_DECLARE_DEBUG_CHANNEL(relay
);
42 WINE_DECLARE_DEBUG_CHANNEL(snoop
);
43 WINE_DECLARE_DEBUG_CHANNEL(loaddll
);
45 typedef DWORD (CALLBACK
*DLLENTRYPROC
)(HMODULE
,DWORD
,LPVOID
);
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 const WCHAR dllW
[] = {'.','d','l','l',0};
68 /* internal representation of 32bit modules. per process. */
69 typedef struct _wine_modref
73 struct _wine_modref
**deps
;
76 /* info about the current builtin dll load */
77 /* used to keep track of things across the register_dll constructor call */
78 struct builtin_load_info
80 const WCHAR
*load_path
;
85 static struct builtin_load_info
*builtin_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 if (len
* sizeof(WCHAR
) <= sizeof(buffer
))
342 ascii_to_unicode( buffer
, name
, len
);
343 status
= load_dll( load_path
, buffer
, 0, &wmImp
);
345 else /* need to allocate a larger buffer */
347 WCHAR
*ptr
= RtlAllocateHeap( GetProcessHeap(), 0, len
* sizeof(WCHAR
) );
348 if (!ptr
) return NULL
;
349 ascii_to_unicode( ptr
, name
, len
);
350 status
= load_dll( load_path
, ptr
, 0, &wmImp
);
351 RtlFreeHeap( GetProcessHeap(), 0, ptr
);
356 if (status
== STATUS_DLL_NOT_FOUND
)
357 ERR("Module (file) %s (which is needed by %s) not found\n",
358 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
));
360 ERR("Loading module (file) %s (which is needed by %s) failed (error %lx).\n",
361 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
), status
);
365 imp_mod
= wmImp
->ldr
.BaseAddress
;
366 if (!(exports
= RtlImageDirectoryEntryToData( imp_mod
, TRUE
,
367 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
370 thunk_list
= get_rva( module
, (DWORD
)descr
->FirstThunk
);
371 if (descr
->u
.OriginalFirstThunk
)
372 import_list
= get_rva( module
, (DWORD
)descr
->u
.OriginalFirstThunk
);
374 import_list
= thunk_list
;
376 while (import_list
->u1
.Ordinal
)
378 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
380 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
382 TRACE("--- Ordinal %s,%d\n", name
, ordinal
);
383 thunk_list
->u1
.Function
= (PDWORD
)find_ordinal_export( imp_mod
, exports
, exp_size
,
384 ordinal
- exports
->Base
);
385 if (!thunk_list
->u1
.Function
)
387 ERR("No implementation for %s.%d imported from %s, setting to 0xdeadbeef\n",
388 name
, ordinal
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
) );
389 thunk_list
->u1
.Function
= (PDWORD
)0xdeadbeef;
392 else /* import by name */
394 IMAGE_IMPORT_BY_NAME
*pe_name
;
395 pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
396 TRACE("--- %s %s.%d\n", pe_name
->Name
, name
, pe_name
->Hint
);
397 thunk_list
->u1
.Function
= (PDWORD
)find_named_export( imp_mod
, exports
, exp_size
,
398 pe_name
->Name
, pe_name
->Hint
);
399 if (!thunk_list
->u1
.Function
)
401 ERR("No implementation for %s.%s imported from %s, setting to 0xdeadbeef\n",
402 name
, pe_name
->Name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
) );
403 thunk_list
->u1
.Function
= (PDWORD
)0xdeadbeef;
413 /****************************************************************
416 * Fixup all imports of a given module.
417 * The loader_section must be locked while calling this function.
419 static NTSTATUS
fixup_imports( WINE_MODREF
*wm
, LPCWSTR load_path
)
422 IMAGE_IMPORT_DESCRIPTOR
*imports
;
426 if (!(imports
= RtlImageDirectoryEntryToData( wm
->ldr
.BaseAddress
, TRUE
,
427 IMAGE_DIRECTORY_ENTRY_IMPORT
, &size
)))
428 return STATUS_SUCCESS
;
430 nb_imports
= size
/ sizeof(*imports
);
431 for (i
= 0; i
< nb_imports
; i
++)
433 if (!imports
[i
].Name
)
439 if (!nb_imports
) return STATUS_SUCCESS
; /* no imports */
441 /* Allocate module dependency list */
442 wm
->nDeps
= nb_imports
;
443 wm
->deps
= RtlAllocateHeap( ntdll_get_process_heap(), 0, nb_imports
*sizeof(WINE_MODREF
*) );
445 /* load the imported modules. They are automatically
446 * added to the modref list of the process.
448 prev
= current_modref
;
450 for (i
= 0; i
< nb_imports
; i
++)
452 if (!(wm
->deps
[i
] = import_dll( wm
->ldr
.BaseAddress
, &imports
[i
], load_path
))) break;
454 current_modref
= prev
;
455 if (i
< nb_imports
) return STATUS_DLL_NOT_FOUND
;
456 return STATUS_SUCCESS
;
460 /*************************************************************************
463 * Allocate a WINE_MODREF structure and add it to the process list
464 * The loader_section must be locked while calling this function.
466 static WINE_MODREF
*alloc_module( HMODULE hModule
, LPCWSTR filename
)
470 IMAGE_NT_HEADERS
*nt
= RtlImageNtHeader(hModule
);
471 PLIST_ENTRY entry
, mark
;
472 BOOLEAN linked
= FALSE
;
475 RtlUnicodeToMultiByteSize( &len
, filename
, (strlenW(filename
) + 1) * sizeof(WCHAR
) );
476 if (!(wm
= RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm
) + len
)))
482 wm
->ldr
.BaseAddress
= hModule
;
483 wm
->ldr
.EntryPoint
= (nt
->OptionalHeader
.AddressOfEntryPoint
) ?
484 ((char *)hModule
+ nt
->OptionalHeader
.AddressOfEntryPoint
) : 0;
485 wm
->ldr
.SizeOfImage
= nt
->OptionalHeader
.SizeOfImage
;
487 wm
->ldr
.LoadCount
= 0;
488 wm
->ldr
.TlsIndex
= -1;
489 wm
->ldr
.SectionHandle
= NULL
;
490 wm
->ldr
.CheckSum
= 0;
491 wm
->ldr
.TimeDateStamp
= 0;
493 RtlCreateUnicodeString( &wm
->ldr
.FullDllName
, filename
);
494 if ((p
= strrchrW( wm
->ldr
.FullDllName
.Buffer
, '\\' ))) p
++;
495 else p
= wm
->ldr
.FullDllName
.Buffer
;
496 RtlInitUnicodeString( &wm
->ldr
.BaseDllName
, p
);
498 /* this is a bit ugly, but we need to have app module first in LoadOrder
499 * list, But in wine, ntdll is loaded first, so by inserting DLLs at the tail
500 * and app module at the head we insure that order
502 if (!(nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
))
504 /* is first loaded module a DLL or an exec ? */
505 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
506 if (mark
->Flink
== mark
||
507 (CONTAINING_RECORD(mark
->Flink
, LDR_MODULE
, InLoadOrderModuleList
)->Flags
& LDR_IMAGE_IS_DLL
))
509 InsertHeadList(&NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
,
510 &wm
->ldr
.InLoadOrderModuleList
);
514 else wm
->ldr
.Flags
|= LDR_IMAGE_IS_DLL
;
517 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
,
518 &wm
->ldr
.InLoadOrderModuleList
);
520 /* insert module in MemoryList, sorted in increasing base addresses */
521 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
522 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
524 if (CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
)->BaseAddress
> wm
->ldr
.BaseAddress
)
527 entry
->Blink
->Flink
= &wm
->ldr
.InMemoryOrderModuleList
;
528 wm
->ldr
.InMemoryOrderModuleList
.Blink
= entry
->Blink
;
529 wm
->ldr
.InMemoryOrderModuleList
.Flink
= entry
;
530 entry
->Blink
= &wm
->ldr
.InMemoryOrderModuleList
;
532 /* wait until init is called for inserting into this list */
533 wm
->ldr
.InInitializationOrderModuleList
.Flink
= NULL
;
534 wm
->ldr
.InInitializationOrderModuleList
.Blink
= NULL
;
539 /*************************************************************************
542 * Allocate the process-wide structure for module TLS storage.
544 static NTSTATUS
alloc_process_tls(void)
546 PLIST_ENTRY mark
, entry
;
548 IMAGE_TLS_DIRECTORY
*dir
;
551 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
552 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
554 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
555 if (!(dir
= RtlImageDirectoryEntryToData( mod
->BaseAddress
, TRUE
,
556 IMAGE_DIRECTORY_ENTRY_TLS
, &size
)))
558 size
= (dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
) + dir
->SizeOfZeroFill
;
560 tls_total_size
+= size
;
563 if (!tls_module_count
) return STATUS_SUCCESS
;
565 TRACE( "count %u size %u\n", tls_module_count
, tls_total_size
);
567 tls_dirs
= RtlAllocateHeap( ntdll_get_process_heap(), 0, tls_module_count
* sizeof(*tls_dirs
) );
568 if (!tls_dirs
) return STATUS_NO_MEMORY
;
570 for (i
= 0, entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
572 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
573 if (!(dir
= RtlImageDirectoryEntryToData( mod
->BaseAddress
, TRUE
,
574 IMAGE_DIRECTORY_ENTRY_TLS
, &size
)))
577 *dir
->AddressOfIndex
= i
;
579 mod
->LoadCount
= -1; /* can't unload it */
582 return STATUS_SUCCESS
;
586 /*************************************************************************
589 * Allocate the per-thread structure for module TLS storage.
591 static NTSTATUS
alloc_thread_tls(void)
597 if (!tls_module_count
) return STATUS_SUCCESS
;
599 if (!(pointers
= RtlAllocateHeap( ntdll_get_process_heap(), 0,
600 tls_module_count
* sizeof(*pointers
) )))
601 return STATUS_NO_MEMORY
;
603 if (!(data
= RtlAllocateHeap( ntdll_get_process_heap(), 0, tls_total_size
)))
605 RtlFreeHeap( ntdll_get_process_heap(), 0, pointers
);
606 return STATUS_NO_MEMORY
;
609 for (i
= 0; i
< tls_module_count
; i
++)
611 const IMAGE_TLS_DIRECTORY
*dir
= tls_dirs
[i
];
612 ULONG size
= dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
;
614 TRACE( "thread %04lx idx %d: %ld/%ld bytes from %p to %p\n",
615 GetCurrentThreadId(), i
, size
, dir
->SizeOfZeroFill
,
616 (void *)dir
->StartAddressOfRawData
, data
);
619 memcpy( data
, (void *)dir
->StartAddressOfRawData
, size
);
621 memset( data
, 0, dir
->SizeOfZeroFill
);
622 data
+= dir
->SizeOfZeroFill
;
624 NtCurrentTeb()->ThreadLocalStoragePointer
= pointers
;
625 return STATUS_SUCCESS
;
629 /*************************************************************************
632 static void call_tls_callbacks( HMODULE module
, UINT reason
)
634 const IMAGE_TLS_DIRECTORY
*dir
;
635 const PIMAGE_TLS_CALLBACK
*callback
;
638 dir
= RtlImageDirectoryEntryToData( module
, TRUE
, IMAGE_DIRECTORY_ENTRY_TLS
, &dirsize
);
639 if (!dir
|| !dir
->AddressOfCallBacks
) return;
641 for (callback
= dir
->AddressOfCallBacks
; *callback
; callback
++)
644 DPRINTF("%04lx:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
645 GetCurrentThreadId(), *callback
, module
, reason_names
[reason
] );
646 (*callback
)( module
, reason
, NULL
);
648 DPRINTF("%04lx:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
649 GetCurrentThreadId(), *callback
, module
, reason_names
[reason
] );
654 /*************************************************************************
657 static BOOL
MODULE_InitDLL( WINE_MODREF
*wm
, UINT reason
, LPVOID lpReserved
)
661 DLLENTRYPROC entry
= wm
->ldr
.EntryPoint
;
662 void *module
= wm
->ldr
.BaseAddress
;
664 /* Skip calls for modules loaded with special load flags */
666 if (wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
) return TRUE
;
667 if (wm
->ldr
.TlsIndex
!= -1) call_tls_callbacks( wm
->ldr
.BaseAddress
, reason
);
668 if (!entry
|| !(wm
->ldr
.Flags
& LDR_IMAGE_IS_DLL
)) return TRUE
;
672 size_t len
= max( wm
->ldr
.BaseDllName
.Length
, sizeof(mod_name
)-sizeof(WCHAR
) );
673 memcpy( mod_name
, wm
->ldr
.BaseDllName
.Buffer
, len
);
674 mod_name
[len
/ sizeof(WCHAR
)] = 0;
675 DPRINTF("%04lx:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
676 GetCurrentThreadId(), entry
, module
, debugstr_w(mod_name
),
677 reason_names
[reason
], lpReserved
);
679 else TRACE("(%p %s,%s,%p) - CALL\n", module
, debugstr_w(wm
->ldr
.BaseDllName
.Buffer
),
680 reason_names
[reason
], lpReserved
);
682 retv
= entry( module
, reason
, lpReserved
);
684 /* The state of the module list may have changed due to the call
685 to the dll. We cannot assume that this module has not been
688 DPRINTF("%04lx:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
689 GetCurrentThreadId(), entry
, module
, debugstr_w(mod_name
),
690 reason_names
[reason
], lpReserved
, retv
);
691 else TRACE("(%p,%s,%p) - RETURN %d\n", module
, reason_names
[reason
], lpReserved
, retv
);
697 /*************************************************************************
700 * Send the process attach notification to all DLLs the given module
701 * depends on (recursively). This is somewhat complicated due to the fact that
703 * - we have to respect the module dependencies, i.e. modules implicitly
704 * referenced by another module have to be initialized before the module
705 * itself can be initialized
707 * - the initialization routine of a DLL can itself call LoadLibrary,
708 * thereby introducing a whole new set of dependencies (even involving
709 * the 'old' modules) at any time during the whole process
711 * (Note that this routine can be recursively entered not only directly
712 * from itself, but also via LoadLibrary from one of the called initialization
715 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
716 * the process *detach* notifications to be sent in the correct order.
717 * This must not only take into account module dependencies, but also
718 * 'hidden' dependencies created by modules calling LoadLibrary in their
719 * attach notification routine.
721 * The strategy is rather simple: we move a WINE_MODREF to the head of the
722 * list after the attach notification has returned. This implies that the
723 * detach notifications are called in the reverse of the sequence the attach
724 * notifications *returned*.
726 * The loader_section must be locked while calling this function.
728 static NTSTATUS
process_attach( WINE_MODREF
*wm
, LPVOID lpReserved
)
730 NTSTATUS status
= STATUS_SUCCESS
;
733 /* prevent infinite recursion in case of cyclical dependencies */
734 if ( ( wm
->ldr
.Flags
& LDR_LOAD_IN_PROGRESS
)
735 || ( wm
->ldr
.Flags
& LDR_PROCESS_ATTACHED
) )
738 TRACE("(%s,%p) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
740 /* Tag current MODREF to prevent recursive loop */
741 wm
->ldr
.Flags
|= LDR_LOAD_IN_PROGRESS
;
743 /* Recursively attach all DLLs this one depends on */
744 for ( i
= 0; i
< wm
->nDeps
; i
++ )
746 if (!wm
->deps
[i
]) continue;
747 if ((status
= process_attach( wm
->deps
[i
], lpReserved
)) != STATUS_SUCCESS
) break;
750 /* Call DLL entry point */
751 if (status
== STATUS_SUCCESS
)
753 WINE_MODREF
*prev
= current_modref
;
755 if (MODULE_InitDLL( wm
, DLL_PROCESS_ATTACH
, lpReserved
))
756 wm
->ldr
.Flags
|= LDR_PROCESS_ATTACHED
;
758 status
= STATUS_DLL_INIT_FAILED
;
759 current_modref
= prev
;
762 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
,
763 &wm
->ldr
.InInitializationOrderModuleList
);
765 /* Remove recursion flag */
766 wm
->ldr
.Flags
&= ~LDR_LOAD_IN_PROGRESS
;
768 TRACE("(%s,%p) - END\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
772 /*************************************************************************
775 * Send DLL process detach notifications. See the comment about calling
776 * sequence at process_attach. Unless the bForceDetach flag
777 * is set, only DLLs with zero refcount are notified.
779 static void process_detach( BOOL bForceDetach
, LPVOID lpReserved
)
781 PLIST_ENTRY mark
, entry
;
784 RtlEnterCriticalSection( &loader_section
);
785 if (bForceDetach
) process_detaching
= 1;
786 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
789 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
791 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
792 InInitializationOrderModuleList
);
793 /* Check whether to detach this DLL */
794 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
796 if ( mod
->LoadCount
&& !bForceDetach
)
799 /* Call detach notification */
800 mod
->Flags
&= ~LDR_PROCESS_ATTACHED
;
801 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
802 DLL_PROCESS_DETACH
, lpReserved
);
804 /* Restart at head of WINE_MODREF list, as entries might have
805 been added and/or removed while performing the call ... */
808 } while (entry
!= mark
);
810 RtlLeaveCriticalSection( &loader_section
);
813 /*************************************************************************
814 * MODULE_DllThreadAttach
816 * Send DLL thread attach notifications. These are sent in the
817 * reverse sequence of process detach notification.
820 NTSTATUS
MODULE_DllThreadAttach( LPVOID lpReserved
)
822 PLIST_ENTRY mark
, entry
;
826 /* don't do any attach calls if process is exiting */
827 if (process_detaching
) return STATUS_SUCCESS
;
828 /* FIXME: there is still a race here */
830 RtlEnterCriticalSection( &loader_section
);
832 if ((status
= alloc_thread_tls()) != STATUS_SUCCESS
) goto done
;
834 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
835 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
837 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
838 InInitializationOrderModuleList
);
839 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
841 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
844 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
845 DLL_THREAD_ATTACH
, lpReserved
);
849 RtlLeaveCriticalSection( &loader_section
);
853 /******************************************************************
854 * LdrDisableThreadCalloutsForDll (NTDLL.@)
857 NTSTATUS WINAPI
LdrDisableThreadCalloutsForDll(HMODULE hModule
)
860 NTSTATUS ret
= STATUS_SUCCESS
;
862 RtlEnterCriticalSection( &loader_section
);
864 wm
= get_modref( hModule
);
865 if (!wm
|| wm
->ldr
.TlsIndex
!= -1)
866 ret
= STATUS_DLL_NOT_FOUND
;
868 wm
->ldr
.Flags
|= LDR_NO_DLL_CALLS
;
870 RtlLeaveCriticalSection( &loader_section
);
875 /******************************************************************
876 * LdrFindEntryForAddress (NTDLL.@)
878 * The loader_section must be locked while calling this function
880 NTSTATUS WINAPI
LdrFindEntryForAddress(const void* addr
, PLDR_MODULE
* pmod
)
882 PLIST_ENTRY mark
, entry
;
885 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
886 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
888 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
889 if ((const void *)mod
->BaseAddress
<= addr
&&
890 (char *)addr
< (char*)mod
->BaseAddress
+ mod
->SizeOfImage
)
893 return STATUS_SUCCESS
;
895 if ((const void *)mod
->BaseAddress
> addr
) break;
897 return STATUS_NO_MORE_ENTRIES
;
900 /******************************************************************
901 * LdrLockLoaderLock (NTDLL.@)
903 * Note: flags are not implemented.
904 * Flag 0x01 is used to raise exceptions on errors.
905 * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
907 NTSTATUS WINAPI
LdrLockLoaderLock( ULONG flags
, ULONG
*result
, ULONG
*magic
)
909 if (flags
) FIXME( "flags %lx not supported\n", flags
);
911 if (result
) *result
= 1;
912 if (!magic
) return STATUS_INVALID_PARAMETER_3
;
913 RtlEnterCriticalSection( &loader_section
);
914 *magic
= GetCurrentThreadId();
915 return STATUS_SUCCESS
;
919 /******************************************************************
920 * LdrUnlockLoaderUnlock (NTDLL.@)
922 NTSTATUS WINAPI
LdrUnlockLoaderLock( ULONG flags
, ULONG magic
)
926 if (magic
!= GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2
;
927 RtlLeaveCriticalSection( &loader_section
);
929 return STATUS_SUCCESS
;
933 /******************************************************************
934 * LdrGetDllHandle (NTDLL.@)
936 NTSTATUS WINAPI
LdrGetDllHandle(ULONG x
, ULONG y
, const UNICODE_STRING
*name
, HMODULE
*base
)
938 NTSTATUS status
= STATUS_DLL_NOT_FOUND
;
939 WCHAR dllname
[MAX_PATH
+4], *p
;
941 PLIST_ENTRY mark
, entry
;
944 if (x
!= 0 || y
!= 0)
945 FIXME("Unknown behavior, please report\n");
947 /* Append .DLL to name if no extension present */
948 if (!(p
= strrchrW( name
->Buffer
, '.')) || strchrW( p
, '/' ) || strchrW( p
, '\\'))
950 if (name
->Length
>= MAX_PATH
) return STATUS_NAME_TOO_LONG
;
951 strcpyW( dllname
, name
->Buffer
);
952 strcatW( dllname
, dllW
);
953 RtlInitUnicodeString( &str
, dllname
);
957 RtlEnterCriticalSection( &loader_section
);
961 if (RtlEqualUnicodeString( name
, &cached_modref
->ldr
.FullDllName
, TRUE
) ||
962 RtlEqualUnicodeString( name
, &cached_modref
->ldr
.BaseDllName
, TRUE
))
964 *base
= cached_modref
->ldr
.BaseAddress
;
965 status
= STATUS_SUCCESS
;
970 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
971 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
973 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
975 if (RtlEqualUnicodeString( name
, &mod
->FullDllName
, TRUE
) ||
976 RtlEqualUnicodeString( name
, &mod
->BaseDllName
, TRUE
))
978 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
979 *base
= mod
->BaseAddress
;
980 status
= STATUS_SUCCESS
;
985 RtlLeaveCriticalSection( &loader_section
);
986 TRACE("%lx %lx %s -> %p\n", x
, y
, debugstr_us(name
), status
? NULL
: *base
);
991 /******************************************************************
992 * LdrGetProcedureAddress (NTDLL.@)
994 NTSTATUS WINAPI
LdrGetProcedureAddress(HMODULE module
, const ANSI_STRING
*name
,
995 ULONG ord
, PVOID
*address
)
997 IMAGE_EXPORT_DIRECTORY
*exports
;
999 NTSTATUS ret
= STATUS_PROCEDURE_NOT_FOUND
;
1001 RtlEnterCriticalSection( &loader_section
);
1003 if ((exports
= RtlImageDirectoryEntryToData( module
, TRUE
,
1004 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
1006 void *proc
= name
? find_named_export( module
, exports
, exp_size
, name
->Buffer
, -1 )
1007 : find_ordinal_export( module
, exports
, exp_size
, ord
- exports
->Base
);
1011 ret
= STATUS_SUCCESS
;
1016 /* check if the module itself is invalid to return the proper error */
1017 if (!get_modref( module
)) ret
= STATUS_DLL_NOT_FOUND
;
1020 RtlLeaveCriticalSection( &loader_section
);
1025 /***********************************************************************
1026 * load_builtin_callback
1028 * Load a library in memory; callback function for wine_dll_register
1030 static void load_builtin_callback( void *module
, const char *filename
)
1032 IMAGE_NT_HEADERS
*nt
;
1034 WCHAR
*fullname
, *p
;
1038 ERR("could not map image for %s\n", filename
? filename
: "main exe" );
1041 if (!(nt
= RtlImageNtHeader( module
)))
1043 ERR( "bad module for %s\n", filename
? filename
: "main exe" );
1044 builtin_load_info
->status
= STATUS_INVALID_IMAGE_FORMAT
;
1047 if (!(nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
))
1049 /* if we already have an executable, ignore this one */
1050 if (!NtCurrentTeb()->Peb
->ImageBaseAddress
)
1051 NtCurrentTeb()->Peb
->ImageBaseAddress
= module
;
1052 return; /* don't create the modref here, will be done later on */
1055 /* create the MODREF */
1057 if (!(fullname
= RtlAllocateHeap( GetProcessHeap(), 0,
1058 system_dir
.MaximumLength
+ (strlen(filename
) + 1) * sizeof(WCHAR
) )))
1060 ERR( "can't load %s\n", filename
);
1061 builtin_load_info
->status
= STATUS_NO_MEMORY
;
1064 memcpy( fullname
, system_dir
.Buffer
, system_dir
.Length
);
1065 p
= fullname
+ system_dir
.Length
/ sizeof(WCHAR
);
1066 if (p
> fullname
&& p
[-1] != '\\') *p
++ = '\\';
1067 ascii_to_unicode( p
, filename
, strlen(filename
) + 1 );
1069 wm
= alloc_module( module
, fullname
);
1070 RtlFreeHeap( GetProcessHeap(), 0, fullname
);
1073 ERR( "can't load %s\n", filename
);
1074 builtin_load_info
->status
= STATUS_NO_MEMORY
;
1077 wm
->ldr
.Flags
|= LDR_WINE_INTERNAL
;
1081 if (fixup_imports( wm
, builtin_load_info
->load_path
) != STATUS_SUCCESS
)
1083 /* the module has only be inserted in the load & memory order lists */
1084 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
1085 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
1086 /* FIXME: free the modref */
1087 builtin_load_info
->status
= STATUS_DLL_NOT_FOUND
;
1090 builtin_load_info
->wm
= wm
;
1091 TRACE( "loaded %s %p %p\n", filename
, wm
, module
);
1093 /* send the DLL load event */
1095 SERVER_START_REQ( load_dll
)
1099 req
->size
= nt
->OptionalHeader
.SizeOfImage
;
1100 req
->dbg_offset
= nt
->FileHeader
.PointerToSymbolTable
;
1101 req
->dbg_size
= nt
->FileHeader
.NumberOfSymbols
;
1102 req
->name
= &wm
->ldr
.FullDllName
.Buffer
;
1103 wine_server_add_data( req
, wm
->ldr
.FullDllName
.Buffer
, wm
->ldr
.FullDllName
.Length
);
1104 wine_server_call( req
);
1108 /* setup relay debugging entry points */
1109 if (TRACE_ON(relay
)) RELAY_SetupDLL( module
);
1113 /******************************************************************************
1114 * load_native_dll (internal)
1116 static NTSTATUS
load_native_dll( LPCWSTR load_path
, LPCWSTR name
, HANDLE file
,
1117 DWORD flags
, WINE_MODREF
** pwm
)
1121 OBJECT_ATTRIBUTES attr
;
1123 IMAGE_NT_HEADERS
*nt
;
1128 TRACE( "loading %s\n", debugstr_w(name
) );
1130 attr
.Length
= sizeof(attr
);
1131 attr
.RootDirectory
= 0;
1132 attr
.ObjectName
= NULL
;
1133 attr
.Attributes
= 0;
1134 attr
.SecurityDescriptor
= NULL
;
1135 attr
.SecurityQualityOfService
= NULL
;
1138 status
= NtCreateSection( &mapping
, STANDARD_RIGHTS_REQUIRED
| SECTION_QUERY
| SECTION_MAP_READ
,
1139 &attr
, &size
, 0, SEC_IMAGE
, file
);
1140 if (status
!= STATUS_SUCCESS
) return status
;
1143 status
= NtMapViewOfSection( mapping
, GetCurrentProcess(),
1144 &module
, 0, 0, &size
, &len
, ViewShare
, 0, PAGE_READONLY
);
1146 if (status
!= STATUS_SUCCESS
) return status
;
1148 /* create the MODREF */
1150 if (!(wm
= alloc_module( module
, name
))) return STATUS_NO_MEMORY
;
1154 if (!(flags
& DONT_RESOLVE_DLL_REFERENCES
))
1156 if ((status
= fixup_imports( wm
, load_path
)) != STATUS_SUCCESS
)
1158 /* the module has only be inserted in the load & memory order lists */
1159 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
1160 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
1162 /* FIXME: there are several more dangling references
1163 * left. Including dlls loaded by this dll before the
1164 * failed one. Unrolling is rather difficult with the
1165 * current structure and we can leave them lying
1166 * around with no problems, so we don't care.
1167 * As these might reference our wm, we don't free it.
1172 else wm
->ldr
.Flags
|= LDR_DONT_RESOLVE_REFS
;
1174 /* send DLL load event */
1176 nt
= RtlImageNtHeader( module
);
1178 SERVER_START_REQ( load_dll
)
1182 req
->size
= nt
->OptionalHeader
.SizeOfImage
;
1183 req
->dbg_offset
= nt
->FileHeader
.PointerToSymbolTable
;
1184 req
->dbg_size
= nt
->FileHeader
.NumberOfSymbols
;
1185 req
->name
= &wm
->ldr
.FullDllName
.Buffer
;
1186 wine_server_add_data( req
, wm
->ldr
.FullDllName
.Buffer
, wm
->ldr
.FullDllName
.Length
);
1187 wine_server_call( req
);
1191 if (TRACE_ON(snoop
)) SNOOP_SetupDLL( module
);
1194 return STATUS_SUCCESS
;
1198 /***********************************************************************
1201 static NTSTATUS
load_builtin_dll( LPCWSTR load_path
, LPCWSTR path
, DWORD flags
, WINE_MODREF
** pwm
)
1203 char error
[256], dllname
[MAX_PATH
];
1205 const WCHAR
*name
, *p
;
1208 struct builtin_load_info info
, *prev_info
;
1210 /* Fix the name in case we have a full path and extension */
1212 if ((p
= strrchrW( name
, '\\' ))) name
= p
+ 1;
1213 if ((p
= strrchrW( name
, '/' ))) name
= p
+ 1;
1215 /* we don't want to depend on the current codepage here */
1216 len
= strlenW( name
) + 1;
1217 if (len
>= sizeof(dllname
)) return STATUS_NAME_TOO_LONG
;
1218 for (i
= 0; i
< len
; i
++)
1220 if (name
[i
] > 127) return STATUS_DLL_NOT_FOUND
;
1221 dllname
[i
] = (char)name
[i
];
1222 if (dllname
[i
] >= 'A' && dllname
[i
] <= 'Z') dllname
[i
] += 'a' - 'A';
1225 /* load_library will modify info.status. Note also that load_library can be
1226 * called several times, if the .so file we're loading has dependencies.
1227 * info.status will gather all the errors we may get while loading all these
1230 info
.load_path
= load_path
;
1231 info
.status
= STATUS_SUCCESS
;
1233 prev_info
= builtin_load_info
;
1234 builtin_load_info
= &info
;
1235 handle
= wine_dll_load( dllname
, error
, sizeof(error
), &file_exists
);
1236 builtin_load_info
= prev_info
;
1242 /* The file does not exist -> WARN() */
1243 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name
), error
);
1244 return STATUS_DLL_NOT_FOUND
;
1246 /* ERR() for all other errors (missing functions, ...) */
1247 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name
), error
);
1248 return STATUS_PROCEDURE_NOT_FOUND
;
1250 if (info
.status
!= STATUS_SUCCESS
) return info
.status
;
1254 /* The constructor wasn't called, this means the .so is already
1255 * loaded under a different name. We can't support multiple names
1256 * for the same module, so return an error. */
1257 return STATUS_INVALID_IMAGE_FORMAT
;
1260 info
.wm
->ldr
.SectionHandle
= handle
;
1261 if (strcmpiW( info
.wm
->ldr
.BaseDllName
.Buffer
, name
))
1263 ERR( "loaded .so for %s but got %s instead - probably 16-bit dll\n",
1264 debugstr_w(name
), debugstr_w(info
.wm
->ldr
.BaseDllName
.Buffer
) );
1265 /* wine_dll_unload( handle );*/
1266 return STATUS_INVALID_IMAGE_FORMAT
;
1269 return STATUS_SUCCESS
;
1273 /***********************************************************************
1276 * Find the file (or already loaded module) for a given dll name.
1278 static NTSTATUS
find_dll_file( const WCHAR
*load_path
, const WCHAR
*libname
,
1279 WCHAR
*filename
, ULONG
*size
, WINE_MODREF
**pwm
, HANDLE
*handle
)
1281 WCHAR
*file_part
, *ext
;
1284 if (RtlDetermineDosPathNameType_U( libname
) == RELATIVE_PATH
)
1286 /* we need to search for it */
1287 /* but first append .dll because RtlDosSearchPath extension handling is broken */
1288 if (!(ext
= strrchrW( libname
, '.')) || strchrW( ext
, '/' ) || strchrW( ext
, '\\'))
1292 if (!(dllname
= RtlAllocateHeap( GetProcessHeap(), 0,
1293 (strlenW(libname
) * sizeof(WCHAR
)) + sizeof(dllW
) )))
1294 return STATUS_NO_MEMORY
;
1295 strcpyW( dllname
, libname
);
1296 strcatW( dllname
, dllW
);
1297 len
= RtlDosSearchPath_U( load_path
, dllname
, NULL
, *size
, filename
, &file_part
);
1298 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1300 else len
= RtlDosSearchPath_U( load_path
, libname
, NULL
, *size
, filename
, &file_part
);
1306 *size
= len
+ sizeof(WCHAR
);
1307 return STATUS_BUFFER_TOO_SMALL
;
1309 if ((*pwm
= find_fullname_module( filename
)) != NULL
) return STATUS_SUCCESS
;
1311 /* check for already loaded module in a different path */
1312 if (!contains_path( libname
))
1314 if ((*pwm
= find_basename_module( file_part
)) != NULL
) return STATUS_SUCCESS
;
1316 *handle
= CreateFileW( filename
, GENERIC_READ
, FILE_SHARE_READ
, NULL
, OPEN_EXISTING
, 0, 0 );
1317 return STATUS_SUCCESS
;
1322 if (!contains_path( libname
))
1324 /* if libname doesn't contain a path at all, we simply return the name as is,
1325 * to be loaded as builtin */
1326 len
= strlenW(libname
) * sizeof(WCHAR
);
1327 if (len
>= *size
) goto overflow
;
1328 strcpyW( filename
, libname
);
1329 if (!strchrW( filename
, '.' ))
1331 len
+= sizeof(dllW
) - sizeof(WCHAR
);
1332 if (len
>= *size
) goto overflow
;
1333 strcatW( filename
, dllW
);
1335 *pwm
= find_basename_module( filename
);
1336 return STATUS_SUCCESS
;
1340 /* absolute path name, or relative path name but not found above */
1342 len
= RtlGetFullPathName_U( libname
, *size
, filename
, &file_part
);
1343 if (len
>= *size
) goto overflow
;
1344 if (file_part
&& !strchrW( file_part
, '.' ))
1346 len
+= sizeof(dllW
) - sizeof(WCHAR
);
1347 if (len
>= *size
) goto overflow
;
1348 strcatW( file_part
, dllW
);
1350 if ((*pwm
= find_fullname_module( filename
)) != NULL
) return STATUS_SUCCESS
;
1351 *handle
= CreateFileW( filename
, GENERIC_READ
, FILE_SHARE_READ
, NULL
, OPEN_EXISTING
, 0, 0 );
1352 return STATUS_SUCCESS
;
1355 *size
= len
+ sizeof(WCHAR
);
1356 return STATUS_BUFFER_TOO_SMALL
;
1360 /***********************************************************************
1361 * load_dll (internal)
1363 * Load a PE style module according to the load order.
1364 * The loader_section must be locked while calling this function.
1366 static NTSTATUS
load_dll( LPCWSTR load_path
, LPCWSTR libname
, DWORD flags
, WINE_MODREF
** pwm
)
1369 enum loadorder_type loadorder
[LOADORDER_NTYPES
];
1373 const char *filetype
= "";
1374 WINE_MODREF
*main_exe
;
1375 HANDLE handle
= INVALID_HANDLE_VALUE
;
1378 TRACE( "looking for %s in %s\n", debugstr_w(libname
), debugstr_w(load_path
) );
1381 size
= sizeof(buffer
);
1384 nts
= find_dll_file( load_path
, libname
, filename
, &size
, pwm
, &handle
);
1385 if (nts
== STATUS_SUCCESS
) break;
1386 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
1387 if (nts
!= STATUS_BUFFER_TOO_SMALL
) return nts
;
1388 /* grow the buffer and retry */
1389 if (!(filename
= RtlAllocateHeap( GetProcessHeap(), 0, size
))) return STATUS_NO_MEMORY
;
1392 if (*pwm
) /* found already loaded module */
1394 if ((*pwm
)->ldr
.LoadCount
!= -1) (*pwm
)->ldr
.LoadCount
++;
1396 if (((*pwm
)->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
) &&
1397 !(flags
& DONT_RESOLVE_DLL_REFERENCES
))
1399 (*pwm
)->ldr
.Flags
&= ~LDR_DONT_RESOLVE_REFS
;
1400 fixup_imports( *pwm
, load_path
);
1402 TRACE("Found loaded module %s for %s at %p, count=%d\n",
1403 debugstr_w((*pwm
)->ldr
.FullDllName
.Buffer
), debugstr_w(libname
),
1404 (*pwm
)->ldr
.BaseAddress
, (*pwm
)->ldr
.LoadCount
);
1405 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
1406 return STATUS_SUCCESS
;
1409 main_exe
= get_modref( NtCurrentTeb()->Peb
->ImageBaseAddress
);
1410 MODULE_GetLoadOrderW( loadorder
, main_exe
->ldr
.BaseDllName
.Buffer
, filename
, TRUE
);
1412 for (i
= 0; i
< LOADORDER_NTYPES
; i
++)
1414 if (loadorder
[i
] == LOADORDER_INVALID
) break;
1416 switch (loadorder
[i
])
1419 TRACE("Trying native dll %s\n", debugstr_w(filename
));
1420 if (handle
== INVALID_HANDLE_VALUE
) continue; /* it cannot possibly be loaded */
1421 nts
= load_native_dll( load_path
, filename
, handle
, flags
, pwm
);
1422 filetype
= "native";
1425 TRACE("Trying built-in %s\n", debugstr_w(filename
));
1426 nts
= load_builtin_dll( load_path
, filename
, flags
, pwm
);
1427 filetype
= "builtin";
1430 nts
= STATUS_INTERNAL_ERROR
;
1434 if (nts
== STATUS_SUCCESS
)
1436 /* Initialize DLL just loaded */
1437 TRACE("Loaded module %s (%s) at %p\n",
1438 debugstr_w(filename
), filetype
, (*pwm
)->ldr
.BaseAddress
);
1439 if (!TRACE_ON(module
))
1440 TRACE_(loaddll
)("Loaded module %s : %s\n", debugstr_w(filename
), filetype
);
1441 /* Set the ldr.LoadCount here so that an attach failure will */
1442 /* decrement the dependencies through the MODULE_FreeLibrary call. */
1443 (*pwm
)->ldr
.LoadCount
= 1;
1444 if (handle
!= INVALID_HANDLE_VALUE
) NtClose( handle
);
1445 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
1448 if (nts
!= STATUS_DLL_NOT_FOUND
) break;
1451 WARN("Failed to load module %s; status=%lx\n", debugstr_w(libname
), nts
);
1452 if (handle
!= INVALID_HANDLE_VALUE
) NtClose( handle
);
1453 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
1457 /******************************************************************
1458 * LdrLoadDll (NTDLL.@)
1460 NTSTATUS WINAPI
LdrLoadDll(LPCWSTR path_name
, DWORD flags
,
1461 const UNICODE_STRING
*libname
, HMODULE
* hModule
)
1466 RtlEnterCriticalSection( &loader_section
);
1468 if (!path_name
) path_name
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1469 nts
= load_dll( path_name
, libname
->Buffer
, flags
, &wm
);
1471 if (nts
== STATUS_SUCCESS
&& !(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
))
1473 nts
= process_attach( wm
, NULL
);
1474 if (nts
!= STATUS_SUCCESS
)
1476 WARN("Attach failed for module %s\n", debugstr_w(libname
->Buffer
));
1477 LdrUnloadDll(wm
->ldr
.BaseAddress
);
1481 *hModule
= (wm
) ? wm
->ldr
.BaseAddress
: NULL
;
1483 RtlLeaveCriticalSection( &loader_section
);
1487 /******************************************************************
1488 * LdrQueryProcessModuleInformation
1491 NTSTATUS WINAPI
LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi
,
1492 ULONG buf_size
, ULONG
* req_size
)
1494 SYSTEM_MODULE
* sm
= &smi
->Modules
[0];
1495 ULONG size
= sizeof(ULONG
);
1496 NTSTATUS nts
= STATUS_SUCCESS
;
1499 PLIST_ENTRY mark
, entry
;
1502 smi
->ModulesCount
= 0;
1504 RtlEnterCriticalSection( &loader_section
);
1505 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
1506 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1508 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
1509 size
+= sizeof(*sm
);
1510 if (size
<= buf_size
)
1512 sm
->Reserved1
= 0; /* FIXME */
1513 sm
->Reserved2
= 0; /* FIXME */
1514 sm
->ImageBaseAddress
= mod
->BaseAddress
;
1515 sm
->ImageSize
= mod
->SizeOfImage
;
1516 sm
->Flags
= mod
->Flags
;
1517 sm
->Id
= 0; /* FIXME */
1518 sm
->Rank
= 0; /* FIXME */
1519 sm
->Unknown
= 0; /* FIXME */
1521 str
.MaximumLength
= MAXIMUM_FILENAME_LENGTH
;
1522 str
.Buffer
= sm
->Name
;
1523 RtlUnicodeStringToAnsiString(&str
, &mod
->FullDllName
, FALSE
);
1524 ptr
= strrchr(sm
->Name
, '\\');
1525 sm
->NameOffset
= (ptr
!= NULL
) ? (ptr
- (char*)sm
->Name
+ 1) : 0;
1527 smi
->ModulesCount
++;
1530 else nts
= STATUS_INFO_LENGTH_MISMATCH
;
1532 RtlLeaveCriticalSection( &loader_section
);
1534 if (req_size
) *req_size
= size
;
1539 /******************************************************************
1540 * LdrShutdownProcess (NTDLL.@)
1543 void WINAPI
LdrShutdownProcess(void)
1546 process_detach( TRUE
, (LPVOID
)1 );
1549 /******************************************************************
1550 * LdrShutdownThread (NTDLL.@)
1553 void WINAPI
LdrShutdownThread(void)
1555 PLIST_ENTRY mark
, entry
;
1560 /* don't do any detach calls if process is exiting */
1561 if (process_detaching
) return;
1562 /* FIXME: there is still a race here */
1564 RtlEnterCriticalSection( &loader_section
);
1566 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1567 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
1569 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
1570 InInitializationOrderModuleList
);
1571 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1573 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
1576 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
1577 DLL_THREAD_DETACH
, NULL
);
1580 RtlLeaveCriticalSection( &loader_section
);
1583 /***********************************************************************
1584 * MODULE_FlushModrefs
1586 * Remove all unused modrefs and call the internal unloading routines
1587 * for the library type.
1589 * The loader_section must be locked while calling this function.
1591 static void MODULE_FlushModrefs(void)
1593 PLIST_ENTRY mark
, entry
, prev
;
1597 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1598 for (entry
= mark
->Blink
; entry
!= mark
; entry
= prev
)
1600 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
1601 InInitializationOrderModuleList
);
1602 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
1604 prev
= entry
->Blink
;
1605 if (mod
->LoadCount
) continue;
1607 RemoveEntryList(&mod
->InLoadOrderModuleList
);
1608 RemoveEntryList(&mod
->InMemoryOrderModuleList
);
1609 RemoveEntryList(&mod
->InInitializationOrderModuleList
);
1611 TRACE(" unloading %s\n", debugstr_w(mod
->FullDllName
.Buffer
));
1612 if (!TRACE_ON(module
))
1613 TRACE_(loaddll
)("Unloaded module %s : %s\n",
1614 debugstr_w(mod
->FullDllName
.Buffer
),
1615 (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) ? "builtin" : "native" );
1617 SERVER_START_REQ( unload_dll
)
1619 req
->base
= mod
->BaseAddress
;
1620 wine_server_call( req
);
1624 if (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) wine_dll_unload( wm
->ldr
.SectionHandle
);
1625 else NtUnmapViewOfSection( GetCurrentProcess(), mod
->BaseAddress
);
1626 if (cached_modref
== wm
) cached_modref
= NULL
;
1627 RtlFreeUnicodeString( &mod
->FullDllName
);
1628 RtlFreeHeap( ntdll_get_process_heap(), 0, wm
->deps
);
1629 RtlFreeHeap( ntdll_get_process_heap(), 0, wm
);
1633 /***********************************************************************
1634 * MODULE_DecRefCount
1636 * The loader_section must be locked while calling this function.
1638 static void MODULE_DecRefCount( WINE_MODREF
*wm
)
1642 if ( wm
->ldr
.Flags
& LDR_UNLOAD_IN_PROGRESS
)
1645 if ( wm
->ldr
.LoadCount
<= 0 )
1648 --wm
->ldr
.LoadCount
;
1649 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), wm
->ldr
.LoadCount
);
1651 if ( wm
->ldr
.LoadCount
== 0 )
1653 wm
->ldr
.Flags
|= LDR_UNLOAD_IN_PROGRESS
;
1655 for ( i
= 0; i
< wm
->nDeps
; i
++ )
1657 MODULE_DecRefCount( wm
->deps
[i
] );
1659 wm
->ldr
.Flags
&= ~LDR_UNLOAD_IN_PROGRESS
;
1663 /******************************************************************
1664 * LdrUnloadDll (NTDLL.@)
1668 NTSTATUS WINAPI
LdrUnloadDll( HMODULE hModule
)
1670 NTSTATUS retv
= STATUS_SUCCESS
;
1672 TRACE("(%p)\n", hModule
);
1674 RtlEnterCriticalSection( &loader_section
);
1676 /* if we're stopping the whole process (and forcing the removal of all
1677 * DLLs) the library will be freed anyway
1679 if (!process_detaching
)
1684 if ((wm
= get_modref( hModule
)) != NULL
)
1686 TRACE("(%s) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
1688 /* Recursively decrement reference counts */
1689 MODULE_DecRefCount( wm
);
1691 /* Call process detach notifications */
1692 if ( free_lib_count
<= 1 )
1694 process_detach( FALSE
, NULL
);
1695 MODULE_FlushModrefs();
1701 retv
= STATUS_DLL_NOT_FOUND
;
1706 RtlLeaveCriticalSection( &loader_section
);
1711 /***********************************************************************
1712 * RtlImageNtHeader (NTDLL.@)
1714 PIMAGE_NT_HEADERS WINAPI
RtlImageNtHeader(HMODULE hModule
)
1716 IMAGE_NT_HEADERS
*ret
;
1720 IMAGE_DOS_HEADER
*dos
= (IMAGE_DOS_HEADER
*)hModule
;
1723 if (dos
->e_magic
== IMAGE_DOS_SIGNATURE
)
1725 ret
= (IMAGE_NT_HEADERS
*)((char *)dos
+ dos
->e_lfanew
);
1726 if (ret
->Signature
!= IMAGE_NT_SIGNATURE
) ret
= NULL
;
1729 __EXCEPT(page_fault
)
1738 /******************************************************************
1739 * LdrInitializeThunk (NTDLL.@)
1741 * FIXME: the arguments are not correct, main_file is a Wine invention.
1743 void WINAPI
LdrInitializeThunk( HANDLE main_file
, ULONG unknown2
, ULONG unknown3
, ULONG unknown4
)
1748 LPTHREAD_START_ROUTINE entry
;
1749 PEB
*peb
= NtCurrentTeb()->Peb
;
1750 UNICODE_STRING
*main_exe_name
= &peb
->ProcessParameters
->ImagePathName
;
1751 IMAGE_NT_HEADERS
*nt
= RtlImageNtHeader( peb
->ImageBaseAddress
);
1753 /* allocate the modref for the main exe */
1754 if (!(wm
= alloc_module( peb
->ImageBaseAddress
, main_exe_name
->Buffer
)))
1756 status
= STATUS_NO_MEMORY
;
1759 wm
->ldr
.LoadCount
= -1; /* can't unload main exe */
1760 entry
= wm
->ldr
.EntryPoint
;
1762 /* Install signal handlers; this cannot be done before, since we cannot
1763 * send exceptions to the debugger before the create process event that
1764 * is sent by REQ_INIT_PROCESS_DONE.
1765 * We do need the handlers in place by the time the request is over, so
1766 * we set them up here. If we segfault between here and the server call
1767 * something is very wrong... */
1768 if (!SIGNAL_Init()) exit(1);
1770 /* Signal the parent process to continue */
1771 SERVER_START_REQ( init_process_done
)
1773 req
->module
= peb
->ImageBaseAddress
;
1774 req
->module_size
= wm
->ldr
.SizeOfImage
;
1776 /* API requires a double indirection */
1777 req
->name
= &main_exe_name
->Buffer
;
1778 req
->exe_file
= main_file
;
1779 req
->gui
= (nt
->OptionalHeader
.Subsystem
!= IMAGE_SUBSYSTEM_WINDOWS_CUI
);
1780 wine_server_add_data( req
, main_exe_name
->Buffer
, main_exe_name
->Length
);
1781 wine_server_call( req
);
1782 peb
->BeingDebugged
= reply
->debugged
;
1786 if (main_file
) NtClose( main_file
); /* we no longer need it */
1787 if (TRACE_ON(relay
) || TRACE_ON(snoop
)) RELAY_InitDebugLists();
1789 RtlEnterCriticalSection( &loader_section
);
1791 load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1792 if ((status
= fixup_imports( wm
, load_path
)) != STATUS_SUCCESS
) goto error
;
1793 if ((status
= alloc_process_tls()) != STATUS_SUCCESS
) goto error
;
1794 if ((status
= alloc_thread_tls()) != STATUS_SUCCESS
) goto error
;
1795 if ((status
= process_attach( wm
, (LPVOID
)1 )) != STATUS_SUCCESS
) goto error
;
1797 RtlLeaveCriticalSection( &loader_section
);
1799 if (TRACE_ON(relay
))
1800 DPRINTF( "%04lx:Starting process %s (entryproc=%p)\n", GetCurrentThreadId(),
1801 debugstr_w(peb
->ProcessParameters
->ImagePathName
.Buffer
), entry
);
1803 NtCurrentTeb()->last_error
= 0; /* clear error code */
1804 if (peb
->BeingDebugged
) DbgBreakPoint();
1805 NtTerminateProcess( GetCurrentProcess(), entry( peb
) );
1808 ERR( "Main exe initialization failed, status %lx\n", status
);
1813 /***********************************************************************
1814 * RtlImageDirectoryEntryToData (NTDLL.@)
1816 PVOID WINAPI
RtlImageDirectoryEntryToData( HMODULE module
, BOOL image
, WORD dir
, ULONG
*size
)
1818 const IMAGE_NT_HEADERS
*nt
;
1821 if ((ULONG_PTR
)module
& 1) /* mapped as data file */
1823 module
= (HMODULE
)((ULONG_PTR
)module
& ~1);
1826 if (!(nt
= RtlImageNtHeader( module
))) return NULL
;
1827 if (dir
>= nt
->OptionalHeader
.NumberOfRvaAndSizes
) return NULL
;
1828 if (!(addr
= nt
->OptionalHeader
.DataDirectory
[dir
].VirtualAddress
)) return NULL
;
1829 *size
= nt
->OptionalHeader
.DataDirectory
[dir
].Size
;
1830 if (image
|| addr
< nt
->OptionalHeader
.SizeOfHeaders
) return (char *)module
+ addr
;
1832 /* not mapped as image, need to find the section containing the virtual address */
1833 return RtlImageRvaToVa( nt
, module
, addr
, NULL
);
1837 /***********************************************************************
1838 * RtlImageRvaToSection (NTDLL.@)
1840 PIMAGE_SECTION_HEADER WINAPI
RtlImageRvaToSection( const IMAGE_NT_HEADERS
*nt
,
1841 HMODULE module
, DWORD rva
)
1844 IMAGE_SECTION_HEADER
*sec
= (IMAGE_SECTION_HEADER
*)((char*)&nt
->OptionalHeader
+
1845 nt
->FileHeader
.SizeOfOptionalHeader
);
1846 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++, sec
++)
1848 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
1855 /***********************************************************************
1856 * RtlImageRvaToVa (NTDLL.@)
1858 PVOID WINAPI
RtlImageRvaToVa( const IMAGE_NT_HEADERS
*nt
, HMODULE module
,
1859 DWORD rva
, IMAGE_SECTION_HEADER
**section
)
1861 IMAGE_SECTION_HEADER
*sec
;
1863 if (section
&& *section
) /* try this section first */
1866 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
1869 if (!(sec
= RtlImageRvaToSection( nt
, module
, rva
))) return NULL
;
1871 if (section
) *section
= sec
;
1872 return (char *)module
+ sec
->PointerToRawData
+ (rva
- sec
->VirtualAddress
);
1876 /***********************************************************************
1879 * Initialize loading callbacks and return HMODULE of main exe.
1880 * 'main' is the main exe in case it was already loaded from a PE file.
1882 * FIXME: this should be done differently once kernel is properly separated.
1884 HMODULE
BUILTIN32_LoadExeModule( HMODULE main
)
1886 static struct builtin_load_info default_info
;
1888 if (!MODULE_GetSystemDirectory( &system_dir
))
1889 MESSAGE( "Couldn't get system dir in process init\n");
1890 NtCurrentTeb()->Peb
->ImageBaseAddress
= main
;
1891 default_info
.status
= STATUS_SUCCESS
;
1892 default_info
.load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1893 builtin_load_info
= &default_info
;
1894 wine_dll_set_callback( load_builtin_callback
);
1895 if (!NtCurrentTeb()->Peb
->ImageBaseAddress
)
1896 MESSAGE( "No built-in EXE module loaded! Did you create a .spec file?\n" );
1897 if (default_info
.status
!= STATUS_SUCCESS
)
1898 MESSAGE( "Error while processing initial modules\n");
1899 return NtCurrentTeb()->Peb
->ImageBaseAddress
;