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
;
84 static struct builtin_load_info default_load_info
;
85 static struct builtin_load_info
*builtin_load_info
= &default_load_info
;
87 static UINT tls_module_count
; /* number of modules with TLS directory */
88 static UINT tls_total_size
; /* total size of TLS storage */
89 static const IMAGE_TLS_DIRECTORY
**tls_dirs
; /* array of TLS directories */
91 UNICODE_STRING system_dir
= { 0, 0, NULL
}; /* system directory */
93 static RTL_CRITICAL_SECTION loader_section
;
94 static RTL_CRITICAL_SECTION_DEBUG critsect_debug
=
96 0, 0, &loader_section
,
97 { &critsect_debug
.ProcessLocksList
, &critsect_debug
.ProcessLocksList
},
98 0, 0, { (DWORD_PTR
)(__FILE__
": loader_section") }
100 static RTL_CRITICAL_SECTION loader_section
= { &critsect_debug
, -1, 0, 0, 0, 0 };
102 static WINE_MODREF
*cached_modref
;
103 static WINE_MODREF
*current_modref
;
104 static WINE_MODREF
*last_failed_modref
;
106 static NTSTATUS
load_dll( LPCWSTR load_path
, LPCWSTR libname
, DWORD flags
, WINE_MODREF
** pwm
);
107 static FARPROC
find_named_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
108 DWORD exp_size
, const char *name
, int hint
);
110 /* convert PE image VirtualAddress to Real Address */
111 inline static void *get_rva( HMODULE module
, DWORD va
)
113 return (void *)((char *)module
+ va
);
116 /* check whether the file name contains a path */
117 inline static int contains_path( LPCWSTR name
)
119 return ((*name
&& (name
[1] == ':')) || strchrW(name
, '/') || strchrW(name
, '\\'));
122 /* convert from straight ASCII to Unicode without depending on the current codepage */
123 inline static void ascii_to_unicode( WCHAR
*dst
, const char *src
, size_t len
)
125 while (len
--) *dst
++ = (unsigned char)*src
++;
129 /*************************************************************************
130 * call_dll_entry_point
132 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
133 * their entry point, so we need a small asm wrapper.
136 extern BOOL
call_dll_entry_point( DLLENTRYPROC proc
, void *module
, UINT reason
, void *reserved
);
137 __ASM_GLOBAL_FUNC(call_dll_entry_point
,
145 "movl 8(%ebp),%eax\n\t"
147 "leal -4(%ebp),%esp\n\t"
152 static inline BOOL
call_dll_entry_point( DLLENTRYPROC proc
, void *module
,
153 UINT reason
, void *reserved
)
155 return proc( module
, reason
, reserved
);
157 #endif /* __i386__ */
161 /*************************************************************************
164 * Entry point for stub functions.
166 static void stub_entry_point( const char *dll
, const char *name
, ... )
168 EXCEPTION_RECORD rec
;
170 rec
.ExceptionCode
= EXCEPTION_WINE_STUB
;
171 rec
.ExceptionFlags
= EH_NONCONTINUABLE
;
172 rec
.ExceptionRecord
= NULL
;
174 rec
.ExceptionAddress
= __builtin_return_address(0);
176 rec
.ExceptionAddress
= *((void **)&dll
- 1);
178 rec
.NumberParameters
= 2;
179 rec
.ExceptionInformation
[0] = (ULONG_PTR
)dll
;
180 rec
.ExceptionInformation
[1] = (ULONG_PTR
)name
;
181 for (;;) RtlRaiseException( &rec
);
185 #include "pshpack1.h"
188 BYTE popl_eax
; /* popl %eax */
189 BYTE pushl1
; /* pushl $name */
191 BYTE pushl2
; /* pushl $dll */
193 BYTE pushl_eax
; /* pushl %eax */
194 BYTE jmp
; /* jmp stub_entry_point */
199 /*************************************************************************
202 * Allocate a stub entry point.
204 static ULONG_PTR
allocate_stub( const char *dll
, const char *name
)
206 #define MAX_SIZE 65536
207 static struct stub
*stubs
;
208 static unsigned int nb_stubs
;
211 if (nb_stubs
>= MAX_SIZE
/ sizeof(*stub
)) return 0xdeadbeef;
215 ULONG size
= MAX_SIZE
;
216 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs
, 0, &size
,
217 MEM_COMMIT
, PAGE_EXECUTE_WRITECOPY
) != STATUS_SUCCESS
)
220 stub
= &stubs
[nb_stubs
++];
221 stub
->popl_eax
= 0x58; /* popl %eax */
222 stub
->pushl1
= 0x68; /* pushl $name */
224 stub
->pushl2
= 0x68; /* pushl $dll */
226 stub
->pushl_eax
= 0x50; /* pushl %eax */
227 stub
->jmp
= 0xe9; /* jmp stub_entry_point */
228 stub
->entry
= (BYTE
*)stub_entry_point
- (BYTE
*)(&stub
->entry
+ 1);
229 return (ULONG_PTR
)stub
;
233 static inline ULONG_PTR
allocate_stub( const char *dll
, const char *name
) { return 0xdeadbeef; }
234 #endif /* __i386__ */
237 /*************************************************************************
240 * Looks for the referenced HMODULE in the current process
241 * The loader_section must be locked while calling this function.
243 static WINE_MODREF
*get_modref( HMODULE hmod
)
245 PLIST_ENTRY mark
, entry
;
248 if (cached_modref
&& cached_modref
->ldr
.BaseAddress
== hmod
) return cached_modref
;
250 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
251 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
253 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
254 if (mod
->BaseAddress
== hmod
)
255 return cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
256 if (mod
->BaseAddress
> (void*)hmod
) break;
262 /**********************************************************************
263 * find_basename_module
265 * Find a module from its base name.
266 * The loader_section must be locked while calling this function
268 static WINE_MODREF
*find_basename_module( LPCWSTR name
)
270 PLIST_ENTRY mark
, entry
;
272 if (cached_modref
&& !strcmpiW( name
, cached_modref
->ldr
.BaseDllName
.Buffer
))
273 return cached_modref
;
275 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
276 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
278 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
279 if (!strcmpiW( name
, mod
->BaseDllName
.Buffer
))
281 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
282 return cached_modref
;
289 /**********************************************************************
290 * find_fullname_module
292 * Find a module from its full path name.
293 * The loader_section must be locked while calling this function
295 static WINE_MODREF
*find_fullname_module( LPCWSTR name
)
297 PLIST_ENTRY mark
, entry
;
299 if (cached_modref
&& !strcmpiW( name
, cached_modref
->ldr
.FullDllName
.Buffer
))
300 return cached_modref
;
302 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
303 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
305 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
306 if (!strcmpiW( name
, mod
->FullDllName
.Buffer
))
308 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
309 return cached_modref
;
316 /*************************************************************************
317 * find_forwarded_export
319 * Find the final function pointer for a forwarded function.
320 * The loader_section must be locked while calling this function.
322 static FARPROC
find_forwarded_export( HMODULE module
, const char *forward
)
324 const IMAGE_EXPORT_DIRECTORY
*exports
;
328 const char *end
= strchr(forward
, '.');
331 if (!end
) return NULL
;
332 if ((end
- forward
) * sizeof(WCHAR
) >= sizeof(mod_name
) - sizeof(dllW
)) return NULL
;
333 ascii_to_unicode( mod_name
, forward
, end
- forward
);
334 memcpy( mod_name
+ (end
- forward
), dllW
, sizeof(dllW
) );
336 if (!(wm
= find_basename_module( mod_name
)))
338 ERR("module not found for forward '%s' used by %s\n",
339 forward
, debugstr_w(get_modref(module
)->ldr
.FullDllName
.Buffer
) );
342 if ((exports
= RtlImageDirectoryEntryToData( wm
->ldr
.BaseAddress
, TRUE
,
343 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
344 proc
= find_named_export( wm
->ldr
.BaseAddress
, exports
, exp_size
, end
+ 1, -1 );
348 ERR("function not found for forward '%s' used by %s."
349 " If you are using builtin %s, try using the native one instead.\n",
350 forward
, debugstr_w(get_modref(module
)->ldr
.FullDllName
.Buffer
),
351 debugstr_w(get_modref(module
)->ldr
.BaseDllName
.Buffer
) );
357 /*************************************************************************
358 * find_ordinal_export
360 * Find an exported function by ordinal.
361 * The exports base must have been subtracted from the ordinal already.
362 * The loader_section must be locked while calling this function.
364 static FARPROC
find_ordinal_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
365 DWORD exp_size
, DWORD ordinal
)
368 const DWORD
*functions
= get_rva( module
, exports
->AddressOfFunctions
);
370 if (ordinal
>= exports
->NumberOfFunctions
)
372 TRACE(" ordinal %ld out of range!\n", ordinal
+ exports
->Base
);
375 if (!functions
[ordinal
]) return NULL
;
377 proc
= get_rva( module
, functions
[ordinal
] );
379 /* if the address falls into the export dir, it's a forward */
380 if (((const char *)proc
>= (const char *)exports
) &&
381 ((const char *)proc
< (const char *)exports
+ exp_size
))
382 return find_forwarded_export( module
, (const char *)proc
);
386 const WCHAR
*user
= current_modref
? current_modref
->ldr
.BaseDllName
.Buffer
: NULL
;
387 proc
= SNOOP_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
, user
);
391 const WCHAR
*user
= current_modref
? current_modref
->ldr
.BaseDllName
.Buffer
: NULL
;
392 proc
= RELAY_GetProcAddress( module
, exports
, exp_size
, proc
, ordinal
, user
);
398 /*************************************************************************
401 * Find an exported function by name.
402 * The loader_section must be locked while calling this function.
404 static FARPROC
find_named_export( HMODULE module
, const IMAGE_EXPORT_DIRECTORY
*exports
,
405 DWORD exp_size
, const char *name
, int hint
)
407 const WORD
*ordinals
= get_rva( module
, exports
->AddressOfNameOrdinals
);
408 const DWORD
*names
= get_rva( module
, exports
->AddressOfNames
);
409 int min
= 0, max
= exports
->NumberOfNames
- 1;
411 /* first check the hint */
412 if (hint
>= 0 && hint
<= max
)
414 char *ename
= get_rva( module
, names
[hint
] );
415 if (!strcmp( ename
, name
))
416 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[hint
] );
419 /* then do a binary search */
422 int res
, pos
= (min
+ max
) / 2;
423 char *ename
= get_rva( module
, names
[pos
] );
424 if (!(res
= strcmp( ename
, name
)))
425 return find_ordinal_export( module
, exports
, exp_size
, ordinals
[pos
] );
426 if (res
> 0) max
= pos
- 1;
434 /*************************************************************************
437 * Import the dll specified by the given import descriptor.
438 * The loader_section must be locked while calling this function.
440 static WINE_MODREF
*import_dll( HMODULE module
, const IMAGE_IMPORT_DESCRIPTOR
*descr
, LPCWSTR load_path
)
445 const IMAGE_EXPORT_DIRECTORY
*exports
;
447 const IMAGE_THUNK_DATA
*import_list
;
448 IMAGE_THUNK_DATA
*thunk_list
;
450 const char *name
= get_rva( module
, descr
->Name
);
451 DWORD len
= strlen(name
) + 1;
453 SIZE_T protect_size
= 0;
456 thunk_list
= get_rva( module
, (DWORD
)descr
->FirstThunk
);
457 if (descr
->u
.OriginalFirstThunk
)
458 import_list
= get_rva( module
, (DWORD
)descr
->u
.OriginalFirstThunk
);
460 import_list
= thunk_list
;
462 if (len
* sizeof(WCHAR
) <= sizeof(buffer
))
464 ascii_to_unicode( buffer
, name
, len
);
465 status
= load_dll( load_path
, buffer
, 0, &wmImp
);
467 else /* need to allocate a larger buffer */
469 WCHAR
*ptr
= RtlAllocateHeap( GetProcessHeap(), 0, len
* sizeof(WCHAR
) );
470 if (!ptr
) return NULL
;
471 ascii_to_unicode( ptr
, name
, len
);
472 status
= load_dll( load_path
, ptr
, 0, &wmImp
);
473 RtlFreeHeap( GetProcessHeap(), 0, ptr
);
478 if (status
== STATUS_DLL_NOT_FOUND
)
479 ERR("Library %s (which is needed by %s) not found\n",
480 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
));
482 ERR("Loading library %s (which is needed by %s) failed (error %lx).\n",
483 name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
), status
);
487 /* unprotect the import address table since it can be located in
488 * readonly section */
489 while (import_list
[protect_size
].u1
.Ordinal
) protect_size
++;
490 protect_base
= thunk_list
;
491 protect_size
*= sizeof(*thunk_list
);
492 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
,
493 &protect_size
, PAGE_WRITECOPY
, &protect_old
);
495 imp_mod
= wmImp
->ldr
.BaseAddress
;
496 exports
= RtlImageDirectoryEntryToData( imp_mod
, TRUE
, IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
);
500 /* set all imported function to deadbeef */
501 while (import_list
->u1
.Ordinal
)
503 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
505 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
506 WARN("No implementation for %s.%d", name
, ordinal
);
507 thunk_list
->u1
.Function
= allocate_stub( name
, (const char *)ordinal
);
511 IMAGE_IMPORT_BY_NAME
*pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
512 WARN("No implementation for %s.%s", name
, pe_name
->Name
);
513 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
515 WARN(" imported from %s, allocating stub %p\n",
516 debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
517 (void *)thunk_list
->u1
.Function
);
524 while (import_list
->u1
.Ordinal
)
526 if (IMAGE_SNAP_BY_ORDINAL(import_list
->u1
.Ordinal
))
528 int ordinal
= IMAGE_ORDINAL(import_list
->u1
.Ordinal
);
530 thunk_list
->u1
.Function
= (ULONG_PTR
)find_ordinal_export( imp_mod
, exports
, exp_size
,
531 ordinal
- exports
->Base
);
532 if (!thunk_list
->u1
.Function
)
534 thunk_list
->u1
.Function
= allocate_stub( name
, (const char *)ordinal
);
535 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
536 name
, ordinal
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
537 (void *)thunk_list
->u1
.Function
);
539 TRACE_(imports
)("--- Ordinal %s.%d = %p\n", name
, ordinal
, (void *)thunk_list
->u1
.Function
);
541 else /* import by name */
543 IMAGE_IMPORT_BY_NAME
*pe_name
;
544 pe_name
= get_rva( module
, (DWORD
)import_list
->u1
.AddressOfData
);
545 thunk_list
->u1
.Function
= (ULONG_PTR
)find_named_export( imp_mod
, exports
, exp_size
,
546 (const char*)pe_name
->Name
, pe_name
->Hint
);
547 if (!thunk_list
->u1
.Function
)
549 thunk_list
->u1
.Function
= allocate_stub( name
, (const char*)pe_name
->Name
);
550 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
551 name
, pe_name
->Name
, debugstr_w(current_modref
->ldr
.FullDllName
.Buffer
),
552 (void *)thunk_list
->u1
.Function
);
554 TRACE_(imports
)("--- %s %s.%d = %p\n",
555 pe_name
->Name
, name
, pe_name
->Hint
, (void *)thunk_list
->u1
.Function
);
562 /* restore old protection of the import address table */
563 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base
, &protect_size
, protect_old
, NULL
);
568 /****************************************************************
571 * Fixup all imports of a given module.
572 * The loader_section must be locked while calling this function.
574 static NTSTATUS
fixup_imports( WINE_MODREF
*wm
, LPCWSTR load_path
)
577 const IMAGE_IMPORT_DESCRIPTOR
*imports
;
582 if (!(imports
= RtlImageDirectoryEntryToData( wm
->ldr
.BaseAddress
, TRUE
,
583 IMAGE_DIRECTORY_ENTRY_IMPORT
, &size
)))
584 return STATUS_SUCCESS
;
587 while (imports
[nb_imports
].Name
&& imports
[nb_imports
].FirstThunk
) nb_imports
++;
589 if (!nb_imports
) return STATUS_SUCCESS
; /* no imports */
591 /* Allocate module dependency list */
592 wm
->nDeps
= nb_imports
;
593 wm
->deps
= RtlAllocateHeap( GetProcessHeap(), 0, nb_imports
*sizeof(WINE_MODREF
*) );
595 /* load the imported modules. They are automatically
596 * added to the modref list of the process.
598 prev
= current_modref
;
600 status
= STATUS_SUCCESS
;
601 for (i
= 0; i
< nb_imports
; i
++)
603 if (!(wm
->deps
[i
] = import_dll( wm
->ldr
.BaseAddress
, &imports
[i
], load_path
)))
604 status
= STATUS_DLL_NOT_FOUND
;
606 current_modref
= prev
;
611 /*************************************************************************
614 * Allocate a WINE_MODREF structure and add it to the process list
615 * The loader_section must be locked while calling this function.
617 static WINE_MODREF
*alloc_module( HMODULE hModule
, LPCWSTR filename
)
621 const IMAGE_NT_HEADERS
*nt
= RtlImageNtHeader(hModule
);
622 PLIST_ENTRY entry
, mark
;
624 if (!(wm
= RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm
) ))) return NULL
;
629 wm
->ldr
.BaseAddress
= hModule
;
630 wm
->ldr
.EntryPoint
= NULL
;
631 wm
->ldr
.SizeOfImage
= nt
->OptionalHeader
.SizeOfImage
;
633 wm
->ldr
.LoadCount
= 0;
634 wm
->ldr
.TlsIndex
= -1;
635 wm
->ldr
.SectionHandle
= NULL
;
636 wm
->ldr
.CheckSum
= 0;
637 wm
->ldr
.TimeDateStamp
= 0;
639 RtlCreateUnicodeString( &wm
->ldr
.FullDllName
, filename
);
640 if ((p
= strrchrW( wm
->ldr
.FullDllName
.Buffer
, '\\' ))) p
++;
641 else p
= wm
->ldr
.FullDllName
.Buffer
;
642 RtlInitUnicodeString( &wm
->ldr
.BaseDllName
, p
);
644 if (nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
)
646 wm
->ldr
.Flags
|= LDR_IMAGE_IS_DLL
;
647 if (nt
->OptionalHeader
.AddressOfEntryPoint
)
648 wm
->ldr
.EntryPoint
= (char *)hModule
+ nt
->OptionalHeader
.AddressOfEntryPoint
;
651 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
,
652 &wm
->ldr
.InLoadOrderModuleList
);
654 /* insert module in MemoryList, sorted in increasing base addresses */
655 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
656 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
658 if (CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
)->BaseAddress
> wm
->ldr
.BaseAddress
)
661 entry
->Blink
->Flink
= &wm
->ldr
.InMemoryOrderModuleList
;
662 wm
->ldr
.InMemoryOrderModuleList
.Blink
= entry
->Blink
;
663 wm
->ldr
.InMemoryOrderModuleList
.Flink
= entry
;
664 entry
->Blink
= &wm
->ldr
.InMemoryOrderModuleList
;
666 /* wait until init is called for inserting into this list */
667 wm
->ldr
.InInitializationOrderModuleList
.Flink
= NULL
;
668 wm
->ldr
.InInitializationOrderModuleList
.Blink
= NULL
;
673 /*************************************************************************
676 * Allocate the process-wide structure for module TLS storage.
678 static NTSTATUS
alloc_process_tls(void)
680 PLIST_ENTRY mark
, entry
;
682 const IMAGE_TLS_DIRECTORY
*dir
;
685 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
686 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
688 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
689 if (!(dir
= RtlImageDirectoryEntryToData( mod
->BaseAddress
, TRUE
,
690 IMAGE_DIRECTORY_ENTRY_TLS
, &size
)))
692 size
= (dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
) + dir
->SizeOfZeroFill
;
694 tls_total_size
+= size
;
697 if (!tls_module_count
) return STATUS_SUCCESS
;
699 TRACE( "count %u size %u\n", tls_module_count
, tls_total_size
);
701 tls_dirs
= RtlAllocateHeap( GetProcessHeap(), 0, tls_module_count
* sizeof(*tls_dirs
) );
702 if (!tls_dirs
) return STATUS_NO_MEMORY
;
704 for (i
= 0, entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
706 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
707 if (!(dir
= RtlImageDirectoryEntryToData( mod
->BaseAddress
, TRUE
,
708 IMAGE_DIRECTORY_ENTRY_TLS
, &size
)))
711 *(DWORD
*)dir
->AddressOfIndex
= i
;
713 mod
->LoadCount
= -1; /* can't unload it */
716 return STATUS_SUCCESS
;
720 /*************************************************************************
723 * Allocate the per-thread structure for module TLS storage.
725 static NTSTATUS
alloc_thread_tls(void)
731 if (!tls_module_count
) return STATUS_SUCCESS
;
733 if (!(pointers
= RtlAllocateHeap( GetProcessHeap(), 0,
734 tls_module_count
* sizeof(*pointers
) )))
735 return STATUS_NO_MEMORY
;
737 if (!(data
= RtlAllocateHeap( GetProcessHeap(), 0, tls_total_size
)))
739 RtlFreeHeap( GetProcessHeap(), 0, pointers
);
740 return STATUS_NO_MEMORY
;
743 for (i
= 0; i
< tls_module_count
; i
++)
745 const IMAGE_TLS_DIRECTORY
*dir
= tls_dirs
[i
];
746 ULONG size
= dir
->EndAddressOfRawData
- dir
->StartAddressOfRawData
;
748 TRACE( "thread %04lx idx %d: %ld/%ld bytes from %p to %p\n",
749 GetCurrentThreadId(), i
, size
, dir
->SizeOfZeroFill
,
750 (void *)dir
->StartAddressOfRawData
, data
);
753 memcpy( data
, (void *)dir
->StartAddressOfRawData
, size
);
755 memset( data
, 0, dir
->SizeOfZeroFill
);
756 data
+= dir
->SizeOfZeroFill
;
758 NtCurrentTeb()->ThreadLocalStoragePointer
= pointers
;
759 return STATUS_SUCCESS
;
763 /*************************************************************************
766 static void call_tls_callbacks( HMODULE module
, UINT reason
)
768 const IMAGE_TLS_DIRECTORY
*dir
;
769 const PIMAGE_TLS_CALLBACK
*callback
;
772 dir
= RtlImageDirectoryEntryToData( module
, TRUE
, IMAGE_DIRECTORY_ENTRY_TLS
, &dirsize
);
773 if (!dir
|| !dir
->AddressOfCallBacks
) return;
775 for (callback
= (const PIMAGE_TLS_CALLBACK
*)dir
->AddressOfCallBacks
; *callback
; callback
++)
778 DPRINTF("%04lx:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
779 GetCurrentThreadId(), *callback
, module
, reason_names
[reason
] );
780 (*callback
)( module
, reason
, NULL
);
782 DPRINTF("%04lx:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
783 GetCurrentThreadId(), *callback
, module
, reason_names
[reason
] );
788 /*************************************************************************
791 static BOOL
MODULE_InitDLL( WINE_MODREF
*wm
, UINT reason
, LPVOID lpReserved
)
795 DLLENTRYPROC entry
= wm
->ldr
.EntryPoint
;
796 void *module
= wm
->ldr
.BaseAddress
;
798 /* Skip calls for modules loaded with special load flags */
800 if (wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
) return TRUE
;
801 if (wm
->ldr
.TlsIndex
!= -1) call_tls_callbacks( wm
->ldr
.BaseAddress
, reason
);
802 if (!entry
) return TRUE
;
806 size_t len
= min( wm
->ldr
.BaseDllName
.Length
, sizeof(mod_name
)-sizeof(WCHAR
) );
807 memcpy( mod_name
, wm
->ldr
.BaseDllName
.Buffer
, len
);
808 mod_name
[len
/ sizeof(WCHAR
)] = 0;
809 DPRINTF("%04lx:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
810 GetCurrentThreadId(), entry
, module
, debugstr_w(mod_name
),
811 reason_names
[reason
], lpReserved
);
813 else TRACE("(%p %s,%s,%p) - CALL\n", module
, debugstr_w(wm
->ldr
.BaseDllName
.Buffer
),
814 reason_names
[reason
], lpReserved
);
816 retv
= call_dll_entry_point( entry
, module
, reason
, lpReserved
);
818 /* The state of the module list may have changed due to the call
819 to the dll. We cannot assume that this module has not been
822 DPRINTF("%04lx:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
823 GetCurrentThreadId(), entry
, module
, debugstr_w(mod_name
),
824 reason_names
[reason
], lpReserved
, retv
);
825 else TRACE("(%p,%s,%p) - RETURN %d\n", module
, reason_names
[reason
], lpReserved
, retv
);
831 /*************************************************************************
834 * Send the process attach notification to all DLLs the given module
835 * depends on (recursively). This is somewhat complicated due to the fact that
837 * - we have to respect the module dependencies, i.e. modules implicitly
838 * referenced by another module have to be initialized before the module
839 * itself can be initialized
841 * - the initialization routine of a DLL can itself call LoadLibrary,
842 * thereby introducing a whole new set of dependencies (even involving
843 * the 'old' modules) at any time during the whole process
845 * (Note that this routine can be recursively entered not only directly
846 * from itself, but also via LoadLibrary from one of the called initialization
849 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
850 * the process *detach* notifications to be sent in the correct order.
851 * This must not only take into account module dependencies, but also
852 * 'hidden' dependencies created by modules calling LoadLibrary in their
853 * attach notification routine.
855 * The strategy is rather simple: we move a WINE_MODREF to the head of the
856 * list after the attach notification has returned. This implies that the
857 * detach notifications are called in the reverse of the sequence the attach
858 * notifications *returned*.
860 * The loader_section must be locked while calling this function.
862 static NTSTATUS
process_attach( WINE_MODREF
*wm
, LPVOID lpReserved
)
864 NTSTATUS status
= STATUS_SUCCESS
;
867 if (process_detaching
) return status
;
869 /* prevent infinite recursion in case of cyclical dependencies */
870 if ( ( wm
->ldr
.Flags
& LDR_LOAD_IN_PROGRESS
)
871 || ( wm
->ldr
.Flags
& LDR_PROCESS_ATTACHED
) )
874 TRACE("(%s,%p) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
876 /* Tag current MODREF to prevent recursive loop */
877 wm
->ldr
.Flags
|= LDR_LOAD_IN_PROGRESS
;
879 /* Recursively attach all DLLs this one depends on */
880 for ( i
= 0; i
< wm
->nDeps
; i
++ )
882 if (!wm
->deps
[i
]) continue;
883 if ((status
= process_attach( wm
->deps
[i
], lpReserved
)) != STATUS_SUCCESS
) break;
886 /* Call DLL entry point */
887 if (status
== STATUS_SUCCESS
)
889 WINE_MODREF
*prev
= current_modref
;
891 if (MODULE_InitDLL( wm
, DLL_PROCESS_ATTACH
, lpReserved
))
893 wm
->ldr
.Flags
|= LDR_PROCESS_ATTACHED
;
897 /* point to the name so LdrInitializeThunk can print it */
898 last_failed_modref
= wm
;
899 WARN("Initialization of %s failed\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
900 status
= STATUS_DLL_INIT_FAILED
;
902 current_modref
= prev
;
905 if (!wm
->ldr
.InInitializationOrderModuleList
.Flink
)
906 InsertTailList(&NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
,
907 &wm
->ldr
.InInitializationOrderModuleList
);
909 /* Remove recursion flag */
910 wm
->ldr
.Flags
&= ~LDR_LOAD_IN_PROGRESS
;
912 TRACE("(%s,%p) - END\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), lpReserved
);
917 /**********************************************************************
918 * attach_implicitly_loaded_dlls
920 * Attach to the (builtin) dlls that have been implicitly loaded because
921 * of a dependency at the Unix level, but not imported at the Win32 level.
923 static void attach_implicitly_loaded_dlls( LPVOID reserved
)
927 PLIST_ENTRY mark
, entry
;
929 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
930 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
932 LDR_MODULE
*mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
934 if (mod
->Flags
& (LDR_LOAD_IN_PROGRESS
| LDR_PROCESS_ATTACHED
)) continue;
935 TRACE( "found implicitly loaded %s, attaching to it\n",
936 debugstr_w(mod
->BaseDllName
.Buffer
));
937 mod
->LoadCount
= -1; /* we can't unload it anyway */
938 process_attach( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
), reserved
);
939 break; /* restart the search from the start */
941 if (entry
== mark
) break; /* nothing found */
946 /*************************************************************************
949 * Send DLL process detach notifications. See the comment about calling
950 * sequence at process_attach. Unless the bForceDetach flag
951 * is set, only DLLs with zero refcount are notified.
953 static void process_detach( BOOL bForceDetach
, LPVOID lpReserved
)
955 PLIST_ENTRY mark
, entry
;
958 RtlEnterCriticalSection( &loader_section
);
959 if (bForceDetach
) process_detaching
= 1;
960 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
963 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
965 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
966 InInitializationOrderModuleList
);
967 /* Check whether to detach this DLL */
968 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
970 if ( mod
->LoadCount
&& !bForceDetach
)
973 /* Call detach notification */
974 mod
->Flags
&= ~LDR_PROCESS_ATTACHED
;
975 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
976 DLL_PROCESS_DETACH
, lpReserved
);
978 /* Restart at head of WINE_MODREF list, as entries might have
979 been added and/or removed while performing the call ... */
982 } while (entry
!= mark
);
984 RtlLeaveCriticalSection( &loader_section
);
987 /*************************************************************************
988 * MODULE_DllThreadAttach
990 * Send DLL thread attach notifications. These are sent in the
991 * reverse sequence of process detach notification.
994 NTSTATUS
MODULE_DllThreadAttach( LPVOID lpReserved
)
996 PLIST_ENTRY mark
, entry
;
1000 /* don't do any attach calls if process is exiting */
1001 if (process_detaching
) return STATUS_SUCCESS
;
1002 /* FIXME: there is still a race here */
1004 RtlEnterCriticalSection( &loader_section
);
1006 if ((status
= alloc_thread_tls()) != STATUS_SUCCESS
) goto done
;
1008 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1009 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1011 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
1012 InInitializationOrderModuleList
);
1013 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1015 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
1018 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
1019 DLL_THREAD_ATTACH
, lpReserved
);
1023 RtlLeaveCriticalSection( &loader_section
);
1027 /******************************************************************
1028 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1031 NTSTATUS WINAPI
LdrDisableThreadCalloutsForDll(HMODULE hModule
)
1034 NTSTATUS ret
= STATUS_SUCCESS
;
1036 RtlEnterCriticalSection( &loader_section
);
1038 wm
= get_modref( hModule
);
1039 if (!wm
|| wm
->ldr
.TlsIndex
!= -1)
1040 ret
= STATUS_DLL_NOT_FOUND
;
1042 wm
->ldr
.Flags
|= LDR_NO_DLL_CALLS
;
1044 RtlLeaveCriticalSection( &loader_section
);
1049 /******************************************************************
1050 * LdrFindEntryForAddress (NTDLL.@)
1052 * The loader_section must be locked while calling this function
1054 NTSTATUS WINAPI
LdrFindEntryForAddress(const void* addr
, PLDR_MODULE
* pmod
)
1056 PLIST_ENTRY mark
, entry
;
1059 mark
= &NtCurrentTeb()->Peb
->LdrData
->InMemoryOrderModuleList
;
1060 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1062 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InMemoryOrderModuleList
);
1063 if ((const void *)mod
->BaseAddress
<= addr
&&
1064 (const char *)addr
< (char*)mod
->BaseAddress
+ mod
->SizeOfImage
)
1067 return STATUS_SUCCESS
;
1069 if ((const void *)mod
->BaseAddress
> addr
) break;
1071 return STATUS_NO_MORE_ENTRIES
;
1074 /******************************************************************
1075 * LdrLockLoaderLock (NTDLL.@)
1077 * Note: flags are not implemented.
1078 * Flag 0x01 is used to raise exceptions on errors.
1079 * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
1081 NTSTATUS WINAPI
LdrLockLoaderLock( ULONG flags
, ULONG
*result
, ULONG
*magic
)
1083 if (flags
) FIXME( "flags %lx not supported\n", flags
);
1085 if (result
) *result
= 1;
1086 if (!magic
) return STATUS_INVALID_PARAMETER_3
;
1087 RtlEnterCriticalSection( &loader_section
);
1088 *magic
= GetCurrentThreadId();
1089 return STATUS_SUCCESS
;
1093 /******************************************************************
1094 * LdrUnlockLoaderUnlock (NTDLL.@)
1096 NTSTATUS WINAPI
LdrUnlockLoaderLock( ULONG flags
, ULONG magic
)
1100 if (magic
!= GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2
;
1101 RtlLeaveCriticalSection( &loader_section
);
1103 return STATUS_SUCCESS
;
1107 /******************************************************************
1108 * LdrGetDllHandle (NTDLL.@)
1110 NTSTATUS WINAPI
LdrGetDllHandle(ULONG x
, ULONG y
, const UNICODE_STRING
*name
, HMODULE
*base
)
1112 NTSTATUS status
= STATUS_DLL_NOT_FOUND
;
1113 WCHAR dllname
[MAX_PATH
+4], *p
;
1115 PLIST_ENTRY mark
, entry
;
1118 if (x
!= 0 || y
!= 0)
1119 FIXME("Unknown behavior, please report\n");
1121 /* Append .DLL to name if no extension present */
1122 if (!(p
= strrchrW( name
->Buffer
, '.')) || strchrW( p
, '/' ) || strchrW( p
, '\\'))
1124 if (name
->Length
>= MAX_PATH
) return STATUS_NAME_TOO_LONG
;
1125 strcpyW( dllname
, name
->Buffer
);
1126 strcatW( dllname
, dllW
);
1127 RtlInitUnicodeString( &str
, dllname
);
1131 RtlEnterCriticalSection( &loader_section
);
1135 if (RtlEqualUnicodeString( name
, &cached_modref
->ldr
.FullDllName
, TRUE
) ||
1136 RtlEqualUnicodeString( name
, &cached_modref
->ldr
.BaseDllName
, TRUE
))
1138 *base
= cached_modref
->ldr
.BaseAddress
;
1139 status
= STATUS_SUCCESS
;
1144 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
1145 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1147 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
1149 if (RtlEqualUnicodeString( name
, &mod
->FullDllName
, TRUE
) ||
1150 RtlEqualUnicodeString( name
, &mod
->BaseDllName
, TRUE
))
1152 cached_modref
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
1153 *base
= mod
->BaseAddress
;
1154 status
= STATUS_SUCCESS
;
1159 RtlLeaveCriticalSection( &loader_section
);
1160 TRACE("%lx %lx %s -> %p\n", x
, y
, debugstr_us(name
), status
? NULL
: *base
);
1165 /******************************************************************
1166 * LdrGetProcedureAddress (NTDLL.@)
1168 NTSTATUS WINAPI
LdrGetProcedureAddress(HMODULE module
, const ANSI_STRING
*name
,
1169 ULONG ord
, PVOID
*address
)
1171 IMAGE_EXPORT_DIRECTORY
*exports
;
1173 NTSTATUS ret
= STATUS_PROCEDURE_NOT_FOUND
;
1175 RtlEnterCriticalSection( &loader_section
);
1177 /* check if the module itself is invalid to return the proper error */
1178 if (!get_modref( module
)) ret
= STATUS_DLL_NOT_FOUND
;
1179 else if ((exports
= RtlImageDirectoryEntryToData( module
, TRUE
,
1180 IMAGE_DIRECTORY_ENTRY_EXPORT
, &exp_size
)))
1182 void *proc
= name
? find_named_export( module
, exports
, exp_size
, name
->Buffer
, -1 )
1183 : find_ordinal_export( module
, exports
, exp_size
, ord
- exports
->Base
);
1187 ret
= STATUS_SUCCESS
;
1191 RtlLeaveCriticalSection( &loader_section
);
1196 /***********************************************************************
1197 * load_builtin_callback
1199 * Load a library in memory; callback function for wine_dll_register
1201 static void load_builtin_callback( void *module
, const char *filename
)
1203 static const WCHAR emptyW
[1];
1205 IMAGE_NT_HEADERS
*nt
;
1207 WCHAR
*fullname
, *p
;
1208 const WCHAR
*load_path
;
1212 ERR("could not map image for %s\n", filename
? filename
: "main exe" );
1215 if (!(nt
= RtlImageNtHeader( module
)))
1217 ERR( "bad module for %s\n", filename
? filename
: "main exe" );
1218 builtin_load_info
->status
= STATUS_INVALID_IMAGE_FORMAT
;
1222 NtAllocateVirtualMemory( NtCurrentProcess(), &addr
, 0, &nt
->OptionalHeader
.SizeOfImage
,
1223 MEM_SYSTEM
| MEM_IMAGE
, PAGE_EXECUTE_WRITECOPY
);
1224 if (!(nt
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
))
1226 /* if we already have an executable, ignore this one */
1227 if (!NtCurrentTeb()->Peb
->ImageBaseAddress
)
1229 NtCurrentTeb()->Peb
->ImageBaseAddress
= module
;
1230 return; /* don't create the modref here, will be done later on */
1234 /* create the MODREF */
1236 if (!(fullname
= RtlAllocateHeap( GetProcessHeap(), 0,
1237 system_dir
.MaximumLength
+ (strlen(filename
) + 1) * sizeof(WCHAR
) )))
1239 ERR( "can't load %s\n", filename
);
1240 builtin_load_info
->status
= STATUS_NO_MEMORY
;
1243 memcpy( fullname
, system_dir
.Buffer
, system_dir
.Length
);
1244 p
= fullname
+ system_dir
.Length
/ sizeof(WCHAR
);
1245 if (p
> fullname
&& p
[-1] != '\\') *p
++ = '\\';
1246 ascii_to_unicode( p
, filename
, strlen(filename
) + 1 );
1248 wm
= alloc_module( module
, fullname
);
1249 RtlFreeHeap( GetProcessHeap(), 0, fullname
);
1252 ERR( "can't load %s\n", filename
);
1253 builtin_load_info
->status
= STATUS_NO_MEMORY
;
1256 wm
->ldr
.Flags
|= LDR_WINE_INTERNAL
;
1260 load_path
= builtin_load_info
->load_path
;
1261 if (!load_path
) load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1262 if (!load_path
) load_path
= emptyW
;
1263 if (fixup_imports( wm
, load_path
) != STATUS_SUCCESS
)
1265 /* the module has only be inserted in the load & memory order lists */
1266 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
1267 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
1268 /* FIXME: free the modref */
1269 builtin_load_info
->status
= STATUS_DLL_NOT_FOUND
;
1272 builtin_load_info
->wm
= wm
;
1273 TRACE( "loaded %s %p %p\n", filename
, wm
, module
);
1275 /* send the DLL load event */
1277 SERVER_START_REQ( load_dll
)
1281 req
->size
= nt
->OptionalHeader
.SizeOfImage
;
1282 req
->dbg_offset
= nt
->FileHeader
.PointerToSymbolTable
;
1283 req
->dbg_size
= nt
->FileHeader
.NumberOfSymbols
;
1284 req
->name
= &wm
->ldr
.FullDllName
.Buffer
;
1285 wine_server_add_data( req
, wm
->ldr
.FullDllName
.Buffer
, wm
->ldr
.FullDllName
.Length
);
1286 wine_server_call( req
);
1290 /* setup relay debugging entry points */
1291 if (TRACE_ON(relay
)) RELAY_SetupDLL( module
);
1295 /******************************************************************************
1296 * load_native_dll (internal)
1298 static NTSTATUS
load_native_dll( LPCWSTR load_path
, LPCWSTR name
, HANDLE file
,
1299 DWORD flags
, WINE_MODREF
** pwm
)
1303 OBJECT_ATTRIBUTES attr
;
1305 IMAGE_NT_HEADERS
*nt
;
1310 TRACE( "loading %s\n", debugstr_w(name
) );
1312 attr
.Length
= sizeof(attr
);
1313 attr
.RootDirectory
= 0;
1314 attr
.ObjectName
= NULL
;
1315 attr
.Attributes
= 0;
1316 attr
.SecurityDescriptor
= NULL
;
1317 attr
.SecurityQualityOfService
= NULL
;
1320 status
= NtCreateSection( &mapping
, STANDARD_RIGHTS_REQUIRED
| SECTION_QUERY
| SECTION_MAP_READ
,
1321 &attr
, &size
, 0, SEC_IMAGE
, file
);
1322 if (status
!= STATUS_SUCCESS
) return status
;
1325 status
= NtMapViewOfSection( mapping
, NtCurrentProcess(),
1326 &module
, 0, 0, &size
, &len
, ViewShare
, 0, PAGE_READONLY
);
1328 if (status
!= STATUS_SUCCESS
) return status
;
1330 /* create the MODREF */
1332 if (!(wm
= alloc_module( module
, name
))) return STATUS_NO_MEMORY
;
1336 if (!(flags
& DONT_RESOLVE_DLL_REFERENCES
))
1338 if ((status
= fixup_imports( wm
, load_path
)) != STATUS_SUCCESS
)
1340 /* the module has only be inserted in the load & memory order lists */
1341 RemoveEntryList(&wm
->ldr
.InLoadOrderModuleList
);
1342 RemoveEntryList(&wm
->ldr
.InMemoryOrderModuleList
);
1344 /* FIXME: there are several more dangling references
1345 * left. Including dlls loaded by this dll before the
1346 * failed one. Unrolling is rather difficult with the
1347 * current structure and we can leave them lying
1348 * around with no problems, so we don't care.
1349 * As these might reference our wm, we don't free it.
1354 else wm
->ldr
.Flags
|= LDR_DONT_RESOLVE_REFS
;
1356 /* send DLL load event */
1358 nt
= RtlImageNtHeader( module
);
1360 /* don't keep the file open if the mapping is from removable media */
1361 if (!VIRTUAL_HasMapping( module
)) file
= 0;
1363 SERVER_START_REQ( load_dll
)
1367 req
->size
= nt
->OptionalHeader
.SizeOfImage
;
1368 req
->dbg_offset
= nt
->FileHeader
.PointerToSymbolTable
;
1369 req
->dbg_size
= nt
->FileHeader
.NumberOfSymbols
;
1370 req
->name
= &wm
->ldr
.FullDllName
.Buffer
;
1371 wine_server_add_data( req
, wm
->ldr
.FullDllName
.Buffer
, wm
->ldr
.FullDllName
.Length
);
1372 wine_server_call( req
);
1376 if (TRACE_ON(snoop
)) SNOOP_SetupDLL( module
);
1378 TRACE_(loaddll
)( " Loaded module %s : native\n", debugstr_w(wm
->ldr
.FullDllName
.Buffer
) );
1381 return STATUS_SUCCESS
;
1385 /***********************************************************************
1388 static NTSTATUS
load_builtin_dll( LPCWSTR load_path
, LPCWSTR path
, DWORD flags
, WINE_MODREF
** pwm
)
1390 char error
[256], dllname
[MAX_PATH
];
1392 const WCHAR
*name
, *p
;
1395 struct builtin_load_info info
, *prev_info
;
1397 /* Fix the name in case we have a full path and extension */
1399 if ((p
= strrchrW( name
, '\\' ))) name
= p
+ 1;
1400 if ((p
= strrchrW( name
, '/' ))) name
= p
+ 1;
1402 /* we don't want to depend on the current codepage here */
1403 len
= strlenW( name
) + 1;
1404 if (len
>= sizeof(dllname
)) return STATUS_NAME_TOO_LONG
;
1405 for (i
= 0; i
< len
; i
++)
1407 if (name
[i
] > 127) return STATUS_DLL_NOT_FOUND
;
1408 dllname
[i
] = (char)name
[i
];
1409 if (dllname
[i
] >= 'A' && dllname
[i
] <= 'Z') dllname
[i
] += 'a' - 'A';
1412 /* load_library will modify info.status. Note also that load_library can be
1413 * called several times, if the .so file we're loading has dependencies.
1414 * info.status will gather all the errors we may get while loading all these
1417 info
.load_path
= load_path
;
1418 info
.status
= STATUS_SUCCESS
;
1420 prev_info
= builtin_load_info
;
1421 builtin_load_info
= &info
;
1422 handle
= wine_dll_load( dllname
, error
, sizeof(error
), &file_exists
);
1423 builtin_load_info
= prev_info
;
1429 /* The file does not exist -> WARN() */
1430 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name
), error
);
1431 return STATUS_DLL_NOT_FOUND
;
1433 /* ERR() for all other errors (missing functions, ...) */
1434 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name
), error
);
1435 return STATUS_PROCEDURE_NOT_FOUND
;
1437 if (info
.status
!= STATUS_SUCCESS
) return info
.status
;
1441 /* The constructor wasn't called, this means the .so is already
1442 * loaded under a different name. We can't support multiple names
1443 * for the same module, so return an error. */
1444 return STATUS_INVALID_IMAGE_FORMAT
;
1447 TRACE_(loaddll
)( "Loaded module %s : builtin\n", debugstr_w(info
.wm
->ldr
.FullDllName
.Buffer
) );
1449 info
.wm
->ldr
.SectionHandle
= handle
;
1450 if (strcmpiW( info
.wm
->ldr
.BaseDllName
.Buffer
, name
))
1452 ERR( "loaded .so for %s but got %s instead - probably 16-bit dll\n",
1453 debugstr_w(name
), debugstr_w(info
.wm
->ldr
.BaseDllName
.Buffer
) );
1454 /* wine_dll_unload( handle );*/
1455 return STATUS_INVALID_IMAGE_FORMAT
;
1458 return STATUS_SUCCESS
;
1462 /***********************************************************************
1465 * Find the file (or already loaded module) for a given dll name.
1467 static NTSTATUS
find_dll_file( const WCHAR
*load_path
, const WCHAR
*libname
,
1468 WCHAR
*filename
, ULONG
*size
, WINE_MODREF
**pwm
, HANDLE
*handle
)
1470 OBJECT_ATTRIBUTES attr
;
1472 UNICODE_STRING nt_name
;
1473 WCHAR
*file_part
, *ext
, *dllname
;
1476 /* first append .dll if needed */
1479 if (!(ext
= strrchrW( libname
, '.')) || strchrW( ext
, '/' ) || strchrW( ext
, '\\'))
1481 if (!(dllname
= RtlAllocateHeap( GetProcessHeap(), 0,
1482 (strlenW(libname
) * sizeof(WCHAR
)) + sizeof(dllW
) )))
1483 return STATUS_NO_MEMORY
;
1484 strcpyW( dllname
, libname
);
1485 strcatW( dllname
, dllW
);
1489 nt_name
.Buffer
= NULL
;
1490 if (RtlDetermineDosPathNameType_U( libname
) == RELATIVE_PATH
)
1492 /* we need to search for it */
1493 len
= RtlDosSearchPath_U( load_path
, libname
, NULL
, *size
, filename
, &file_part
);
1496 if (len
>= *size
) goto overflow
;
1497 if ((*pwm
= find_fullname_module( filename
)) != NULL
) goto found
;
1499 /* check for already loaded module in a different path */
1500 if (!contains_path( libname
))
1502 if ((*pwm
= find_basename_module( file_part
)) != NULL
) goto found
;
1504 if (!RtlDosPathNameToNtPathName_U( filename
, &nt_name
, NULL
, NULL
))
1506 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1507 return STATUS_NO_MEMORY
;
1509 attr
.Length
= sizeof(attr
);
1510 attr
.RootDirectory
= 0;
1511 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
1512 attr
.ObjectName
= &nt_name
;
1513 attr
.SecurityDescriptor
= NULL
;
1514 attr
.SecurityQualityOfService
= NULL
;
1515 if (NtOpenFile( handle
, GENERIC_READ
, &attr
, &io
, FILE_SHARE_READ
|FILE_SHARE_DELETE
, 0 )) *handle
= 0;
1521 if (!contains_path( libname
))
1523 /* if libname doesn't contain a path at all, we simply return the name as is,
1524 * to be loaded as builtin */
1525 len
= strlenW(libname
) * sizeof(WCHAR
);
1526 if (len
>= *size
) goto overflow
;
1527 strcpyW( filename
, libname
);
1528 *pwm
= find_basename_module( filename
);
1533 /* absolute path name, or relative path name but not found above */
1535 if (!RtlDosPathNameToNtPathName_U( libname
, &nt_name
, &file_part
, NULL
))
1537 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1538 return STATUS_NO_MEMORY
;
1540 len
= nt_name
.Length
- 4*sizeof(WCHAR
); /* for \??\ prefix */
1541 if (len
>= *size
) goto overflow
;
1542 memcpy( filename
, nt_name
.Buffer
+ 4, len
+ sizeof(WCHAR
) );
1543 if (!(*pwm
= find_fullname_module( filename
)))
1545 attr
.Length
= sizeof(attr
);
1546 attr
.RootDirectory
= 0;
1547 attr
.Attributes
= OBJ_CASE_INSENSITIVE
;
1548 attr
.ObjectName
= &nt_name
;
1549 attr
.SecurityDescriptor
= NULL
;
1550 attr
.SecurityQualityOfService
= NULL
;
1551 if (NtOpenFile( handle
, GENERIC_READ
, &attr
, &io
, FILE_SHARE_READ
|FILE_SHARE_DELETE
, 0 )) *handle
= 0;
1554 RtlFreeUnicodeString( &nt_name
);
1555 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1556 return STATUS_SUCCESS
;
1559 RtlFreeUnicodeString( &nt_name
);
1560 RtlFreeHeap( GetProcessHeap(), 0, dllname
);
1561 *size
= len
+ sizeof(WCHAR
);
1562 return STATUS_BUFFER_TOO_SMALL
;
1566 /***********************************************************************
1567 * load_dll (internal)
1569 * Load a PE style module according to the load order.
1570 * The loader_section must be locked while calling this function.
1572 static NTSTATUS
load_dll( LPCWSTR load_path
, LPCWSTR libname
, DWORD flags
, WINE_MODREF
** pwm
)
1575 enum loadorder_type loadorder
[LOADORDER_NTYPES
];
1579 const char *filetype
= "";
1580 WINE_MODREF
*main_exe
;
1584 TRACE( "looking for %s in %s\n", debugstr_w(libname
), debugstr_w(load_path
) );
1587 size
= sizeof(buffer
);
1590 nts
= find_dll_file( load_path
, libname
, filename
, &size
, pwm
, &handle
);
1591 if (nts
== STATUS_SUCCESS
) break;
1592 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
1593 if (nts
!= STATUS_BUFFER_TOO_SMALL
) return nts
;
1594 /* grow the buffer and retry */
1595 if (!(filename
= RtlAllocateHeap( GetProcessHeap(), 0, size
))) return STATUS_NO_MEMORY
;
1598 if (*pwm
) /* found already loaded module */
1600 if ((*pwm
)->ldr
.LoadCount
!= -1) (*pwm
)->ldr
.LoadCount
++;
1602 if (((*pwm
)->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
) &&
1603 !(flags
& DONT_RESOLVE_DLL_REFERENCES
))
1605 (*pwm
)->ldr
.Flags
&= ~LDR_DONT_RESOLVE_REFS
;
1606 fixup_imports( *pwm
, load_path
);
1608 TRACE("Found loaded module %s for %s at %p, count=%d\n",
1609 debugstr_w((*pwm
)->ldr
.FullDllName
.Buffer
), debugstr_w(libname
),
1610 (*pwm
)->ldr
.BaseAddress
, (*pwm
)->ldr
.LoadCount
);
1611 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
1612 return STATUS_SUCCESS
;
1615 main_exe
= get_modref( NtCurrentTeb()->Peb
->ImageBaseAddress
);
1616 MODULE_GetLoadOrderW( loadorder
, main_exe
? main_exe
->ldr
.BaseDllName
.Buffer
: NULL
, filename
);
1618 nts
= STATUS_DLL_NOT_FOUND
;
1619 for (i
= 0; i
< LOADORDER_NTYPES
; i
++)
1621 if (loadorder
[i
] == LOADORDER_INVALID
) break;
1623 switch (loadorder
[i
])
1626 TRACE("Trying native dll %s\n", debugstr_w(filename
));
1627 if (!handle
) continue; /* it cannot possibly be loaded */
1628 nts
= load_native_dll( load_path
, filename
, handle
, flags
, pwm
);
1629 filetype
= "native";
1632 TRACE("Trying built-in %s\n", debugstr_w(filename
));
1633 nts
= load_builtin_dll( load_path
, filename
, flags
, pwm
);
1634 filetype
= "builtin";
1637 nts
= STATUS_INTERNAL_ERROR
;
1641 if (nts
== STATUS_SUCCESS
)
1643 /* Initialize DLL just loaded */
1644 TRACE("Loaded module %s (%s) at %p\n",
1645 debugstr_w(filename
), filetype
, (*pwm
)->ldr
.BaseAddress
);
1646 /* Set the ldr.LoadCount here so that an attach failure will */
1647 /* decrement the dependencies through the MODULE_FreeLibrary call. */
1648 (*pwm
)->ldr
.LoadCount
= 1;
1649 if (handle
) NtClose( handle
);
1650 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
1653 if (nts
!= STATUS_DLL_NOT_FOUND
) break;
1656 WARN("Failed to load module %s; status=%lx\n", debugstr_w(libname
), nts
);
1657 if (handle
) NtClose( handle
);
1658 if (filename
!= buffer
) RtlFreeHeap( GetProcessHeap(), 0, filename
);
1662 /******************************************************************
1663 * LdrLoadDll (NTDLL.@)
1665 NTSTATUS WINAPI
LdrLoadDll(LPCWSTR path_name
, DWORD flags
,
1666 const UNICODE_STRING
*libname
, HMODULE
* hModule
)
1671 RtlEnterCriticalSection( &loader_section
);
1673 if (!path_name
) path_name
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1674 nts
= load_dll( path_name
, libname
->Buffer
, flags
, &wm
);
1676 if (nts
== STATUS_SUCCESS
&& !(wm
->ldr
.Flags
& LDR_DONT_RESOLVE_REFS
))
1678 nts
= process_attach( wm
, NULL
);
1679 if (nts
!= STATUS_SUCCESS
)
1681 LdrUnloadDll(wm
->ldr
.BaseAddress
);
1685 *hModule
= (wm
) ? wm
->ldr
.BaseAddress
: NULL
;
1687 RtlLeaveCriticalSection( &loader_section
);
1691 /******************************************************************
1692 * LdrQueryProcessModuleInformation
1695 NTSTATUS WINAPI
LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi
,
1696 ULONG buf_size
, ULONG
* req_size
)
1698 SYSTEM_MODULE
* sm
= &smi
->Modules
[0];
1699 ULONG size
= sizeof(ULONG
);
1700 NTSTATUS nts
= STATUS_SUCCESS
;
1703 PLIST_ENTRY mark
, entry
;
1706 smi
->ModulesCount
= 0;
1708 RtlEnterCriticalSection( &loader_section
);
1709 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
1710 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
1712 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
, InLoadOrderModuleList
);
1713 size
+= sizeof(*sm
);
1714 if (size
<= buf_size
)
1716 sm
->Reserved1
= 0; /* FIXME */
1717 sm
->Reserved2
= 0; /* FIXME */
1718 sm
->ImageBaseAddress
= mod
->BaseAddress
;
1719 sm
->ImageSize
= mod
->SizeOfImage
;
1720 sm
->Flags
= mod
->Flags
;
1721 sm
->Id
= 0; /* FIXME */
1722 sm
->Rank
= 0; /* FIXME */
1723 sm
->Unknown
= 0; /* FIXME */
1725 str
.MaximumLength
= MAXIMUM_FILENAME_LENGTH
;
1726 str
.Buffer
= (char*)sm
->Name
;
1727 RtlUnicodeStringToAnsiString(&str
, &mod
->FullDllName
, FALSE
);
1728 ptr
= strrchr(str
.Buffer
, '\\');
1729 sm
->NameOffset
= (ptr
!= NULL
) ? (ptr
- str
.Buffer
+ 1) : 0;
1731 smi
->ModulesCount
++;
1734 else nts
= STATUS_INFO_LENGTH_MISMATCH
;
1736 RtlLeaveCriticalSection( &loader_section
);
1738 if (req_size
) *req_size
= size
;
1743 /******************************************************************
1744 * LdrShutdownProcess (NTDLL.@)
1747 void WINAPI
LdrShutdownProcess(void)
1750 process_detach( TRUE
, (LPVOID
)1 );
1753 /******************************************************************
1754 * LdrShutdownThread (NTDLL.@)
1757 void WINAPI
LdrShutdownThread(void)
1759 PLIST_ENTRY mark
, entry
;
1764 /* don't do any detach calls if process is exiting */
1765 if (process_detaching
) return;
1766 /* FIXME: there is still a race here */
1768 RtlEnterCriticalSection( &loader_section
);
1770 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1771 for (entry
= mark
->Blink
; entry
!= mark
; entry
= entry
->Blink
)
1773 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
1774 InInitializationOrderModuleList
);
1775 if ( !(mod
->Flags
& LDR_PROCESS_ATTACHED
) )
1777 if ( mod
->Flags
& LDR_NO_DLL_CALLS
)
1780 MODULE_InitDLL( CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
),
1781 DLL_THREAD_DETACH
, NULL
);
1784 RtlLeaveCriticalSection( &loader_section
);
1787 /***********************************************************************
1788 * MODULE_FlushModrefs
1790 * Remove all unused modrefs and call the internal unloading routines
1791 * for the library type.
1793 * The loader_section must be locked while calling this function.
1795 static void MODULE_FlushModrefs(void)
1797 PLIST_ENTRY mark
, entry
, prev
;
1801 mark
= &NtCurrentTeb()->Peb
->LdrData
->InInitializationOrderModuleList
;
1802 for (entry
= mark
->Blink
; entry
!= mark
; entry
= prev
)
1804 mod
= CONTAINING_RECORD(entry
, LDR_MODULE
,
1805 InInitializationOrderModuleList
);
1806 wm
= CONTAINING_RECORD(mod
, WINE_MODREF
, ldr
);
1808 prev
= entry
->Blink
;
1809 if (mod
->LoadCount
) continue;
1811 RemoveEntryList(&mod
->InLoadOrderModuleList
);
1812 RemoveEntryList(&mod
->InMemoryOrderModuleList
);
1813 RemoveEntryList(&mod
->InInitializationOrderModuleList
);
1815 TRACE(" unloading %s\n", debugstr_w(mod
->FullDllName
.Buffer
));
1816 if (!TRACE_ON(module
))
1817 TRACE_(loaddll
)("Unloaded module %s : %s\n",
1818 debugstr_w(mod
->FullDllName
.Buffer
),
1819 (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) ? "builtin" : "native" );
1821 SERVER_START_REQ( unload_dll
)
1823 req
->base
= mod
->BaseAddress
;
1824 wine_server_call( req
);
1828 NtUnmapViewOfSection( NtCurrentProcess(), mod
->BaseAddress
);
1829 if (wm
->ldr
.Flags
& LDR_WINE_INTERNAL
) wine_dll_unload( wm
->ldr
.SectionHandle
);
1830 if (cached_modref
== wm
) cached_modref
= NULL
;
1831 RtlFreeUnicodeString( &mod
->FullDllName
);
1832 RtlFreeHeap( GetProcessHeap(), 0, wm
->deps
);
1833 RtlFreeHeap( GetProcessHeap(), 0, wm
);
1837 /***********************************************************************
1838 * MODULE_DecRefCount
1840 * The loader_section must be locked while calling this function.
1842 static void MODULE_DecRefCount( WINE_MODREF
*wm
)
1846 if ( wm
->ldr
.Flags
& LDR_UNLOAD_IN_PROGRESS
)
1849 if ( wm
->ldr
.LoadCount
<= 0 )
1852 --wm
->ldr
.LoadCount
;
1853 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
), wm
->ldr
.LoadCount
);
1855 if ( wm
->ldr
.LoadCount
== 0 )
1857 wm
->ldr
.Flags
|= LDR_UNLOAD_IN_PROGRESS
;
1859 for ( i
= 0; i
< wm
->nDeps
; i
++ )
1861 MODULE_DecRefCount( wm
->deps
[i
] );
1863 wm
->ldr
.Flags
&= ~LDR_UNLOAD_IN_PROGRESS
;
1867 /******************************************************************
1868 * LdrUnloadDll (NTDLL.@)
1872 NTSTATUS WINAPI
LdrUnloadDll( HMODULE hModule
)
1874 NTSTATUS retv
= STATUS_SUCCESS
;
1876 TRACE("(%p)\n", hModule
);
1878 RtlEnterCriticalSection( &loader_section
);
1880 /* if we're stopping the whole process (and forcing the removal of all
1881 * DLLs) the library will be freed anyway
1883 if (!process_detaching
)
1888 if ((wm
= get_modref( hModule
)) != NULL
)
1890 TRACE("(%s) - START\n", debugstr_w(wm
->ldr
.BaseDllName
.Buffer
));
1892 /* Recursively decrement reference counts */
1893 MODULE_DecRefCount( wm
);
1895 /* Call process detach notifications */
1896 if ( free_lib_count
<= 1 )
1898 process_detach( FALSE
, NULL
);
1899 MODULE_FlushModrefs();
1905 retv
= STATUS_DLL_NOT_FOUND
;
1910 RtlLeaveCriticalSection( &loader_section
);
1915 /***********************************************************************
1916 * RtlImageNtHeader (NTDLL.@)
1918 PIMAGE_NT_HEADERS WINAPI
RtlImageNtHeader(HMODULE hModule
)
1920 IMAGE_NT_HEADERS
*ret
;
1924 IMAGE_DOS_HEADER
*dos
= (IMAGE_DOS_HEADER
*)hModule
;
1927 if (dos
->e_magic
== IMAGE_DOS_SIGNATURE
)
1929 ret
= (IMAGE_NT_HEADERS
*)((char *)dos
+ dos
->e_lfanew
);
1930 if (ret
->Signature
!= IMAGE_NT_SIGNATURE
) ret
= NULL
;
1942 /******************************************************************
1943 * LdrInitializeThunk (NTDLL.@)
1945 * FIXME: the arguments are not correct, main_file is a Wine invention.
1947 void WINAPI
LdrInitializeThunk( HANDLE main_file
, ULONG unknown2
, ULONG unknown3
, ULONG unknown4
)
1952 PEB
*peb
= NtCurrentTeb()->Peb
;
1953 UNICODE_STRING
*main_exe_name
= &peb
->ProcessParameters
->ImagePathName
;
1954 IMAGE_NT_HEADERS
*nt
= RtlImageNtHeader( peb
->ImageBaseAddress
);
1956 version_init( main_exe_name
->Buffer
);
1958 /* allocate the modref for the main exe */
1959 if (!(wm
= alloc_module( peb
->ImageBaseAddress
, main_exe_name
->Buffer
)))
1961 status
= STATUS_NO_MEMORY
;
1964 wm
->ldr
.LoadCount
= -1; /* can't unload main exe */
1966 /* the main exe needs to be the first in the load order list */
1967 RemoveEntryList( &wm
->ldr
.InLoadOrderModuleList
);
1968 InsertHeadList( &peb
->LdrData
->InLoadOrderModuleList
, &wm
->ldr
.InLoadOrderModuleList
);
1970 /* Install signal handlers; this cannot be done before, since we cannot
1971 * send exceptions to the debugger before the create process event that
1972 * is sent by REQ_INIT_PROCESS_DONE.
1973 * We do need the handlers in place by the time the request is over, so
1974 * we set them up here. If we segfault between here and the server call
1975 * something is very wrong... */
1976 if (!SIGNAL_Init()) exit(1);
1978 /* Signal the parent process to continue */
1979 SERVER_START_REQ( init_process_done
)
1981 req
->module
= peb
->ImageBaseAddress
;
1982 req
->module_size
= wm
->ldr
.SizeOfImage
;
1983 req
->entry
= (char *)peb
->ImageBaseAddress
+ nt
->OptionalHeader
.AddressOfEntryPoint
;
1984 /* API requires a double indirection */
1985 req
->name
= &main_exe_name
->Buffer
;
1986 req
->exe_file
= main_file
;
1987 req
->gui
= (nt
->OptionalHeader
.Subsystem
!= IMAGE_SUBSYSTEM_WINDOWS_CUI
);
1988 wine_server_add_data( req
, main_exe_name
->Buffer
, main_exe_name
->Length
);
1989 wine_server_call( req
);
1993 if (main_file
) NtClose( main_file
); /* we no longer need it */
1995 RtlEnterCriticalSection( &loader_section
);
1997 load_path
= NtCurrentTeb()->Peb
->ProcessParameters
->DllPath
.Buffer
;
1998 if ((status
= fixup_imports( wm
, load_path
)) != STATUS_SUCCESS
) goto error
;
1999 if ((status
= alloc_process_tls()) != STATUS_SUCCESS
) goto error
;
2000 if ((status
= alloc_thread_tls()) != STATUS_SUCCESS
) goto error
;
2001 if ((status
= process_attach( wm
, (LPVOID
)1 )) != STATUS_SUCCESS
)
2003 if (last_failed_modref
)
2004 ERR( "%s failed to initialize, aborting\n", debugstr_w(last_failed_modref
->ldr
.BaseDllName
.Buffer
) + 1 );
2007 attach_implicitly_loaded_dlls( (LPVOID
)1 );
2009 RtlLeaveCriticalSection( &loader_section
);
2011 if (nt
->FileHeader
.Characteristics
& IMAGE_FILE_LARGE_ADDRESS_AWARE
) VIRTUAL_UseLargeAddressSpace();
2015 ERR( "Main exe initialization for %s failed, status %lx\n", debugstr_w(main_exe_name
->Buffer
), status
);
2020 /***********************************************************************
2021 * RtlImageDirectoryEntryToData (NTDLL.@)
2023 PVOID WINAPI
RtlImageDirectoryEntryToData( HMODULE module
, BOOL image
, WORD dir
, ULONG
*size
)
2025 const IMAGE_NT_HEADERS
*nt
;
2028 if ((ULONG_PTR
)module
& 1) /* mapped as data file */
2030 module
= (HMODULE
)((ULONG_PTR
)module
& ~1);
2033 if (!(nt
= RtlImageNtHeader( module
))) return NULL
;
2034 if (dir
>= nt
->OptionalHeader
.NumberOfRvaAndSizes
) return NULL
;
2035 if (!(addr
= nt
->OptionalHeader
.DataDirectory
[dir
].VirtualAddress
)) return NULL
;
2036 *size
= nt
->OptionalHeader
.DataDirectory
[dir
].Size
;
2037 if (image
|| addr
< nt
->OptionalHeader
.SizeOfHeaders
) return (char *)module
+ addr
;
2039 /* not mapped as image, need to find the section containing the virtual address */
2040 return RtlImageRvaToVa( nt
, module
, addr
, NULL
);
2044 /***********************************************************************
2045 * RtlImageRvaToSection (NTDLL.@)
2047 PIMAGE_SECTION_HEADER WINAPI
RtlImageRvaToSection( const IMAGE_NT_HEADERS
*nt
,
2048 HMODULE module
, DWORD rva
)
2051 const IMAGE_SECTION_HEADER
*sec
;
2053 sec
= (const IMAGE_SECTION_HEADER
*)((const char*)&nt
->OptionalHeader
+
2054 nt
->FileHeader
.SizeOfOptionalHeader
);
2055 for (i
= 0; i
< nt
->FileHeader
.NumberOfSections
; i
++, sec
++)
2057 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
2058 return (PIMAGE_SECTION_HEADER
)sec
;
2064 /***********************************************************************
2065 * RtlImageRvaToVa (NTDLL.@)
2067 PVOID WINAPI
RtlImageRvaToVa( const IMAGE_NT_HEADERS
*nt
, HMODULE module
,
2068 DWORD rva
, IMAGE_SECTION_HEADER
**section
)
2070 IMAGE_SECTION_HEADER
*sec
;
2072 if (section
&& *section
) /* try this section first */
2075 if ((sec
->VirtualAddress
<= rva
) && (sec
->VirtualAddress
+ sec
->SizeOfRawData
> rva
))
2078 if (!(sec
= RtlImageRvaToSection( nt
, module
, rva
))) return NULL
;
2080 if (section
) *section
= sec
;
2081 return (char *)module
+ sec
->PointerToRawData
+ (rva
- sec
->VirtualAddress
);
2085 /***********************************************************************
2086 * NtLoadDriver (NTDLL.@)
2087 * ZwLoadDriver (NTDLL.@)
2089 NTSTATUS WINAPI
NtLoadDriver( const UNICODE_STRING
*DriverServiceName
)
2091 FIXME("(%p), stub!\n",DriverServiceName
);
2092 return STATUS_NOT_IMPLEMENTED
;
2096 /***********************************************************************
2097 * NtUnloadDriver (NTDLL.@)
2098 * ZwUnloadDriver (NTDLL.@)
2100 NTSTATUS WINAPI
NtUnloadDriver( const UNICODE_STRING
*DriverServiceName
)
2102 FIXME("(%p), stub!\n",DriverServiceName
);
2103 return STATUS_NOT_IMPLEMENTED
;
2107 /******************************************************************
2110 BOOL WINAPI
DllMain( HINSTANCE inst
, DWORD reason
, LPVOID reserved
)
2112 if (reason
== DLL_PROCESS_ATTACH
) LdrDisableThreadCalloutsForDll( inst
);
2117 /******************************************************************
2118 * __wine_init_windows_dir (NTDLL.@)
2120 * Windows and system dir initialization once kernel32 has been loaded.
2122 void __wine_init_windows_dir( const WCHAR
*windir
, const WCHAR
*sysdir
)
2124 PLIST_ENTRY mark
, entry
;
2127 RtlCreateUnicodeString( &system_dir
, sysdir
);
2129 /* prepend the system dir to the name of the already created modules */
2130 mark
= &NtCurrentTeb()->Peb
->LdrData
->InLoadOrderModuleList
;
2131 for (entry
= mark
->Flink
; entry
!= mark
; entry
= entry
->Flink
)
2133 LDR_MODULE
*mod
= CONTAINING_RECORD( entry
, LDR_MODULE
, InLoadOrderModuleList
);
2135 assert( mod
->Flags
& LDR_WINE_INTERNAL
);
2137 buffer
= RtlAllocateHeap( GetProcessHeap(), 0,
2138 system_dir
.Length
+ mod
->FullDllName
.Length
+ 2*sizeof(WCHAR
) );
2139 if (!buffer
) continue;
2140 strcpyW( buffer
, system_dir
.Buffer
);
2141 p
= buffer
+ strlenW( buffer
);
2142 if (p
> buffer
&& p
[-1] != '\\') *p
++ = '\\';
2143 strcpyW( p
, mod
->FullDllName
.Buffer
);
2144 RtlInitUnicodeString( &mod
->FullDllName
, buffer
);
2145 RtlInitUnicodeString( &mod
->BaseDllName
, p
);
2150 /***********************************************************************
2151 * __wine_process_init
2153 void __wine_process_init( int argc
, char *argv
[] )
2155 static const WCHAR kernel32W
[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
2159 ANSI_STRING func_name
;
2160 void (* DECLSPEC_NORETURN init_func
)();
2161 extern mode_t FILE_umask
;
2165 /* retrieve current umask */
2166 FILE_umask
= umask(0777);
2167 umask( FILE_umask
);
2169 /* setup the load callback and create ntdll modref */
2170 wine_dll_set_callback( load_builtin_callback
);
2172 if ((status
= load_builtin_dll( NULL
, kernel32W
, 0, &wm
)) != STATUS_SUCCESS
)
2174 MESSAGE( "wine: could not load kernel32.dll, status %lx\n", status
);
2177 RtlInitAnsiString( &func_name
, "__wine_kernel_init" );
2178 if ((status
= LdrGetProcedureAddress( wm
->ldr
.BaseAddress
, &func_name
,
2179 0, (void **)&init_func
)) != STATUS_SUCCESS
)
2181 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %lx\n", status
);