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
23 #include "wine/port.h"
28 #define NONAMELESSUNION
29 #define NONAMELESSSTRUCT
32 #define WIN32_NO_STATUS
38 #include "wine/exception.h"
40 #include "wine/library.h"
41 #include "wine/unicode.h"
42 #include "wine/debug.h"
43 #include "wine/server.h"
44 #include "ntdll_misc.h"
46 WINE_DEFAULT_DEBUG_CHANNEL(module
);
47 WINE_DECLARE_DEBUG_CHANNEL(relay
);
48 WINE_DECLARE_DEBUG_CHANNEL(snoop
);
49 WINE_DECLARE_DEBUG_CHANNEL(loaddll
);
50 WINE_DECLARE_DEBUG_CHANNEL(imports
);
52 typedef DWORD (CALLBACK
*DLLENTRYPROC
)(HMODULE
,DWORD
,LPVOID
);
54 static int process_detaching
= 0; /* set on process detach to avoid deadlocks with thread detach */
55 static int free_lib_count
; /* recursion depth of LdrUnloadDll calls */
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
;
80 const WCHAR
*filename
;
85 static struct builtin_load_info default_load_info
;
86 static struct builtin_load_info
*builtin_load_info
= &default_load_info
;
88 static UINT tls_module_count
; /* number of modules with TLS directory */
89 static UINT tls_total_size
; /* total size of TLS storage */
90 static const IMAGE_TLS_DIRECTORY
**tls_dirs
; /* array of TLS directories */
92 UNICODE_STRING system_dir
= { 0, 0, NULL
}; /* system directory */
94 static RTL_CRITICAL_SECTION loader_section
;
95 static RTL_CRITICAL_SECTION_DEBUG critsect_debug
=
97 0, 0, &loader_section
,
98 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
99 0, 0, { (DWORD_PTR
)(__FILE__
": loader_section") }
101 static RTL_CRITICAL_SECTION loader_section
= { &critsect_debug
, -1, 0, 0, 0, 0 };
103 static WINE_MODREF
*cached_modref
;
104 static WINE_MODREF
*current_modref
;
105 static WINE_MODREF
*last_failed_modref
;
107 static NTSTATUS
load_dll( LPCWSTR load_path
, LPCWSTR libname
, DWORD flags
, WINE_MODREF
** pwm
);
108 static FARPROC
find_named_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
109 DWORD exp_size
, const char *name
, int hint
);
111 /* convert PE image VirtualAddress to Real Address */
112 inline static void *get_rva( HMODULE module
, DWORD va
)
114 return (void *)((char *)module
+ va
);
117 /* check whether the file name contains a path */
118 inline static int contains_path( LPCWSTR name
)
120 return ((*name
&& (name
[1] == ':')) || strchrW(name
, '/') || strchrW(name
, '\\'));
123 /* convert from straight ASCII to Unicode without depending on the current codepage */
124 inline static void ascii_to_unicode( WCHAR
*dst
, const char *src
, size_t len
)
126 while (len
--) *dst
++ = (unsigned char)*src
++;
130 /*************************************************************************
131 * call_dll_entry_point
133 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
134 * their entry point, so we need a small asm wrapper.
137 extern BOOL
call_dll_entry_point( DLLENTRYPROC proc
, void *module
, UINT reason
, void *reserved
);
138 __ASM_GLOBAL_FUNC(call_dll_entry_point
,
146 "movl 8(%ebp),%eax\n\t"
148 "leal -4(%ebp),%esp\n\t"
153 static inline BOOL
call_dll_entry_point( DLLENTRYPROC proc
, void *module
,
154 UINT reason
, void *reserved
)
156 return proc( module
, reason
, reserved
);
158 #endif /* __i386__ */
162 /*************************************************************************
165 * Entry point for stub functions.
167 static void stub_entry_point( const char *dll
, const char *name
, ... )
169 EXCEPTION_RECORD rec
;
171 rec
.ExceptionCode
= EXCEPTION_WINE_STUB
;
172 rec
.ExceptionFlags
= EH_NONCONTINUABLE
;
173 rec
.ExceptionRecord
= NULL
;
175 rec
.ExceptionAddress
= __builtin_return_address(0);
177 rec
.ExceptionAddress
= *((void **)&dll
- 1);
179 rec
.NumberParameters
= 2;
180 rec
.ExceptionInformation
[0] = (ULONG_PTR
)dll
;
181 rec
.ExceptionInformation
[1] = (ULONG_PTR
)name
;
182 for (;;) RtlRaiseException( &rec
);
186 #include "pshpack1.h"
189 BYTE popl_eax
; /* popl %eax */
190 BYTE pushl1
; /* pushl $name */
192 BYTE pushl2
; /* pushl $dll */
194 BYTE pushl_eax
; /* pushl %eax */
195 BYTE jmp
; /* jmp stub_entry_point */
200 /*************************************************************************
203 * Allocate a stub entry point.
205 static ULONG_PTR
allocate_stub( const char *dll
, const char *name
)
207 #define MAX_SIZE 65536
208 static struct stub
*stubs
;
209 static unsigned int nb_stubs
;
212 if (nb_stubs
>= MAX_SIZE
/ sizeof(*stub
)) return 0xdeadbeef;
216 ULONG size
= MAX_SIZE
;
217 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs
, 0, &size
,
218 MEM_COMMIT
, PAGE_EXECUTE_WRITECOPY
) != STATUS_SUCCESS
)
221 stub
= &stubs
[nb_stubs
++];
222 stub
->popl_eax
= 0x58; /* popl %eax */
223 stub
->pushl1
= 0x68; /* pushl $name */
225 stub
->pushl2
= 0x68; /* pushl $dll */
227 stub
->pushl_eax
= 0x50; /* pushl %eax */
228 stub
->jmp
= 0xe9; /* jmp stub_entry_point */
229 stub
->entry
= (BYTE
*)stub_entry_point
- (BYTE
*)(&stub
->entry
+ 1);
230 return (ULONG_PTR
)stub
;
234 static inline ULONG_PTR
allocate_stub( const char *dll
, const char *name
) { return 0xdeadbeef; }
235 #endif /* __i386__ */
238 /*************************************************************************
241 * Looks for the referenced HMODULE in the current process
242 * The loader_section must be locked while calling this function.
244 static WINE_MODREF
*get_modref( HMODULE hmod
)
246 PLIST_ENTRY mark
, entry
;
249 if (cached_modref
&& cached_modref
->ldr
.BaseAddress
== hmod
) return cached_modref
;
251 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
252 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
254 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
255 if (mod
->BaseAddress
== hmod
)
256 return cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
257 if (mod
->BaseAddress
> (void*)hmod
) break;
263 /**********************************************************************
264 * find_basename_module
266 * Find a module from its base name.
267 * The loader_section must be locked while calling this function
269 static WINE_MODREF
*find_basename_module( LPCWSTR name
)
271 PLIST_ENTRY mark
, entry
;
273 if (cached_modref
&& !strcmpiW( name
, cached_modref
->ldr
.BaseDllName
.Buffer
))
274 return cached_modref
;
276 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
277 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
279 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
280 if (!strcmpiW( name
, mod
->BaseDllName
.Buffer
))
282 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
283 return cached_modref
;
290 /**********************************************************************
291 * find_fullname_module
293 * Find a module from its full path name.
294 * The loader_section must be locked while calling this function
296 static WINE_MODREF
*find_fullname_module( LPCWSTR name
)
298 PLIST_ENTRY mark
, entry
;
300 if (cached_modref
&& !strcmpiW( name
, cached_modref
->ldr
.FullDllName
.Buffer
))
301 return cached_modref
;
303 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
304 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
306 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
307 if (!strcmpiW( name
, mod
->FullDllName
.Buffer
))
309 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
310 return cached_modref
;
317 /*************************************************************************
318 * find_forwarded_export
320 * Find the final function pointer for a forwarded function.
321 * The loader_section must be locked while calling this function.
323 static FARPROC
find_forwarded_export( HMODULE module
, const char *forward
)
325 const IMAGE_EXPORT_DIRECTORY
*exports
;
329 const char *end
= strchr(forward
, '.');
332 if (!end
) return NULL
;
333 if ((end
- forward
) * sizeof(WCHAR
) >= sizeof(mod_name
) - sizeof(dllW
)) return NULL
;
334 ascii_to_unicode( mod_name
, forward
, end
- forward
);
335 memcpy( mod_name
+ (end
- forward
), dllW
, sizeof(dllW
) );
337 if (!(wm
= find_basename_module( mod_name
)))
339 ERR("module not found for forward '%s' used by %s\n",
340 forward
, debugstr_w(get_modref(module
)->ldr
.FullDllName
.Buffer
) );
343 if ((exports
= RtlImageDirectoryEntryToData( wm
->ldr
.BaseAddress
, TRUE
,
344 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
345 proc
= find_named_export( wm
->ldr
.BaseAddress
, exports
, exp_size
, end
+ 1, -1 );
349 ERR("function not found for forward '%s' used by %s."
350 " If you are using builtin %s, try using the native one instead.\n",
351 forward
, debugstr_w(get_modref(module
)->ldr
.FullDllName
.Buffer
),
352 debugstr_w(get_modref(module
)->ldr
.BaseDllName
.Buffer
) );
358 /*************************************************************************
359 * find_ordinal_export
361 * Find an exported function by ordinal.
362 * The exports base must have been subtracted from the ordinal already.
363 * The loader_section must be locked while calling this function.
365 static FARPROC
find_ordinal_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
366 DWORD exp_size
, DWORD ordinal
)
369 const DWORD
*functions
= get_rva( module
, exports
->AddressOfFunctions
);
371 if (ordinal
>= exports
->NumberOfFunctions
)
373 TRACE(" ordinal %ld out of range!\n", ordinal
+ exports
->Base
);
376 if (!functions
[ordinal
]) return NULL
;
378 proc
= get_rva( module
, functions
[ordinal
] );
380 /* if the address falls into the export dir, it's a forward */
381 if (((const char *)proc
>= (const char *)exports
) &&
382 ((const char *)proc
< (const char *)exports
+ exp_size
))
383 return find_forwarded_export( module
, (const char *)proc
);
387 const WCHAR
*user
= current_modref
? current_modref
->ldr
.BaseDllName
.Buffer
: NULL
;
388 proc
= SNOOP_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
, user
);
392 const WCHAR
*user
= current_modref
? current_modref
->ldr
.BaseDllName
.Buffer
: NULL
;
393 proc
= RELAY_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
, user
);
399 /*************************************************************************
402 * Find an exported function by name.
403 * The loader_section must be locked while calling this function.
405 static FARPROC
find_named_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
406 DWORD exp_size
, const char *name
, int hint
)
408 const WORD
*ordinals
= get_rva( module
, exports
->AddressOfNameOrdinals
);
409 const DWORD
*names
= get_rva( module
, exports
->AddressOfNames
);
410 int min
= 0, max
= exports
->NumberOfNames
- 1;
412 /* first check the hint */
413 if (hint
>= 0 && hint
<= max
)
415 char *ename
= get_rva( module
, names
[hint
] );
416 if (!strcmp( ename
, name
))
417 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[hint
] );
420 /* then do a binary search */
423 int res
, pos
= (min
+ max
) / 2;
424 char *ename
= get_rva( module
, names
[pos
] );
425 if (!(res
= strcmp( ename
, name
)))
426 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[pos
] );
427 if (res
> 0) max
= pos
- 1;
435 /*************************************************************************
438 * Import the dll specified by the given import descriptor.
439 * The loader_section must be locked while calling this function.
441 static WINE_MODREF
*import_dll( HMODULE module
, const IMAGE_IMPORT_DESCRIPTOR
*descr
, LPCWSTR load_path
)
446 const IMAGE_EXPORT_DIRECTORY
*exports
;
448 const IMAGE_THUNK_DATA
*import_list
;
449 IMAGE_THUNK_DATA
*thunk_list
;
451 const char *name
= get_rva( module
, descr
->Name
);
452 DWORD len
= strlen(name
) + 1;
454 SIZE_T protect_size
= 0;
457 thunk_list
= get_rva( module
, (DWORD
)descr
->FirstThunk
);
458 if (descr
->u
.OriginalFirstThunk
)
459 import_list
= get_rva( module
, (DWORD
)descr
->u
.OriginalFirstThunk
);
461 import_list
= thunk_list
;
463 if (len
* sizeof(WCHAR
) <= sizeof(buffer
))
465 ascii_to_unicode( buffer
, name
, len
);
466 status
= load_dll( load_path
, buffer
, 0, &wmImp
);
468 else /* need to allocate a larger buffer */
470 WCHAR
*ptr
= RtlAllocateHeap( GetProcessHeap(), 0, len
* sizeof(WCHAR
) );
471 if (!ptr
) return NULL
;
472 ascii_to_unicode( ptr
, name
, len
);
473 status
= load_dll( load_path
, ptr
, 0, &wmImp
);
474 RtlFreeHeap( GetProcessHeap(), 0, ptr
);
479 if (status
== STATUS_DLL_NOT_FOUND
)
480 ERR("Library %s (which is needed by %s) not found\n",
481 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
));
483 ERR("Loading library %s (which is needed by %s) failed (error %lx).\n",
484 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
), status
);
488 /* unprotect the import address table since it can be located in
489 * readonly section */
490 while (import_list
[protect_size
].u1
.Ordinal
) protect_size
++;
491 protect_base
= thunk_list
;
492 protect_size
*= sizeof(*thunk_list
);
493 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
,
494 &protect_size
, PAGE_WRITECOPY
, &protect_old
);
496 imp_mod
= wmImp
->ldr
.BaseAddress
;
497 exports
= RtlImageDirectoryEntryToData( imp_mod
, TRUE
, IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
);
501 /* set all imported function to deadbeef */
502 while (import_list
->u1
.Ordinal
)
504 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
506 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
507 WARN("No implementation for %s.%d", name
, ordinal
);
508 thunk_list
->u1
.Function
= allocate_stub( name
, (const char *)ordinal
);
512 IMAGE_IMPORT_BY_NAME
*pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
513 WARN("No implementation for %s.%s", name
, pe_name
->Name
);
514 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
516 WARN(" imported from %s, allocating stub %p\n",
517 debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
518 (void *)thunk_list
->u1
.Function
);
525 while (import_list
->u1
.Ordinal
)
527 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
529 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
531 thunk_list
->u1
.Function
= (ULONG_PTR
)find_ordinal_export( imp_mod
, exports
, exp_size
,
532 ordinal
- exports
->Base
);
533 if (!thunk_list
->u1
.Function
)
535 thunk_list
->u1
.Function
= allocate_stub( name
, (const char *)ordinal
);
536 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
537 name
, ordinal
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
538 (void *)thunk_list
->u1
.Function
);
540 TRACE_(imports
)("--- Ordinal %s.%d = %p\n", name
, ordinal
, (void *)thunk_list
->u1
.Function
);
542 else /* import by name */
544 IMAGE_IMPORT_BY_NAME
*pe_name
;
545 pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
546 thunk_list
->u1
.Function
= (ULONG_PTR
)find_named_export( imp_mod
, exports
, exp_size
,
547 (const char*)pe_name
->Name
, pe_name
->Hint
);
548 if (!thunk_list
->u1
.Function
)
550 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
551 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
552 name
, pe_name
->Name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
553 (void *)thunk_list
->u1
.Function
);
555 TRACE_(imports
)("--- %s %s.%d = %p\n",
556 pe_name
->Name
, name
, pe_name
->Hint
, (void *)thunk_list
->u1
.Function
);
563 /* restore old protection of the import address table */
564 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
, &protect_size
, protect_old
, NULL
);
569 /****************************************************************
572 * Fixup all imports of a given module.
573 * The loader_section must be locked while calling this function.
575 static NTSTATUS
fixup_imports( WINE_MODREF
*wm
, LPCWSTR load_path
)
578 const IMAGE_IMPORT_DESCRIPTOR
*imports
;
583 if (!(imports
= RtlImageDirectoryEntryToData( wm
->ldr
.BaseAddress
, TRUE
,
584 IMAGE_DIRECTORY_ENTRY_IMPORT
, &size
)))
585 return STATUS_SUCCESS
;
588 while (imports
[nb_imports
].Name
&& imports
[nb_imports
].FirstThunk
) nb_imports
++;
590 if (!nb_imports
) return STATUS_SUCCESS
; /* no imports */
592 /* Allocate module dependency list */
593 wm
->nDeps
= nb_imports
;
594 wm
->deps
= RtlAllocateHeap( GetProcessHeap(), 0, nb_imports
*sizeof(WINE_MODREF
*) );
596 /* load the imported modules. They are automatically
597 * added to the modref list of the process.
599 prev
= current_modref
;
601 status
= STATUS_SUCCESS
;
602 for (i
= 0; i
< nb_imports
; i
++)
604 if (!(wm
->deps
[i
] = import_dll( wm
->ldr
.BaseAddress
, &imports
[i
], load_path
)))
605 status
= STATUS_DLL_NOT_FOUND
;
607 current_modref
= prev
;
612 /*************************************************************************
615 * Allocate a WINE_MODREF structure and add it to the process list
616 * The loader_section must be locked while calling this function.
618 static WINE_MODREF
*alloc_module( HMODULE hModule
, LPCWSTR filename
)
622 const IMAGE_NT_HEADERS
*nt
= RtlImageNtHeader(hModule
);
623 PLIST_ENTRY entry
, mark
;
625 if (!(wm
= RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm
) ))) return NULL
;
630 wm
->ldr
.BaseAddress
= hModule
;
631 wm
->ldr
.EntryPoint
= NULL
;
632 wm
->ldr
.SizeOfImage
= nt
->OptionalHeader
.SizeOfImage
;
634 wm
->ldr
.LoadCount
= 0;
635 wm
->ldr
.TlsIndex
= -1;
636 wm
->ldr
.SectionHandle
= NULL
;
637 wm
->ldr
.CheckSum
= 0;
638 wm
->ldr
.TimeDateStamp
= 0;
640 RtlCreateUnicodeString( &wm
->ldr
.FullDllName
, filename
);
641 if ((p
= strrchrW( wm
->ldr
.FullDllName
.Buffer
, '\\' ))) p
++;
642 else p
= wm
->ldr
.FullDllName
.Buffer
;
643 RtlInitUnicodeString( &wm
->ldr
.BaseDllName
, p
);
645 if (nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
)
647 wm
->ldr
.Flags
|= LDR_IMAGE_IS_DLL
;
648 if (nt
->OptionalHeader
.AddressOfEntryPoint
)
649 wm
->ldr
.EntryPoint
= (char *)hModule
+ nt
->OptionalHeader
.AddressOfEntryPoint
;
652 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
,
653 &wm
->ldr
.InLoadOrderModuleList
);
655 /* insert module in MemoryList, sorted in increasing base addresses */
656 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
657 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
659 if (CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
)->BaseAddress
> wm
->ldr
.BaseAddress
)
662 entry
->Blink
->Flink
= &wm
->ldr
.InMemoryOrderModuleList
;
663 wm
->ldr
.InMemoryOrderModuleList
.Blink
= entry
->Blink
;
664 wm
->ldr
.InMemoryOrderModuleList
.Flink
= entry
;
665 entry
->Blink
= &wm
->ldr
.InMemoryOrderModuleList
;
667 /* wait until init is called for inserting into this list */
668 wm
->ldr
.InInitializationOrderModuleList
.Flink
= NULL
;
669 wm
->ldr
.InInitializationOrderModuleList
.Blink
= NULL
;
674 /*************************************************************************
677 * Allocate the process-wide structure for module TLS storage.
679 static NTSTATUS
alloc_process_tls(void)
681 PLIST_ENTRY mark
, entry
;
683 const IMAGE_TLS_DIRECTORY
*dir
;
686 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
687 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
689 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
690 if (!(dir
= RtlImageDirectoryEntryToData( mod
->BaseAddress
, TRUE
,
691 IMAGE_DIRECTORY_ENTRY_TLS
, &size
)))
693 size
= (dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
) + dir
->SizeOfZeroFill
;
695 tls_total_size
+= size
;
698 if (!tls_module_count
) return STATUS_SUCCESS
;
700 TRACE( "count %u size %u\n", tls_module_count
, tls_total_size
);
702 tls_dirs
= RtlAllocateHeap( GetProcessHeap(), 0, tls_module_count
* sizeof(*tls_dirs
) );
703 if (!tls_dirs
) return STATUS_NO_MEMORY
;
705 for (i
= 0, entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
707 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
708 if (!(dir
= RtlImageDirectoryEntryToData( mod
->BaseAddress
, TRUE
,
709 IMAGE_DIRECTORY_ENTRY_TLS
, &size
)))
712 *(DWORD
*)dir
->AddressOfIndex
= i
;
714 mod
->LoadCount
= -1; /* can't unload it */
717 return STATUS_SUCCESS
;
721 /*************************************************************************
724 * Allocate the per-thread structure for module TLS storage.
726 static NTSTATUS
alloc_thread_tls(void)
732 if (!tls_module_count
) return STATUS_SUCCESS
;
734 if (!(pointers
= RtlAllocateHeap( GetProcessHeap(), 0,
735 tls_module_count
* sizeof(*pointers
) )))
736 return STATUS_NO_MEMORY
;
738 if (!(data
= RtlAllocateHeap( GetProcessHeap(), 0, tls_total_size
)))
740 RtlFreeHeap( GetProcessHeap(), 0, pointers
);
741 return STATUS_NO_MEMORY
;
744 for (i
= 0; i
< tls_module_count
; i
++)
746 const IMAGE_TLS_DIRECTORY
*dir
= tls_dirs
[i
];
747 ULONG size
= dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
;
749 TRACE( "thread %04lx idx %d: %ld/%ld bytes from %p to %p\n",
750 GetCurrentThreadId(), i
, size
, dir
->SizeOfZeroFill
,
751 (void *)dir
->StartAddressOfRawData
, data
);
754 memcpy( data
, (void *)dir
->StartAddressOfRawData
, size
);
756 memset( data
, 0, dir
->SizeOfZeroFill
);
757 data
+= dir
->SizeOfZeroFill
;
759 NtCurrentTeb()->ThreadLocalStoragePointer
= pointers
;
760 return STATUS_SUCCESS
;
764 /*************************************************************************
767 static void call_tls_callbacks( HMODULE module
, UINT reason
)
769 const IMAGE_TLS_DIRECTORY
*dir
;
770 const PIMAGE_TLS_CALLBACK
*callback
;
773 dir
= RtlImageDirectoryEntryToData( module
, TRUE
, IMAGE_DIRECTORY_ENTRY_TLS
, &dirsize
);
774 if (!dir
|| !dir
->AddressOfCallBacks
) return;
776 for (callback
= (const PIMAGE_TLS_CALLBACK
*)dir
->AddressOfCallBacks
; *callback
; callback
++)
779 DPRINTF("%04lx:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
780 GetCurrentThreadId(), *callback
, module
, reason_names
[reason
] );
781 (*callback
)( module
, reason
, NULL
);
783 DPRINTF("%04lx:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
784 GetCurrentThreadId(), *callback
, module
, reason_names
[reason
] );
789 /*************************************************************************
792 static BOOL
MODULE_InitDLL( WINE_MODREF
*wm
, UINT reason
, LPVOID lpReserved
)
796 DLLENTRYPROC entry
= wm
->ldr
.EntryPoint
;
797 void *module
= wm
->ldr
.BaseAddress
;
799 /* Skip calls for modules loaded with special load flags */
801 if (wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
) return TRUE
;
802 if (wm
->ldr
.TlsIndex
!= -1) call_tls_callbacks( wm
->ldr
.BaseAddress
, reason
);
803 if (!entry
) return TRUE
;
807 size_t len
= min( wm
->ldr
.BaseDllName
.Length
, sizeof(mod_name
)-sizeof(WCHAR
) );
808 memcpy( mod_name
, wm
->ldr
.BaseDllName
.Buffer
, len
);
809 mod_name
[len
/ sizeof(WCHAR
)] = 0;
810 DPRINTF("%04lx:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
811 GetCurrentThreadId(), entry
, module
, debugstr_w(mod_name
),
812 reason_names
[reason
], lpReserved
);
814 else TRACE("(%p %s,%s,%p) - CALL\n", module
, debugstr_w(wm
->ldr
.BaseDllName
.Buffer
),
815 reason_names
[reason
], lpReserved
);
817 retv
= call_dll_entry_point( entry
, module
, reason
, lpReserved
);
819 /* The state of the module list may have changed due to the call
820 to the dll. We cannot assume that this module has not been
823 DPRINTF("%04lx:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
824 GetCurrentThreadId(), entry
, module
, debugstr_w(mod_name
),
825 reason_names
[reason
], lpReserved
, retv
);
826 else TRACE("(%p,%s,%p) - RETURN %d\n", module
, reason_names
[reason
], lpReserved
, retv
);
832 /*************************************************************************
835 * Send the process attach notification to all DLLs the given module
836 * depends on (recursively). This is somewhat complicated due to the fact that
838 * - we have to respect the module dependencies, i.e. modules implicitly
839 * referenced by another module have to be initialized before the module
840 * itself can be initialized
842 * - the initialization routine of a DLL can itself call LoadLibrary,
843 * thereby introducing a whole new set of dependencies (even involving
844 * the 'old' modules) at any time during the whole process
846 * (Note that this routine can be recursively entered not only directly
847 * from itself, but also via LoadLibrary from one of the called initialization
850 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
851 * the process *detach* notifications to be sent in the correct order.
852 * This must not only take into account module dependencies, but also
853 * 'hidden' dependencies created by modules calling LoadLibrary in their
854 * attach notification routine.
856 * The strategy is rather simple: we move a WINE_MODREF to the head of the
857 * list after the attach notification has returned. This implies that the
858 * detach notifications are called in the reverse of the sequence the attach
859 * notifications *returned*.
861 * The loader_section must be locked while calling this function.
863 static NTSTATUS
process_attach( WINE_MODREF
*wm
, LPVOID lpReserved
)
865 NTSTATUS status
= STATUS_SUCCESS
;
868 if (process_detaching
) return status
;
870 /* prevent infinite recursion in case of cyclical dependencies */
871 if ( ( wm
->ldr
.Flags
& LDR_LOAD_IN_PROGRESS
)
872 || ( wm
->ldr
.Flags
& LDR_PROCESS_ATTACHED
) )
875 TRACE("(%s,%p) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
877 /* Tag current MODREF to prevent recursive loop */
878 wm
->ldr
.Flags
|= LDR_LOAD_IN_PROGRESS
;
880 /* Recursively attach all DLLs this one depends on */
881 for ( i
= 0; i
< wm
->nDeps
; i
++ )
883 if (!wm
->deps
[i
]) continue;
884 if ((status
= process_attach( wm
->deps
[i
], lpReserved
)) != STATUS_SUCCESS
) break;
887 /* Call DLL entry point */
888 if (status
== STATUS_SUCCESS
)
890 WINE_MODREF
*prev
= current_modref
;
892 if (MODULE_InitDLL( wm
, DLL_PROCESS_ATTACH
, lpReserved
))
894 wm
->ldr
.Flags
|= LDR_PROCESS_ATTACHED
;
898 /* point to the name so LdrInitializeThunk can print it */
899 last_failed_modref
= wm
;
900 WARN("Initialization of %s failed\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
901 status
= STATUS_DLL_INIT_FAILED
;
903 current_modref
= prev
;
906 if (!wm
->ldr
.InInitializationOrderModuleList
.Flink
)
907 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
,
908 &wm
->ldr
.InInitializationOrderModuleList
);
910 /* Remove recursion flag */
911 wm
->ldr
.Flags
&= ~LDR_LOAD_IN_PROGRESS
;
913 TRACE("(%s,%p) - END\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
918 /**********************************************************************
919 * attach_implicitly_loaded_dlls
921 * Attach to the (builtin) dlls that have been implicitly loaded because
922 * of a dependency at the Unix level, but not imported at the Win32 level.
924 static void attach_implicitly_loaded_dlls( LPVOID reserved
)
928 PLIST_ENTRY mark
, entry
;
930 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
931 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
933 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
935 if (mod
->Flags
& (LDR_LOAD_IN_PROGRESS
| LDR_PROCESS_ATTACHED
)) continue;
936 TRACE( "found implicitly loaded %s, attaching to it\n",
937 debugstr_w(mod
->BaseDllName
.Buffer
));
938 mod
->LoadCount
= -1; /* we can't unload it anyway */
939 process_attach( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
), reserved
);
940 break; /* restart the search from the start */
942 if (entry
== mark
) break; /* nothing found */
947 /*************************************************************************
950 * Send DLL process detach notifications. See the comment about calling
951 * sequence at process_attach. Unless the bForceDetach flag
952 * is set, only DLLs with zero refcount are notified.
954 static void process_detach( BOOL bForceDetach
, LPVOID lpReserved
)
956 PLIST_ENTRY mark
, entry
;
959 RtlEnterCriticalSection( &loader_section
);
960 if (bForceDetach
) process_detaching
= 1;
961 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
964 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
966 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
967 InInitializationOrderModuleList
);
968 /* Check whether to detach this DLL */
969 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
971 if ( mod
->LoadCount
&& !bForceDetach
)
974 /* Call detach notification */
975 mod
->Flags
&= ~LDR_PROCESS_ATTACHED
;
976 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
977 DLL_PROCESS_DETACH
, lpReserved
);
979 /* Restart at head of WINE_MODREF list, as entries might have
980 been added and/or removed while performing the call ... */
983 } while (entry
!= mark
);
985 RtlLeaveCriticalSection( &loader_section
);
988 /*************************************************************************
989 * MODULE_DllThreadAttach
991 * Send DLL thread attach notifications. These are sent in the
992 * reverse sequence of process detach notification.
995 NTSTATUS
MODULE_DllThreadAttach( LPVOID lpReserved
)
997 PLIST_ENTRY mark
, entry
;
1001 /* don't do any attach calls if process is exiting */
1002 if (process_detaching
) return STATUS_SUCCESS
;
1003 /* FIXME: there is still a race here */
1005 RtlEnterCriticalSection( &loader_section
);
1007 if ((status
= alloc_thread_tls()) != STATUS_SUCCESS
) goto done
;
1009 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1010 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1012 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
1013 InInitializationOrderModuleList
);
1014 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1016 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
1019 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
1020 DLL_THREAD_ATTACH
, lpReserved
);
1024 RtlLeaveCriticalSection( &loader_section
);
1028 /******************************************************************
1029 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1032 NTSTATUS WINAPI
LdrDisableThreadCalloutsForDll(HMODULE hModule
)
1035 NTSTATUS ret
= STATUS_SUCCESS
;
1037 RtlEnterCriticalSection( &loader_section
);
1039 wm
= get_modref( hModule
);
1040 if (!wm
|| wm
->ldr
.TlsIndex
!= -1)
1041 ret
= STATUS_DLL_NOT_FOUND
;
1043 wm
->ldr
.Flags
|= LDR_NO_DLL_CALLS
;
1045 RtlLeaveCriticalSection( &loader_section
);
1050 /******************************************************************
1051 * LdrFindEntryForAddress (NTDLL.@)
1053 * The loader_section must be locked while calling this function
1055 NTSTATUS WINAPI
LdrFindEntryForAddress(const void* addr
, PLDR_MODULE
* pmod
)
1057 PLIST_ENTRY mark
, entry
;
1060 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
1061 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1063 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
1064 if ((const void *)mod
->BaseAddress
<= addr
&&
1065 (const char *)addr
< (char*)mod
->BaseAddress
+ mod
->SizeOfImage
)
1068 return STATUS_SUCCESS
;
1070 if ((const void *)mod
->BaseAddress
> addr
) break;
1072 return STATUS_NO_MORE_ENTRIES
;
1075 /******************************************************************
1076 * LdrLockLoaderLock (NTDLL.@)
1078 * Note: flags are not implemented.
1079 * Flag 0x01 is used to raise exceptions on errors.
1080 * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
1082 NTSTATUS WINAPI
LdrLockLoaderLock( ULONG flags
, ULONG
*result
, ULONG
*magic
)
1084 if (flags
) FIXME( "flags %lx not supported\n", flags
);
1086 if (result
) *result
= 1;
1087 if (!magic
) return STATUS_INVALID_PARAMETER_3
;
1088 RtlEnterCriticalSection( &loader_section
);
1089 *magic
= GetCurrentThreadId();
1090 return STATUS_SUCCESS
;
1094 /******************************************************************
1095 * LdrUnlockLoaderUnlock (NTDLL.@)
1097 NTSTATUS WINAPI
LdrUnlockLoaderLock( ULONG flags
, ULONG magic
)
1101 if (magic
!= GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2
;
1102 RtlLeaveCriticalSection( &loader_section
);
1104 return STATUS_SUCCESS
;
1108 /******************************************************************
1109 * LdrGetDllHandle (NTDLL.@)
1111 NTSTATUS WINAPI
LdrGetDllHandle(ULONG x
, ULONG y
, const UNICODE_STRING
*name
, HMODULE
*base
)
1113 NTSTATUS status
= STATUS_DLL_NOT_FOUND
;
1114 WCHAR dllname
[MAX_PATH
+4], *p
;
1116 PLIST_ENTRY mark
, entry
;
1119 if (x
!= 0 || y
!= 0)
1120 FIXME("Unknown behavior, please report\n");
1122 /* Append .DLL to name if no extension present */
1123 if (!(p
= strrchrW( name
->Buffer
, '.')) || strchrW( p
, '/' ) || strchrW( p
, '\\'))
1125 if (name
->Length
>= MAX_PATH
) return STATUS_NAME_TOO_LONG
;
1126 strcpyW( dllname
, name
->Buffer
);
1127 strcatW( dllname
, dllW
);
1128 RtlInitUnicodeString( &str
, dllname
);
1132 RtlEnterCriticalSection( &loader_section
);
1136 if (RtlEqualUnicodeString( name
, &cached_modref
->ldr
.FullDllName
, TRUE
) ||
1137 RtlEqualUnicodeString( name
, &cached_modref
->ldr
.BaseDllName
, TRUE
))
1139 *base
= cached_modref
->ldr
.BaseAddress
;
1140 status
= STATUS_SUCCESS
;
1145 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
1146 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1148 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
1150 if (RtlEqualUnicodeString( name
, &mod
->FullDllName
, TRUE
) ||
1151 RtlEqualUnicodeString( name
, &mod
->BaseDllName
, TRUE
))
1153 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
1154 *base
= mod
->BaseAddress
;
1155 status
= STATUS_SUCCESS
;
1160 RtlLeaveCriticalSection( &loader_section
);
1161 TRACE("%lx %lx %s -> %p\n", x
, y
, debugstr_us(name
), status
? NULL
: *base
);
1166 /******************************************************************
1167 * LdrGetProcedureAddress (NTDLL.@)
1169 NTSTATUS WINAPI
LdrGetProcedureAddress(HMODULE module
, const ANSI_STRING
*name
,
1170 ULONG ord
, PVOID
*address
)
1172 IMAGE_EXPORT_DIRECTORY
*exports
;
1174 NTSTATUS ret
= STATUS_PROCEDURE_NOT_FOUND
;
1176 RtlEnterCriticalSection( &loader_section
);
1178 /* check if the module itself is invalid to return the proper error */
1179 if (!get_modref( module
)) ret
= STATUS_DLL_NOT_FOUND
;
1180 else if ((exports
= RtlImageDirectoryEntryToData( module
, TRUE
,
1181 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
1183 void *proc
= name
? find_named_export( module
, exports
, exp_size
, name
->Buffer
, -1 )
1184 : find_ordinal_export( module
, exports
, exp_size
, ord
- exports
->Base
);
1188 ret
= STATUS_SUCCESS
;
1192 RtlLeaveCriticalSection( &loader_section
);
1197 /***********************************************************************
1198 * get_builtin_fullname
1200 * Build the full pathname for a builtin dll.
1202 static WCHAR
*get_builtin_fullname( const WCHAR
*path
, const char *filename
)
1204 static const WCHAR soW
[] = {'.','s','o',0};
1205 WCHAR
*p
, *fullname
;
1206 size_t i
, len
= strlen(filename
);
1208 /* check if path can correspond to the dll we have */
1209 if (path
&& (p
= strrchrW( path
, '\\' )))
1212 for (i
= 0; i
< len
; i
++)
1213 if (tolowerW(p
[i
]) != tolowerW( (WCHAR
)filename
[i
]) ) break;
1214 if (i
== len
&& (!p
[len
] || !strcmpiW( p
+ len
, soW
)))
1216 /* the filename matches, use path as the full path */
1218 if ((fullname
= RtlAllocateHeap( GetProcessHeap(), 0, (len
+ 1) * sizeof(WCHAR
) )))
1220 memcpy( fullname
, path
, len
* sizeof(WCHAR
) );
1227 if ((fullname
= RtlAllocateHeap( GetProcessHeap(), 0,
1228 system_dir
.MaximumLength
+ (len
+ 1) * sizeof(WCHAR
) )))
1230 memcpy( fullname
, system_dir
.Buffer
, system_dir
.Length
);
1231 p
= fullname
+ system_dir
.Length
/ sizeof(WCHAR
);
1232 if (p
> fullname
&& p
[-1] != '\\') *p
++ = '\\';
1233 ascii_to_unicode( p
, filename
, len
+ 1 );
1239 /***********************************************************************
1240 * load_builtin_callback
1242 * Load a library in memory; callback function for wine_dll_register
1244 static void load_builtin_callback( void *module
, const char *filename
)
1246 static const WCHAR emptyW
[1];
1248 IMAGE_NT_HEADERS
*nt
;
1251 const WCHAR
*load_path
;
1255 ERR("could not map image for %s\n", filename
? filename
: "main exe" );
1258 if (!(nt
= RtlImageNtHeader( module
)))
1260 ERR( "bad module for %s\n", filename
? filename
: "main exe" );
1261 builtin_load_info
->status
= STATUS_INVALID_IMAGE_FORMAT
;
1265 NtAllocateVirtualMemory( NtCurrentProcess(), &addr
, 0, &nt
->OptionalHeader
.SizeOfImage
,
1266 MEM_SYSTEM
| MEM_IMAGE
, PAGE_EXECUTE_WRITECOPY
);
1267 if (!(nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
))
1269 /* if we already have an executable, ignore this one */
1270 if (!NtCurrentTeb()->Peb
->ImageBaseAddress
)
1272 NtCurrentTeb()->Peb
->ImageBaseAddress
= module
;
1273 return; /* don't create the modref here, will be done later on */
1277 /* create the MODREF */
1279 if (!(fullname
= get_builtin_fullname( builtin_load_info
->filename
, filename
)))
1281 ERR( "can't load %s\n", filename
);
1282 builtin_load_info
->status
= STATUS_NO_MEMORY
;
1286 wm
= alloc_module( module
, fullname
);
1287 RtlFreeHeap( GetProcessHeap(), 0, fullname
);
1290 ERR( "can't load %s\n", filename
);
1291 builtin_load_info
->status
= STATUS_NO_MEMORY
;
1294 wm
->ldr
.Flags
|= LDR_WINE_INTERNAL
;
1298 load_path
= builtin_load_info
->load_path
;
1299 if (!load_path
) load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1300 if (!load_path
) load_path
= emptyW
;
1301 if (fixup_imports( wm
, load_path
) != STATUS_SUCCESS
)
1303 /* the module has only be inserted in the load & memory order lists */
1304 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
1305 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
1306 /* FIXME: free the modref */
1307 builtin_load_info
->status
= STATUS_DLL_NOT_FOUND
;
1310 builtin_load_info
->wm
= wm
;
1311 TRACE( "loaded %s %p %p\n", filename
, wm
, module
);
1313 /* send the DLL load event */
1315 SERVER_START_REQ( load_dll
)
1319 req
->size
= nt
->OptionalHeader
.SizeOfImage
;
1320 req
->dbg_offset
= nt
->FileHeader
.PointerToSymbolTable
;
1321 req
->dbg_size
= nt
->FileHeader
.NumberOfSymbols
;
1322 req
->name
= &wm
->ldr
.FullDllName
.Buffer
;
1323 wine_server_add_data( req
, wm
->ldr
.FullDllName
.Buffer
, wm
->ldr
.FullDllName
.Length
);
1324 wine_server_call( req
);
1328 /* setup relay debugging entry points */
1329 if (TRACE_ON(relay
)) RELAY_SetupDLL( module
);
1333 /******************************************************************************
1334 * load_native_dll (internal)
1336 static NTSTATUS
load_native_dll( LPCWSTR load_path
, LPCWSTR name
, HANDLE file
,
1337 DWORD flags
, WINE_MODREF
** pwm
)
1341 OBJECT_ATTRIBUTES attr
;
1343 IMAGE_NT_HEADERS
*nt
;
1348 TRACE( "loading %s\n", debugstr_w(name
) );
1350 attr
.Length
= sizeof(attr
);
1351 attr
.RootDirectory
= 0;
1352 attr
.ObjectName
= NULL
;
1353 attr
.Attributes
= 0;
1354 attr
.SecurityDescriptor
= NULL
;
1355 attr
.SecurityQualityOfService
= NULL
;
1358 status
= NtCreateSection( &mapping
, STANDARD_RIGHTS_REQUIRED
| SECTION_QUERY
| SECTION_MAP_READ
,
1359 &attr
, &size
, 0, SEC_IMAGE
, file
);
1360 if (status
!= STATUS_SUCCESS
) return status
;
1363 status
= NtMapViewOfSection( mapping
, NtCurrentProcess(),
1364 &module
, 0, 0, &size
, &len
, ViewShare
, 0, PAGE_READONLY
);
1366 if (status
!= STATUS_SUCCESS
) return status
;
1368 /* create the MODREF */
1370 if (!(wm
= alloc_module( module
, name
))) return STATUS_NO_MEMORY
;
1374 if (!(flags
& DONT_RESOLVE_DLL_REFERENCES
))
1376 if ((status
= fixup_imports( wm
, load_path
)) != STATUS_SUCCESS
)
1378 /* the module has only be inserted in the load & memory order lists */
1379 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
1380 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
1382 /* FIXME: there are several more dangling references
1383 * left. Including dlls loaded by this dll before the
1384 * failed one. Unrolling is rather difficult with the
1385 * current structure and we can leave them lying
1386 * around with no problems, so we don't care.
1387 * As these might reference our wm, we don't free it.
1392 else wm
->ldr
.Flags
|= LDR_DONT_RESOLVE_REFS
;
1394 /* send DLL load event */
1396 nt
= RtlImageNtHeader( module
);
1398 /* don't keep the file open if the mapping is from removable media */
1399 if (!VIRTUAL_HasMapping( module
)) file
= 0;
1401 SERVER_START_REQ( load_dll
)
1405 req
->size
= nt
->OptionalHeader
.SizeOfImage
;
1406 req
->dbg_offset
= nt
->FileHeader
.PointerToSymbolTable
;
1407 req
->dbg_size
= nt
->FileHeader
.NumberOfSymbols
;
1408 req
->name
= &wm
->ldr
.FullDllName
.Buffer
;
1409 wine_server_add_data( req
, wm
->ldr
.FullDllName
.Buffer
, wm
->ldr
.FullDllName
.Length
);
1410 wine_server_call( req
);
1414 if (TRACE_ON(snoop
)) SNOOP_SetupDLL( module
);
1416 TRACE_(loaddll
)( " Loaded module %s : native\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
) );
1419 return STATUS_SUCCESS
;
1423 /***********************************************************************
1426 static NTSTATUS
load_builtin_dll( LPCWSTR load_path
, LPCWSTR path
, HANDLE file
,
1427 DWORD flags
, WINE_MODREF
** pwm
)
1429 char error
[256], dllname
[MAX_PATH
];
1431 const WCHAR
*name
, *p
;
1433 void *handle
= NULL
;
1434 struct builtin_load_info info
, *prev_info
;
1436 /* Fix the name in case we have a full path and extension */
1438 if ((p
= strrchrW( name
, '\\' ))) name
= p
+ 1;
1439 if ((p
= strrchrW( name
, '/' ))) name
= p
+ 1;
1441 /* load_library will modify info.status. Note also that load_library can be
1442 * called several times, if the .so file we're loading has dependencies.
1443 * info.status will gather all the errors we may get while loading all these
1446 info
.load_path
= load_path
;
1447 info
.filename
= NULL
;
1448 info
.status
= STATUS_SUCCESS
;
1451 if (file
) /* we have a real file, try to load it */
1453 UNICODE_STRING nt_name
;
1454 ANSI_STRING unix_name
;
1456 if (!RtlDosPathNameToNtPathName_U( path
, &nt_name
, NULL
, NULL
))
1457 return STATUS_DLL_NOT_FOUND
;
1459 if (!wine_nt_to_unix_file_name( &nt_name
, &unix_name
, FILE_OPEN
, FALSE
))
1462 prev_info
= builtin_load_info
;
1463 info
.filename
= nt_name
.Buffer
+ 4; /* skip \??\ */
1464 builtin_load_info
= &info
;
1465 handle
= wine_dlopen( unix_name
.Buffer
, RTLD_NOW
, error
, sizeof(error
) );
1466 builtin_load_info
= prev_info
;
1467 RtlFreeHeap( GetProcessHeap(), 0, unix_name
.Buffer
);
1469 RtlFreeUnicodeString( &nt_name
);
1473 /* we don't want to depend on the current codepage here */
1474 len
= strlenW( name
) + 1;
1475 if (len
>= sizeof(dllname
)) return STATUS_NAME_TOO_LONG
;
1476 for (i
= 0; i
< len
; i
++)
1478 if (name
[i
] > 127) return STATUS_DLL_NOT_FOUND
;
1479 dllname
[i
] = (char)name
[i
];
1480 if (dllname
[i
] >= 'A' && dllname
[i
] <= 'Z') dllname
[i
] += 'a' - 'A';
1483 prev_info
= builtin_load_info
;
1484 builtin_load_info
= &info
;
1485 handle
= wine_dll_load( dllname
, error
, sizeof(error
), &file_exists
);
1486 builtin_load_info
= prev_info
;
1493 /* The file does not exist -> WARN() */
1494 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name
), error
);
1495 return STATUS_DLL_NOT_FOUND
;
1497 /* ERR() for all other errors (missing functions, ...) */
1498 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name
), error
);
1499 return STATUS_PROCEDURE_NOT_FOUND
;
1501 if (info
.status
!= STATUS_SUCCESS
) return info
.status
;
1505 /* The constructor wasn't called, this means the .so is already
1506 * loaded under a different name. We can't support multiple names
1507 * for the same module, so return an error. */
1508 return STATUS_INVALID_IMAGE_FORMAT
;
1511 TRACE_(loaddll
)( "Loaded module %s : builtin\n", debugstr_w(info
.wm
->ldr
.FullDllName
.Buffer
) );
1513 info
.wm
->ldr
.SectionHandle
= handle
;
1514 if (strcmpiW( info
.wm
->ldr
.BaseDllName
.Buffer
, name
))
1516 /* check without .so extension */
1517 static const WCHAR soW
[] = {'.','s','o',0};
1518 DWORD len
= info
.wm
->ldr
.BaseDllName
.Length
/ sizeof(WCHAR
);
1519 if (strncmpiW( info
.wm
->ldr
.BaseDllName
.Buffer
, name
, len
) || strcmpiW( name
+ len
, soW
))
1521 ERR( "loaded .so for %s but got %s instead - probably 16-bit dll\n",
1522 debugstr_w(name
), debugstr_w(info
.wm
->ldr
.BaseDllName
.Buffer
) );
1523 /* wine_dll_unload( handle );*/
1524 return STATUS_INVALID_IMAGE_FORMAT
;
1528 return STATUS_SUCCESS
;
1532 /***********************************************************************
1535 * Find the file (or already loaded module) for a given dll name.
1537 static NTSTATUS
find_dll_file( const WCHAR
*load_path
, const WCHAR
*libname
,
1538 WCHAR
*filename
, ULONG
*size
, WINE_MODREF
**pwm
, HANDLE
*handle
)
1540 OBJECT_ATTRIBUTES attr
;
1542 UNICODE_STRING nt_name
;
1543 WCHAR
*file_part
, *ext
, *dllname
;
1546 /* first append .dll if needed */
1549 if (!(ext
= strrchrW( libname
, '.')) || strchrW( ext
, '/' ) || strchrW( ext
, '\\'))
1551 if (!(dllname
= RtlAllocateHeap( GetProcessHeap(), 0,
1552 (strlenW(libname
) * sizeof(WCHAR
)) + sizeof(dllW
) )))
1553 return STATUS_NO_MEMORY
;
1554 strcpyW( dllname
, libname
);
1555 strcatW( dllname
, dllW
);
1559 nt_name
.Buffer
= NULL
;
1561 if (!contains_path( libname
))
1563 if ((*pwm
= find_basename_module( libname
)) != NULL
) goto found
;
1566 if (RtlDetermineDosPathNameType_U( libname
) == RELATIVE_PATH
)
1568 /* we need to search for it */
1569 len
= RtlDosSearchPath_U( load_path
, libname
, NULL
, *size
, filename
, &file_part
);
1572 if (len
>= *size
) goto overflow
;
1573 if ((*pwm
= find_fullname_module( filename
)) != NULL
) goto found
;
1575 if (!RtlDosPathNameToNtPathName_U( filename
, &nt_name
, NULL
, NULL
))
1577 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1578 return STATUS_NO_MEMORY
;
1580 attr
.Length
= sizeof(attr
);
1581 attr
.RootDirectory
= 0;
1582 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
1583 attr
.ObjectName
= &nt_name
;
1584 attr
.SecurityDescriptor
= NULL
;
1585 attr
.SecurityQualityOfService
= NULL
;
1586 if (NtOpenFile( handle
, GENERIC_READ
, &attr
, &io
, FILE_SHARE_READ
|FILE_SHARE_DELETE
, 0 )) *handle
= 0;
1592 if (!contains_path( libname
))
1594 /* if libname doesn't contain a path at all, we simply return the name as is,
1595 * to be loaded as builtin */
1596 len
= strlenW(libname
) * sizeof(WCHAR
);
1597 if (len
>= *size
) goto overflow
;
1598 strcpyW( filename
, libname
);
1603 /* absolute path name, or relative path name but not found above */
1605 if (!RtlDosPathNameToNtPathName_U( libname
, &nt_name
, &file_part
, NULL
))
1607 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1608 return STATUS_NO_MEMORY
;
1610 len
= nt_name
.Length
- 4*sizeof(WCHAR
); /* for \??\ prefix */
1611 if (len
>= *size
) goto overflow
;
1612 memcpy( filename
, nt_name
.Buffer
+ 4, len
+ sizeof(WCHAR
) );
1613 if (!(*pwm
= find_fullname_module( filename
)))
1615 attr
.Length
= sizeof(attr
);
1616 attr
.RootDirectory
= 0;
1617 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
1618 attr
.ObjectName
= &nt_name
;
1619 attr
.SecurityDescriptor
= NULL
;
1620 attr
.SecurityQualityOfService
= NULL
;
1621 if (NtOpenFile( handle
, GENERIC_READ
, &attr
, &io
, FILE_SHARE_READ
|FILE_SHARE_DELETE
, 0 )) *handle
= 0;
1624 RtlFreeUnicodeString( &nt_name
);
1625 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1626 return STATUS_SUCCESS
;
1629 RtlFreeUnicodeString( &nt_name
);
1630 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1631 *size
= len
+ sizeof(WCHAR
);
1632 return STATUS_BUFFER_TOO_SMALL
;
1636 /***********************************************************************
1637 * load_dll (internal)
1639 * Load a PE style module according to the load order.
1640 * The loader_section must be locked while calling this function.
1642 static NTSTATUS
load_dll( LPCWSTR load_path
, LPCWSTR libname
, DWORD flags
, WINE_MODREF
** pwm
)
1645 enum loadorder_type loadorder
[LOADORDER_NTYPES
];
1649 WINE_MODREF
*main_exe
;
1653 TRACE( "looking for %s in %s\n", debugstr_w(libname
), debugstr_w(load_path
) );
1656 size
= sizeof(buffer
);
1659 nts
= find_dll_file( load_path
, libname
, filename
, &size
, pwm
, &handle
);
1660 if (nts
== STATUS_SUCCESS
) break;
1661 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
1662 if (nts
!= STATUS_BUFFER_TOO_SMALL
) return nts
;
1663 /* grow the buffer and retry */
1664 if (!(filename
= RtlAllocateHeap( GetProcessHeap(), 0, size
))) return STATUS_NO_MEMORY
;
1667 if (*pwm
) /* found already loaded module */
1669 if ((*pwm
)->ldr
.LoadCount
!= -1) (*pwm
)->ldr
.LoadCount
++;
1671 if (((*pwm
)->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
) &&
1672 !(flags
& DONT_RESOLVE_DLL_REFERENCES
))
1674 (*pwm
)->ldr
.Flags
&= ~LDR_DONT_RESOLVE_REFS
;
1675 fixup_imports( *pwm
, load_path
);
1677 TRACE("Found loaded module %s for %s at %p, count=%d\n",
1678 debugstr_w((*pwm
)->ldr
.FullDllName
.Buffer
), debugstr_w(libname
),
1679 (*pwm
)->ldr
.BaseAddress
, (*pwm
)->ldr
.LoadCount
);
1680 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
1681 return STATUS_SUCCESS
;
1684 main_exe
= get_modref( NtCurrentTeb()->Peb
->ImageBaseAddress
);
1685 MODULE_GetLoadOrderW( loadorder
, main_exe
? main_exe
->ldr
.BaseDllName
.Buffer
: NULL
, filename
);
1687 nts
= STATUS_DLL_NOT_FOUND
;
1688 for (i
= 0; i
< LOADORDER_NTYPES
; i
++)
1690 if (loadorder
[i
] == LOADORDER_INVALID
) break;
1692 switch (loadorder
[i
])
1695 TRACE("Trying native dll %s\n", debugstr_w(filename
));
1696 if (!handle
) continue; /* it cannot possibly be loaded */
1697 nts
= load_native_dll( load_path
, filename
, handle
, flags
, pwm
);
1698 if (nts
== STATUS_INVALID_FILE_FOR_SECTION
)
1700 /* not in PE format, maybe it's a builtin */
1701 nts
= load_builtin_dll( load_path
, filename
, handle
, flags
, pwm
);
1705 TRACE("Trying built-in %s\n", debugstr_w(filename
));
1706 nts
= load_builtin_dll( load_path
, filename
, 0, flags
, pwm
);
1709 nts
= STATUS_INTERNAL_ERROR
;
1713 if (nts
== STATUS_SUCCESS
)
1715 /* Initialize DLL just loaded */
1716 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename
),
1717 ((*pwm
)->ldr
.Flags
& LDR_WINE_INTERNAL
) ? "builtin" : "native",
1718 (*pwm
)->ldr
.BaseAddress
);
1719 /* Set the ldr.LoadCount here so that an attach failure will */
1720 /* decrement the dependencies through the MODULE_FreeLibrary call. */
1721 (*pwm
)->ldr
.LoadCount
= 1;
1722 if (handle
) NtClose( handle
);
1723 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
1726 if (nts
!= STATUS_DLL_NOT_FOUND
) break;
1729 WARN("Failed to load module %s; status=%lx\n", debugstr_w(libname
), nts
);
1730 if (handle
) NtClose( handle
);
1731 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
1735 /******************************************************************
1736 * LdrLoadDll (NTDLL.@)
1738 NTSTATUS WINAPI
LdrLoadDll(LPCWSTR path_name
, DWORD flags
,
1739 const UNICODE_STRING
*libname
, HMODULE
* hModule
)
1744 RtlEnterCriticalSection( &loader_section
);
1746 if (!path_name
) path_name
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1747 nts
= load_dll( path_name
, libname
->Buffer
, flags
, &wm
);
1749 if (nts
== STATUS_SUCCESS
&& !(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
))
1751 nts
= process_attach( wm
, NULL
);
1752 if (nts
!= STATUS_SUCCESS
)
1754 LdrUnloadDll(wm
->ldr
.BaseAddress
);
1758 *hModule
= (wm
) ? wm
->ldr
.BaseAddress
: NULL
;
1760 RtlLeaveCriticalSection( &loader_section
);
1764 /******************************************************************
1765 * LdrQueryProcessModuleInformation
1768 NTSTATUS WINAPI
LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi
,
1769 ULONG buf_size
, ULONG
* req_size
)
1771 SYSTEM_MODULE
* sm
= &smi
->Modules
[0];
1772 ULONG size
= sizeof(ULONG
);
1773 NTSTATUS nts
= STATUS_SUCCESS
;
1776 PLIST_ENTRY mark
, entry
;
1779 smi
->ModulesCount
= 0;
1781 RtlEnterCriticalSection( &loader_section
);
1782 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
1783 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1785 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
1786 size
+= sizeof(*sm
);
1787 if (size
<= buf_size
)
1789 sm
->Reserved1
= 0; /* FIXME */
1790 sm
->Reserved2
= 0; /* FIXME */
1791 sm
->ImageBaseAddress
= mod
->BaseAddress
;
1792 sm
->ImageSize
= mod
->SizeOfImage
;
1793 sm
->Flags
= mod
->Flags
;
1794 sm
->Id
= 0; /* FIXME */
1795 sm
->Rank
= 0; /* FIXME */
1796 sm
->Unknown
= 0; /* FIXME */
1798 str
.MaximumLength
= MAXIMUM_FILENAME_LENGTH
;
1799 str
.Buffer
= (char*)sm
->Name
;
1800 RtlUnicodeStringToAnsiString(&str
, &mod
->FullDllName
, FALSE
);
1801 ptr
= strrchr(str
.Buffer
, '\\');
1802 sm
->NameOffset
= (ptr
!= NULL
) ? (ptr
- str
.Buffer
+ 1) : 0;
1804 smi
->ModulesCount
++;
1807 else nts
= STATUS_INFO_LENGTH_MISMATCH
;
1809 RtlLeaveCriticalSection( &loader_section
);
1811 if (req_size
) *req_size
= size
;
1816 /******************************************************************
1817 * LdrShutdownProcess (NTDLL.@)
1820 void WINAPI
LdrShutdownProcess(void)
1823 process_detach( TRUE
, (LPVOID
)1 );
1826 /******************************************************************
1827 * LdrShutdownThread (NTDLL.@)
1830 void WINAPI
LdrShutdownThread(void)
1832 PLIST_ENTRY mark
, entry
;
1837 /* don't do any detach calls if process is exiting */
1838 if (process_detaching
) return;
1839 /* FIXME: there is still a race here */
1841 RtlEnterCriticalSection( &loader_section
);
1843 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1844 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
1846 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
1847 InInitializationOrderModuleList
);
1848 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1850 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
1853 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
1854 DLL_THREAD_DETACH
, NULL
);
1857 RtlLeaveCriticalSection( &loader_section
);
1860 /***********************************************************************
1861 * MODULE_FlushModrefs
1863 * Remove all unused modrefs and call the internal unloading routines
1864 * for the library type.
1866 * The loader_section must be locked while calling this function.
1868 static void MODULE_FlushModrefs(void)
1870 PLIST_ENTRY mark
, entry
, prev
;
1874 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1875 for (entry
= mark
->Blink
; entry
!= mark
; entry
= prev
)
1877 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
1878 InInitializationOrderModuleList
);
1879 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
1881 prev
= entry
->Blink
;
1882 if (mod
->LoadCount
) continue;
1884 RemoveEntryList(&mod
->InLoadOrderModuleList
);
1885 RemoveEntryList(&mod
->InMemoryOrderModuleList
);
1886 RemoveEntryList(&mod
->InInitializationOrderModuleList
);
1888 TRACE(" unloading %s\n", debugstr_w(mod
->FullDllName
.Buffer
));
1889 if (!TRACE_ON(module
))
1890 TRACE_(loaddll
)("Unloaded module %s : %s\n",
1891 debugstr_w(mod
->FullDllName
.Buffer
),
1892 (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) ? "builtin" : "native" );
1894 SERVER_START_REQ( unload_dll
)
1896 req
->base
= mod
->BaseAddress
;
1897 wine_server_call( req
);
1901 NtUnmapViewOfSection( NtCurrentProcess(), mod
->BaseAddress
);
1902 if (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) wine_dll_unload( wm
->ldr
.SectionHandle
);
1903 if (cached_modref
== wm
) cached_modref
= NULL
;
1904 RtlFreeUnicodeString( &mod
->FullDllName
);
1905 RtlFreeHeap( GetProcessHeap(), 0, wm
->deps
);
1906 RtlFreeHeap( GetProcessHeap(), 0, wm
);
1910 /***********************************************************************
1911 * MODULE_DecRefCount
1913 * The loader_section must be locked while calling this function.
1915 static void MODULE_DecRefCount( WINE_MODREF
*wm
)
1919 if ( wm
->ldr
.Flags
& LDR_UNLOAD_IN_PROGRESS
)
1922 if ( wm
->ldr
.LoadCount
<= 0 )
1925 --wm
->ldr
.LoadCount
;
1926 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), wm
->ldr
.LoadCount
);
1928 if ( wm
->ldr
.LoadCount
== 0 )
1930 wm
->ldr
.Flags
|= LDR_UNLOAD_IN_PROGRESS
;
1932 for ( i
= 0; i
< wm
->nDeps
; i
++ )
1934 MODULE_DecRefCount( wm
->deps
[i
] );
1936 wm
->ldr
.Flags
&= ~LDR_UNLOAD_IN_PROGRESS
;
1940 /******************************************************************
1941 * LdrUnloadDll (NTDLL.@)
1945 NTSTATUS WINAPI
LdrUnloadDll( HMODULE hModule
)
1947 NTSTATUS retv
= STATUS_SUCCESS
;
1949 TRACE("(%p)\n", hModule
);
1951 RtlEnterCriticalSection( &loader_section
);
1953 /* if we're stopping the whole process (and forcing the removal of all
1954 * DLLs) the library will be freed anyway
1956 if (!process_detaching
)
1961 if ((wm
= get_modref( hModule
)) != NULL
)
1963 TRACE("(%s) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
1965 /* Recursively decrement reference counts */
1966 MODULE_DecRefCount( wm
);
1968 /* Call process detach notifications */
1969 if ( free_lib_count
<= 1 )
1971 process_detach( FALSE
, NULL
);
1972 MODULE_FlushModrefs();
1978 retv
= STATUS_DLL_NOT_FOUND
;
1983 RtlLeaveCriticalSection( &loader_section
);
1988 /***********************************************************************
1989 * RtlImageNtHeader (NTDLL.@)
1991 PIMAGE_NT_HEADERS WINAPI
RtlImageNtHeader(HMODULE hModule
)
1993 IMAGE_NT_HEADERS
*ret
;
1997 IMAGE_DOS_HEADER
*dos
= (IMAGE_DOS_HEADER
*)hModule
;
2000 if (dos
->e_magic
== IMAGE_DOS_SIGNATURE
)
2002 ret
= (IMAGE_NT_HEADERS
*)((char *)dos
+ dos
->e_lfanew
);
2003 if (ret
->Signature
!= IMAGE_NT_SIGNATURE
) ret
= NULL
;
2015 /******************************************************************
2016 * LdrInitializeThunk (NTDLL.@)
2018 * FIXME: the arguments are not correct, main_file is a Wine invention.
2020 void WINAPI
LdrInitializeThunk( HANDLE main_file
, ULONG unknown2
, ULONG unknown3
, ULONG unknown4
)
2025 PEB
*peb
= NtCurrentTeb()->Peb
;
2026 IMAGE_NT_HEADERS
*nt
= RtlImageNtHeader( peb
->ImageBaseAddress
);
2028 /* allocate the modref for the main exe (if not already done) */
2029 if (!(wm
= get_modref( peb
->ImageBaseAddress
)) &&
2030 !(wm
= alloc_module( peb
->ImageBaseAddress
, peb
->ProcessParameters
->ImagePathName
.Buffer
)))
2032 status
= STATUS_NO_MEMORY
;
2035 wm
->ldr
.LoadCount
= -1; /* can't unload main exe */
2036 wm
->ldr
.Flags
&= ~LDR_DONT_RESOLVE_REFS
;
2038 peb
->ProcessParameters
->ImagePathName
= wm
->ldr
.FullDllName
;
2039 version_init( wm
->ldr
.FullDllName
.Buffer
);
2041 /* the main exe needs to be the first in the load order list */
2042 RemoveEntryList( &wm
->ldr
.InLoadOrderModuleList
);
2043 InsertHeadList( &peb
->LdrData
->InLoadOrderModuleList
, &wm
->ldr
.InLoadOrderModuleList
);
2045 /* Install signal handlers; this cannot be done before, since we cannot
2046 * send exceptions to the debugger before the create process event that
2047 * is sent by REQ_INIT_PROCESS_DONE.
2048 * We do need the handlers in place by the time the request is over, so
2049 * we set them up here. If we segfault between here and the server call
2050 * something is very wrong... */
2051 if (!SIGNAL_Init()) exit(1);
2053 /* Signal the parent process to continue */
2054 SERVER_START_REQ( init_process_done
)
2056 req
->module
= peb
->ImageBaseAddress
;
2057 req
->module_size
= wm
->ldr
.SizeOfImage
;
2058 req
->entry
= (char *)peb
->ImageBaseAddress
+ nt
->OptionalHeader
.AddressOfEntryPoint
;
2059 /* API requires a double indirection */
2060 req
->name
= &wm
->ldr
.FullDllName
.Buffer
;
2061 req
->exe_file
= main_file
;
2062 req
->gui
= (nt
->OptionalHeader
.Subsystem
!= IMAGE_SUBSYSTEM_WINDOWS_CUI
);
2063 wine_server_add_data( req
, wm
->ldr
.FullDllName
.Buffer
, wm
->ldr
.FullDllName
.Length
);
2064 wine_server_call( req
);
2068 if (main_file
) NtClose( main_file
); /* we no longer need it */
2070 RtlEnterCriticalSection( &loader_section
);
2072 load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
2073 if ((status
= fixup_imports( wm
, load_path
)) != STATUS_SUCCESS
) goto error
;
2074 if ((status
= alloc_process_tls()) != STATUS_SUCCESS
) goto error
;
2075 if ((status
= alloc_thread_tls()) != STATUS_SUCCESS
) goto error
;
2076 if ((status
= process_attach( wm
, (LPVOID
)1 )) != STATUS_SUCCESS
)
2078 if (last_failed_modref
)
2079 ERR( "%s failed to initialize, aborting\n", debugstr_w(last_failed_modref
->ldr
.BaseDllName
.Buffer
) + 1 );
2082 attach_implicitly_loaded_dlls( (LPVOID
)1 );
2084 RtlLeaveCriticalSection( &loader_section
);
2086 if (nt
->FileHeader
.Characteristics
& IMAGE_FILE_LARGE_ADDRESS_AWARE
) VIRTUAL_UseLargeAddressSpace();
2090 ERR( "Main exe initialization for %s failed, status %lx\n",
2091 debugstr_w(peb
->ProcessParameters
->ImagePathName
.Buffer
), status
);
2096 /***********************************************************************
2097 * RtlImageDirectoryEntryToData (NTDLL.@)
2099 PVOID WINAPI
RtlImageDirectoryEntryToData( HMODULE module
, BOOL image
, WORD dir
, ULONG
*size
)
2101 const IMAGE_NT_HEADERS
*nt
;
2104 if ((ULONG_PTR
)module
& 1) /* mapped as data file */
2106 module
= (HMODULE
)((ULONG_PTR
)module
& ~1);
2109 if (!(nt
= RtlImageNtHeader( module
))) return NULL
;
2110 if (dir
>= nt
->OptionalHeader
.NumberOfRvaAndSizes
) return NULL
;
2111 if (!(addr
= nt
->OptionalHeader
.DataDirectory
[dir
].VirtualAddress
)) return NULL
;
2112 *size
= nt
->OptionalHeader
.DataDirectory
[dir
].Size
;
2113 if (image
|| addr
< nt
->OptionalHeader
.SizeOfHeaders
) return (char *)module
+ addr
;
2115 /* not mapped as image, need to find the section containing the virtual address */
2116 return RtlImageRvaToVa( nt
, module
, addr
, NULL
);
2120 /***********************************************************************
2121 * RtlImageRvaToSection (NTDLL.@)
2123 PIMAGE_SECTION_HEADER WINAPI
RtlImageRvaToSection( const IMAGE_NT_HEADERS
*nt
,
2124 HMODULE module
, DWORD rva
)
2127 const IMAGE_SECTION_HEADER
*sec
;
2129 sec
= (const IMAGE_SECTION_HEADER
*)((const char*)&nt
->OptionalHeader
+
2130 nt
->FileHeader
.SizeOfOptionalHeader
);
2131 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++, sec
++)
2133 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
2134 return (PIMAGE_SECTION_HEADER
)sec
;
2140 /***********************************************************************
2141 * RtlImageRvaToVa (NTDLL.@)
2143 PVOID WINAPI
RtlImageRvaToVa( const IMAGE_NT_HEADERS
*nt
, HMODULE module
,
2144 DWORD rva
, IMAGE_SECTION_HEADER
**section
)
2146 IMAGE_SECTION_HEADER
*sec
;
2148 if (section
&& *section
) /* try this section first */
2151 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
2154 if (!(sec
= RtlImageRvaToSection( nt
, module
, rva
))) return NULL
;
2156 if (section
) *section
= sec
;
2157 return (char *)module
+ sec
->PointerToRawData
+ (rva
- sec
->VirtualAddress
);
2161 /***********************************************************************
2162 * NtLoadDriver (NTDLL.@)
2163 * ZwLoadDriver (NTDLL.@)
2165 NTSTATUS WINAPI
NtLoadDriver( const UNICODE_STRING
*DriverServiceName
)
2167 FIXME("(%p), stub!\n",DriverServiceName
);
2168 return STATUS_NOT_IMPLEMENTED
;
2172 /***********************************************************************
2173 * NtUnloadDriver (NTDLL.@)
2174 * ZwUnloadDriver (NTDLL.@)
2176 NTSTATUS WINAPI
NtUnloadDriver( const UNICODE_STRING
*DriverServiceName
)
2178 FIXME("(%p), stub!\n",DriverServiceName
);
2179 return STATUS_NOT_IMPLEMENTED
;
2183 /******************************************************************
2186 BOOL WINAPI
DllMain( HINSTANCE inst
, DWORD reason
, LPVOID reserved
)
2188 if (reason
== DLL_PROCESS_ATTACH
) LdrDisableThreadCalloutsForDll( inst
);
2193 /******************************************************************
2194 * __wine_init_windows_dir (NTDLL.@)
2196 * Windows and system dir initialization once kernel32 has been loaded.
2198 void __wine_init_windows_dir( const WCHAR
*windir
, const WCHAR
*sysdir
)
2200 PLIST_ENTRY mark
, entry
;
2203 RtlCreateUnicodeString( &system_dir
, sysdir
);
2205 /* prepend the system dir to the name of the already created modules */
2206 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
2207 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
2209 LDR_MODULE
*mod
= CONTAINING_RECORD( entry
, LDR_MODULE
, InLoadOrderModuleList
);
2211 assert( mod
->Flags
& LDR_WINE_INTERNAL
);
2213 buffer
= RtlAllocateHeap( GetProcessHeap(), 0,
2214 system_dir
.Length
+ mod
->FullDllName
.Length
+ 2*sizeof(WCHAR
) );
2215 if (!buffer
) continue;
2216 strcpyW( buffer
, system_dir
.Buffer
);
2217 p
= buffer
+ strlenW( buffer
);
2218 if (p
> buffer
&& p
[-1] != '\\') *p
++ = '\\';
2219 strcpyW( p
, mod
->FullDllName
.Buffer
);
2220 RtlInitUnicodeString( &mod
->FullDllName
, buffer
);
2221 RtlInitUnicodeString( &mod
->BaseDllName
, p
);
2226 /***********************************************************************
2227 * __wine_process_init
2229 void __wine_process_init( int argc
, char *argv
[] )
2231 static const WCHAR kernel32W
[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
2235 ANSI_STRING func_name
;
2236 void (* DECLSPEC_NORETURN init_func
)(void);
2237 extern mode_t FILE_umask
;
2241 /* retrieve current umask */
2242 FILE_umask
= umask(0777);
2243 umask( FILE_umask
);
2245 /* setup the load callback and create ntdll modref */
2246 wine_dll_set_callback( load_builtin_callback
);
2248 if ((status
= load_builtin_dll( NULL
, kernel32W
, 0, 0, &wm
)) != STATUS_SUCCESS
)
2250 MESSAGE( "wine: could not load kernel32.dll, status %lx\n", status
);
2253 RtlInitAnsiString( &func_name
, "__wine_kernel_init" );
2254 if ((status
= LdrGetProcedureAddress( wm
->ldr
.BaseAddress
, &func_name
,
2255 0, (void **)&init_func
)) != STATUS_SUCCESS
)
2257 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %lx\n", status
);