Take advantage of the __EXCEPT_PAGE_FAULT macro.
[wine/dcerpc.git] / dlls / ntdll / loader.c
blob99b4ccf0ea2d5073be26726cfbb1f5d44213f6c1
1 /*
2 * Loader functions
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
22 #include "config.h"
23 #include "wine/port.h"
25 #include <assert.h>
26 #include <stdarg.h>
28 #define NONAMELESSUNION
29 #define NONAMELESSSTRUCT
31 #include "ntstatus.h"
32 #define WIN32_NO_STATUS
33 #include "windef.h"
34 #include "winnt.h"
35 #include "winternl.h"
37 #include "module.h"
38 #include "wine/exception.h"
39 #include "excpt.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[] =
59 "PROCESS_DETACH",
60 "PROCESS_ATTACH",
61 "THREAD_ATTACH",
62 "THREAD_DETACH"
65 static const WCHAR dllW[] = {'.','d','l','l',0};
67 /* internal representation of 32bit modules. per process. */
68 typedef struct _wine_modref
70 LDR_MODULE ldr;
71 int nDeps;
72 struct _wine_modref **deps;
73 } WINE_MODREF;
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 NTSTATUS status;
81 WINE_MODREF *wm;
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.
135 #ifdef __i386__
136 extern BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module, UINT reason, void *reserved );
137 __ASM_GLOBAL_FUNC(call_dll_entry_point,
138 "pushl %ebp\n\t"
139 "movl %esp,%ebp\n\t"
140 "pushl %ebx\n\t"
141 "subl $8,%esp\n\t"
142 "pushl 20(%ebp)\n\t"
143 "pushl 16(%ebp)\n\t"
144 "pushl 12(%ebp)\n\t"
145 "movl 8(%ebp),%eax\n\t"
146 "call *%eax\n\t"
147 "leal -4(%ebp),%esp\n\t"
148 "popl %ebx\n\t"
149 "popl %ebp\n\t"
150 "ret" );
151 #else /* __i386__ */
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__ */
160 #ifdef __i386__
161 /*************************************************************************
162 * stub_entry_point
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;
173 #ifdef __GNUC__
174 rec.ExceptionAddress = __builtin_return_address(0);
175 #else
176 rec.ExceptionAddress = *((void **)&dll - 1);
177 #endif
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"
186 struct stub
188 BYTE popl_eax; /* popl %eax */
189 BYTE pushl1; /* pushl $name */
190 const char *name;
191 BYTE pushl2; /* pushl $dll */
192 const char *dll;
193 BYTE pushl_eax; /* pushl %eax */
194 BYTE jmp; /* jmp stub_entry_point */
195 DWORD entry;
197 #include "poppack.h"
199 /*************************************************************************
200 * allocate_stub
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;
209 struct stub *stub;
211 if (nb_stubs >= MAX_SIZE / sizeof(*stub)) return 0xdeadbeef;
213 if (!stubs)
215 ULONG size = MAX_SIZE;
216 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs, 0, &size,
217 MEM_COMMIT, PAGE_EXECUTE_WRITECOPY ) != STATUS_SUCCESS)
218 return 0xdeadbeef;
220 stub = &stubs[nb_stubs++];
221 stub->popl_eax = 0x58; /* popl %eax */
222 stub->pushl1 = 0x68; /* pushl $name */
223 stub->name = name;
224 stub->pushl2 = 0x68; /* pushl $dll */
225 stub->dll = 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;
232 #else /* __i386__ */
233 static inline ULONG_PTR allocate_stub( const char *dll, const char *name ) { return 0xdeadbeef; }
234 #endif /* __i386__ */
237 /*************************************************************************
238 * get_modref
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;
246 PLDR_MODULE mod;
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;
258 return NULL;
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;
285 return NULL;
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;
312 return NULL;
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;
325 DWORD exp_size;
326 WINE_MODREF *wm;
327 WCHAR mod_name[32];
328 const char *end = strchr(forward, '.');
329 FARPROC proc = NULL;
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) );
340 return NULL;
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 );
346 if (!proc)
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) );
353 return proc;
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, int ordinal )
367 FARPROC proc;
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 );
373 return NULL;
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 );
384 if (TRACE_ON(snoop))
386 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
387 proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
389 if (TRACE_ON(relay))
391 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
392 proc = RELAY_GetProcAddress( module, exports, exp_size, proc, user );
394 return proc;
398 /*************************************************************************
399 * find_named_export
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 */
420 while (min <= max)
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;
427 else min = pos + 1;
429 return NULL;
434 /*************************************************************************
435 * import_dll
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 )
442 NTSTATUS status;
443 WINE_MODREF *wmImp;
444 HMODULE imp_mod;
445 const IMAGE_EXPORT_DIRECTORY *exports;
446 DWORD exp_size;
447 const IMAGE_THUNK_DATA *import_list;
448 IMAGE_THUNK_DATA *thunk_list;
449 WCHAR buffer[32];
450 const char *name = get_rva( module, descr->Name );
451 DWORD len = strlen(name) + 1;
452 PVOID protect_base;
453 SIZE_T protect_size = 0;
454 DWORD protect_old;
456 thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
457 if (descr->u.OriginalFirstThunk)
458 import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
459 else
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 );
476 if (status)
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));
481 else
482 ERR("Loading library %s (which is needed by %s) failed (error %lx).\n",
483 name, debugstr_w(current_modref->ldr.FullDllName.Buffer), status);
484 return NULL;
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 );
498 if (!exports)
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 );
509 else
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 );
518 import_list++;
519 thunk_list++;
521 goto done;
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);
557 import_list++;
558 thunk_list++;
561 done:
562 /* restore old protection of the import address table */
563 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base, &protect_size, protect_old, NULL );
564 return wmImp;
568 /****************************************************************
569 * fixup_imports
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 )
576 int i, nb_imports;
577 const IMAGE_IMPORT_DESCRIPTOR *imports;
578 WINE_MODREF *prev;
579 DWORD size;
580 NTSTATUS status;
582 if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
583 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
584 return STATUS_SUCCESS;
586 nb_imports = 0;
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;
599 current_modref = wm;
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;
607 return status;
611 /*************************************************************************
612 * alloc_module
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 )
619 WINE_MODREF *wm;
620 const WCHAR *p;
621 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
622 PLIST_ENTRY entry, mark;
624 if (!(wm = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm) ))) return NULL;
626 wm->nDeps = 0;
627 wm->deps = NULL;
629 wm->ldr.BaseAddress = hModule;
630 wm->ldr.EntryPoint = NULL;
631 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
632 wm->ldr.Flags = 0;
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)
659 break;
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;
669 return wm;
673 /*************************************************************************
674 * alloc_process_tls
676 * Allocate the process-wide structure for module TLS storage.
678 static NTSTATUS alloc_process_tls(void)
680 PLIST_ENTRY mark, entry;
681 PLDR_MODULE mod;
682 const IMAGE_TLS_DIRECTORY *dir;
683 ULONG size, i;
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 )))
691 continue;
692 size = (dir->EndAddressOfRawData - dir->StartAddressOfRawData) + dir->SizeOfZeroFill;
693 if (!size) continue;
694 tls_total_size += size;
695 tls_module_count++;
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 )))
709 continue;
710 tls_dirs[i] = dir;
711 *(DWORD *)dir->AddressOfIndex = i;
712 mod->TlsIndex = i;
713 mod->LoadCount = -1; /* can't unload it */
714 i++;
716 return STATUS_SUCCESS;
720 /*************************************************************************
721 * alloc_thread_tls
723 * Allocate the per-thread structure for module TLS storage.
725 static NTSTATUS alloc_thread_tls(void)
727 void **pointers;
728 char *data;
729 UINT i;
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 );
752 pointers[i] = data;
753 memcpy( data, (void *)dir->StartAddressOfRawData, size );
754 data += size;
755 memset( data, 0, dir->SizeOfZeroFill );
756 data += dir->SizeOfZeroFill;
758 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
759 return STATUS_SUCCESS;
763 /*************************************************************************
764 * call_tls_callbacks
766 static void call_tls_callbacks( HMODULE module, UINT reason )
768 const IMAGE_TLS_DIRECTORY *dir;
769 const PIMAGE_TLS_CALLBACK *callback;
770 ULONG dirsize;
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++)
777 if (TRACE_ON(relay))
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 );
781 if (TRACE_ON(relay))
782 DPRINTF("%04lx:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
783 GetCurrentThreadId(), *callback, module, reason_names[reason] );
788 /*************************************************************************
789 * MODULE_InitDLL
791 static BOOL MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
793 WCHAR mod_name[32];
794 BOOL retv = TRUE;
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;
804 if (TRACE_ON(relay))
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
820 deleted. */
821 if (TRACE_ON(relay))
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 );
827 return retv;
831 /*************************************************************************
832 * process_attach
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
847 * routines.)
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;
865 int i;
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 ) )
872 return status;
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;
890 current_modref = wm;
891 if (MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved ))
893 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
895 else
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 );
913 return status;
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 )
925 for (;;)
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 process_attach( CONTAINING_RECORD(mod, WINE_MODREF, ldr), reserved );
938 break; /* restart the search from the start */
940 if (entry == mark) break; /* nothing found */
945 /*************************************************************************
946 * process_detach
948 * Send DLL process detach notifications. See the comment about calling
949 * sequence at process_attach. Unless the bForceDetach flag
950 * is set, only DLLs with zero refcount are notified.
952 static void process_detach( BOOL bForceDetach, LPVOID lpReserved )
954 PLIST_ENTRY mark, entry;
955 PLDR_MODULE mod;
957 RtlEnterCriticalSection( &loader_section );
958 if (bForceDetach) process_detaching = 1;
959 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
962 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
964 mod = CONTAINING_RECORD(entry, LDR_MODULE,
965 InInitializationOrderModuleList);
966 /* Check whether to detach this DLL */
967 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
968 continue;
969 if ( mod->LoadCount && !bForceDetach )
970 continue;
972 /* Call detach notification */
973 mod->Flags &= ~LDR_PROCESS_ATTACHED;
974 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
975 DLL_PROCESS_DETACH, lpReserved );
977 /* Restart at head of WINE_MODREF list, as entries might have
978 been added and/or removed while performing the call ... */
979 break;
981 } while (entry != mark);
983 RtlLeaveCriticalSection( &loader_section );
986 /*************************************************************************
987 * MODULE_DllThreadAttach
989 * Send DLL thread attach notifications. These are sent in the
990 * reverse sequence of process detach notification.
993 NTSTATUS MODULE_DllThreadAttach( LPVOID lpReserved )
995 PLIST_ENTRY mark, entry;
996 PLDR_MODULE mod;
997 NTSTATUS status;
999 /* don't do any attach calls if process is exiting */
1000 if (process_detaching) return STATUS_SUCCESS;
1001 /* FIXME: there is still a race here */
1003 RtlEnterCriticalSection( &loader_section );
1005 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto done;
1007 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1008 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1010 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1011 InInitializationOrderModuleList);
1012 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1013 continue;
1014 if ( mod->Flags & LDR_NO_DLL_CALLS )
1015 continue;
1017 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1018 DLL_THREAD_ATTACH, lpReserved );
1021 done:
1022 RtlLeaveCriticalSection( &loader_section );
1023 return status;
1026 /******************************************************************
1027 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1030 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1032 WINE_MODREF *wm;
1033 NTSTATUS ret = STATUS_SUCCESS;
1035 RtlEnterCriticalSection( &loader_section );
1037 wm = get_modref( hModule );
1038 if (!wm || wm->ldr.TlsIndex != -1)
1039 ret = STATUS_DLL_NOT_FOUND;
1040 else
1041 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1043 RtlLeaveCriticalSection( &loader_section );
1045 return ret;
1048 /******************************************************************
1049 * LdrFindEntryForAddress (NTDLL.@)
1051 * The loader_section must be locked while calling this function
1053 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
1055 PLIST_ENTRY mark, entry;
1056 PLDR_MODULE mod;
1058 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1059 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1061 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
1062 if ((const void *)mod->BaseAddress <= addr &&
1063 (const char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
1065 *pmod = mod;
1066 return STATUS_SUCCESS;
1068 if ((const void *)mod->BaseAddress > addr) break;
1070 return STATUS_NO_MORE_ENTRIES;
1073 /******************************************************************
1074 * LdrLockLoaderLock (NTDLL.@)
1076 * Note: flags are not implemented.
1077 * Flag 0x01 is used to raise exceptions on errors.
1078 * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
1080 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG *magic )
1082 if (flags) FIXME( "flags %lx not supported\n", flags );
1084 if (result) *result = 1;
1085 if (!magic) return STATUS_INVALID_PARAMETER_3;
1086 RtlEnterCriticalSection( &loader_section );
1087 *magic = GetCurrentThreadId();
1088 return STATUS_SUCCESS;
1092 /******************************************************************
1093 * LdrUnlockLoaderUnlock (NTDLL.@)
1095 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG magic )
1097 if (magic)
1099 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1100 RtlLeaveCriticalSection( &loader_section );
1102 return STATUS_SUCCESS;
1106 /******************************************************************
1107 * LdrGetDllHandle (NTDLL.@)
1109 NTSTATUS WINAPI LdrGetDllHandle(ULONG x, ULONG y, const UNICODE_STRING *name, HMODULE *base)
1111 NTSTATUS status = STATUS_DLL_NOT_FOUND;
1112 WCHAR dllname[MAX_PATH+4], *p;
1113 UNICODE_STRING str;
1114 PLIST_ENTRY mark, entry;
1115 PLDR_MODULE mod;
1117 if (x != 0 || y != 0)
1118 FIXME("Unknown behavior, please report\n");
1120 /* Append .DLL to name if no extension present */
1121 if (!(p = strrchrW( name->Buffer, '.')) || strchrW( p, '/' ) || strchrW( p, '\\'))
1123 if (name->Length >= MAX_PATH) return STATUS_NAME_TOO_LONG;
1124 strcpyW( dllname, name->Buffer );
1125 strcatW( dllname, dllW );
1126 RtlInitUnicodeString( &str, dllname );
1127 name = &str;
1130 RtlEnterCriticalSection( &loader_section );
1132 if (cached_modref)
1134 if (RtlEqualUnicodeString( name, &cached_modref->ldr.FullDllName, TRUE ) ||
1135 RtlEqualUnicodeString( name, &cached_modref->ldr.BaseDllName, TRUE ))
1137 *base = cached_modref->ldr.BaseAddress;
1138 status = STATUS_SUCCESS;
1139 goto done;
1143 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1144 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1146 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1148 if (RtlEqualUnicodeString( name, &mod->FullDllName, TRUE ) ||
1149 RtlEqualUnicodeString( name, &mod->BaseDllName, TRUE ))
1151 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1152 *base = mod->BaseAddress;
1153 status = STATUS_SUCCESS;
1154 break;
1157 done:
1158 RtlLeaveCriticalSection( &loader_section );
1159 TRACE("%lx %lx %s -> %p\n", x, y, debugstr_us(name), status ? NULL : *base);
1160 return status;
1164 /******************************************************************
1165 * LdrGetProcedureAddress (NTDLL.@)
1167 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1168 ULONG ord, PVOID *address)
1170 IMAGE_EXPORT_DIRECTORY *exports;
1171 DWORD exp_size;
1172 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1174 RtlEnterCriticalSection( &loader_section );
1176 /* check if the module itself is invalid to return the proper error */
1177 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1178 else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1179 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1181 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1 )
1182 : find_ordinal_export( module, exports, exp_size, ord - exports->Base );
1183 if (proc)
1185 *address = proc;
1186 ret = STATUS_SUCCESS;
1190 RtlLeaveCriticalSection( &loader_section );
1191 return ret;
1195 /***********************************************************************
1196 * load_builtin_callback
1198 * Load a library in memory; callback function for wine_dll_register
1200 static void load_builtin_callback( void *module, const char *filename )
1202 static const WCHAR emptyW[1];
1203 void *addr;
1204 IMAGE_NT_HEADERS *nt;
1205 WINE_MODREF *wm;
1206 WCHAR *fullname, *p;
1207 const WCHAR *load_path;
1209 if (!module)
1211 ERR("could not map image for %s\n", filename ? filename : "main exe" );
1212 return;
1214 if (!(nt = RtlImageNtHeader( module )))
1216 ERR( "bad module for %s\n", filename ? filename : "main exe" );
1217 builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1218 return;
1220 addr = module;
1221 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 0, &nt->OptionalHeader.SizeOfImage,
1222 MEM_SYSTEM | MEM_IMAGE, PAGE_EXECUTE_WRITECOPY );
1223 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL))
1225 /* if we already have an executable, ignore this one */
1226 if (!NtCurrentTeb()->Peb->ImageBaseAddress)
1228 NtCurrentTeb()->Peb->ImageBaseAddress = module;
1229 return; /* don't create the modref here, will be done later on */
1233 /* create the MODREF */
1235 if (!(fullname = RtlAllocateHeap( GetProcessHeap(), 0,
1236 system_dir.MaximumLength + (strlen(filename) + 1) * sizeof(WCHAR) )))
1238 ERR( "can't load %s\n", filename );
1239 builtin_load_info->status = STATUS_NO_MEMORY;
1240 return;
1242 memcpy( fullname, system_dir.Buffer, system_dir.Length );
1243 p = fullname + system_dir.Length / sizeof(WCHAR);
1244 if (p > fullname && p[-1] != '\\') *p++ = '\\';
1245 ascii_to_unicode( p, filename, strlen(filename) + 1 );
1247 wm = alloc_module( module, fullname );
1248 RtlFreeHeap( GetProcessHeap(), 0, fullname );
1249 if (!wm)
1251 ERR( "can't load %s\n", filename );
1252 builtin_load_info->status = STATUS_NO_MEMORY;
1253 return;
1255 wm->ldr.Flags |= LDR_WINE_INTERNAL;
1257 /* fixup imports */
1259 load_path = builtin_load_info->load_path;
1260 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1261 if (!load_path) load_path = emptyW;
1262 if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1264 /* the module has only be inserted in the load & memory order lists */
1265 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1266 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1267 /* FIXME: free the modref */
1268 builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1269 return;
1271 builtin_load_info->wm = wm;
1272 TRACE( "loaded %s %p %p\n", filename, wm, module );
1274 /* send the DLL load event */
1276 SERVER_START_REQ( load_dll )
1278 req->handle = 0;
1279 req->base = module;
1280 req->size = nt->OptionalHeader.SizeOfImage;
1281 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1282 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1283 req->name = &wm->ldr.FullDllName.Buffer;
1284 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1285 wine_server_call( req );
1287 SERVER_END_REQ;
1289 /* setup relay debugging entry points */
1290 if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1294 /******************************************************************************
1295 * load_native_dll (internal)
1297 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1298 DWORD flags, WINE_MODREF** pwm )
1300 void *module;
1301 HANDLE mapping;
1302 OBJECT_ATTRIBUTES attr;
1303 LARGE_INTEGER size;
1304 IMAGE_NT_HEADERS *nt;
1305 SIZE_T len = 0;
1306 WINE_MODREF *wm;
1307 NTSTATUS status;
1309 TRACE( "loading %s\n", debugstr_w(name) );
1311 attr.Length = sizeof(attr);
1312 attr.RootDirectory = 0;
1313 attr.ObjectName = NULL;
1314 attr.Attributes = 0;
1315 attr.SecurityDescriptor = NULL;
1316 attr.SecurityQualityOfService = NULL;
1317 size.QuadPart = 0;
1319 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1320 &attr, &size, 0, SEC_IMAGE, file );
1321 if (status != STATUS_SUCCESS) return status;
1323 module = NULL;
1324 status = NtMapViewOfSection( mapping, NtCurrentProcess(),
1325 &module, 0, 0, &size, &len, ViewShare, 0, PAGE_READONLY );
1326 NtClose( mapping );
1327 if (status != STATUS_SUCCESS) return status;
1329 /* create the MODREF */
1331 if (!(wm = alloc_module( module, name ))) return STATUS_NO_MEMORY;
1333 /* fixup imports */
1335 if (!(flags & DONT_RESOLVE_DLL_REFERENCES))
1337 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1339 /* the module has only be inserted in the load & memory order lists */
1340 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1341 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1343 /* FIXME: there are several more dangling references
1344 * left. Including dlls loaded by this dll before the
1345 * failed one. Unrolling is rather difficult with the
1346 * current structure and we can leave them lying
1347 * around with no problems, so we don't care.
1348 * As these might reference our wm, we don't free it.
1350 return status;
1353 else wm->ldr.Flags |= LDR_DONT_RESOLVE_REFS;
1355 /* send DLL load event */
1357 nt = RtlImageNtHeader( module );
1359 /* don't keep the file open if the mapping is from removable media */
1360 if (!VIRTUAL_HasMapping( module )) file = 0;
1362 SERVER_START_REQ( load_dll )
1364 req->handle = file;
1365 req->base = module;
1366 req->size = nt->OptionalHeader.SizeOfImage;
1367 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1368 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1369 req->name = &wm->ldr.FullDllName.Buffer;
1370 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1371 wine_server_call( req );
1373 SERVER_END_REQ;
1375 if (TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1377 TRACE_(loaddll)( " Loaded module %s : native\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
1379 *pwm = wm;
1380 return STATUS_SUCCESS;
1384 /***********************************************************************
1385 * load_builtin_dll
1387 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, DWORD flags, WINE_MODREF** pwm )
1389 char error[256], dllname[MAX_PATH];
1390 int file_exists;
1391 const WCHAR *name, *p;
1392 DWORD len, i;
1393 void *handle;
1394 struct builtin_load_info info, *prev_info;
1396 /* Fix the name in case we have a full path and extension */
1397 name = path;
1398 if ((p = strrchrW( name, '\\' ))) name = p + 1;
1399 if ((p = strrchrW( name, '/' ))) name = p + 1;
1401 /* we don't want to depend on the current codepage here */
1402 len = strlenW( name ) + 1;
1403 if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1404 for (i = 0; i < len; i++)
1406 if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1407 dllname[i] = (char)name[i];
1408 if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1411 /* load_library will modify info.status. Note also that load_library can be
1412 * called several times, if the .so file we're loading has dependencies.
1413 * info.status will gather all the errors we may get while loading all these
1414 * libraries
1416 info.load_path = load_path;
1417 info.status = STATUS_SUCCESS;
1418 info.wm = NULL;
1419 prev_info = builtin_load_info;
1420 builtin_load_info = &info;
1421 handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1422 builtin_load_info = prev_info;
1424 if (!handle)
1426 if (!file_exists)
1428 /* The file does not exist -> WARN() */
1429 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
1430 return STATUS_DLL_NOT_FOUND;
1432 /* ERR() for all other errors (missing functions, ...) */
1433 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
1434 return STATUS_PROCEDURE_NOT_FOUND;
1436 if (info.status != STATUS_SUCCESS) return info.status;
1438 if (!info.wm)
1440 /* The constructor wasn't called, this means the .so is already
1441 * loaded under a different name. We can't support multiple names
1442 * for the same module, so return an error. */
1443 return STATUS_INVALID_IMAGE_FORMAT;
1446 TRACE_(loaddll)( "Loaded module %s : builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer) );
1448 info.wm->ldr.SectionHandle = handle;
1449 if (strcmpiW( info.wm->ldr.BaseDllName.Buffer, name ))
1451 ERR( "loaded .so for %s but got %s instead - probably 16-bit dll\n",
1452 debugstr_w(name), debugstr_w(info.wm->ldr.BaseDllName.Buffer) );
1453 /* wine_dll_unload( handle );*/
1454 return STATUS_INVALID_IMAGE_FORMAT;
1456 *pwm = info.wm;
1457 return STATUS_SUCCESS;
1461 /***********************************************************************
1462 * find_dll_file
1464 * Find the file (or already loaded module) for a given dll name.
1466 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
1467 WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
1469 OBJECT_ATTRIBUTES attr;
1470 IO_STATUS_BLOCK io;
1471 UNICODE_STRING nt_name;
1472 WCHAR *file_part, *ext, *dllname;
1473 ULONG len;
1475 /* first append .dll if needed */
1477 dllname = NULL;
1478 if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
1480 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
1481 (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
1482 return STATUS_NO_MEMORY;
1483 strcpyW( dllname, libname );
1484 strcatW( dllname, dllW );
1485 libname = dllname;
1488 nt_name.Buffer = NULL;
1489 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
1491 /* we need to search for it */
1492 len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
1493 if (len)
1495 if (len >= *size) goto overflow;
1496 if ((*pwm = find_fullname_module( filename )) != NULL) goto found;
1498 /* check for already loaded module in a different path */
1499 if (!contains_path( libname ))
1501 if ((*pwm = find_basename_module( file_part )) != NULL) goto found;
1503 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
1505 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1506 return STATUS_NO_MEMORY;
1508 attr.Length = sizeof(attr);
1509 attr.RootDirectory = 0;
1510 attr.Attributes = OBJ_CASE_INSENSITIVE;
1511 attr.ObjectName = &nt_name;
1512 attr.SecurityDescriptor = NULL;
1513 attr.SecurityQualityOfService = NULL;
1514 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1515 goto found;
1518 /* not found */
1520 if (!contains_path( libname ))
1522 /* if libname doesn't contain a path at all, we simply return the name as is,
1523 * to be loaded as builtin */
1524 len = strlenW(libname) * sizeof(WCHAR);
1525 if (len >= *size) goto overflow;
1526 strcpyW( filename, libname );
1527 *pwm = find_basename_module( filename );
1528 goto found;
1532 /* absolute path name, or relative path name but not found above */
1534 if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
1536 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1537 return STATUS_NO_MEMORY;
1539 len = nt_name.Length - 4*sizeof(WCHAR); /* for \??\ prefix */
1540 if (len >= *size) goto overflow;
1541 memcpy( filename, nt_name.Buffer + 4, len + sizeof(WCHAR) );
1542 if (!(*pwm = find_fullname_module( filename )))
1544 attr.Length = sizeof(attr);
1545 attr.RootDirectory = 0;
1546 attr.Attributes = OBJ_CASE_INSENSITIVE;
1547 attr.ObjectName = &nt_name;
1548 attr.SecurityDescriptor = NULL;
1549 attr.SecurityQualityOfService = NULL;
1550 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1552 found:
1553 RtlFreeUnicodeString( &nt_name );
1554 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1555 return STATUS_SUCCESS;
1557 overflow:
1558 RtlFreeUnicodeString( &nt_name );
1559 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1560 *size = len + sizeof(WCHAR);
1561 return STATUS_BUFFER_TOO_SMALL;
1565 /***********************************************************************
1566 * load_dll (internal)
1568 * Load a PE style module according to the load order.
1569 * The loader_section must be locked while calling this function.
1571 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
1573 int i;
1574 enum loadorder_type loadorder[LOADORDER_NTYPES];
1575 WCHAR buffer[32];
1576 WCHAR *filename;
1577 ULONG size;
1578 const char *filetype = "";
1579 WINE_MODREF *main_exe;
1580 HANDLE handle = 0;
1581 NTSTATUS nts;
1583 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
1585 filename = buffer;
1586 size = sizeof(buffer);
1587 for (;;)
1589 nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
1590 if (nts == STATUS_SUCCESS) break;
1591 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1592 if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
1593 /* grow the buffer and retry */
1594 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
1597 if (*pwm) /* found already loaded module */
1599 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
1601 if (((*pwm)->ldr.Flags & LDR_DONT_RESOLVE_REFS) &&
1602 !(flags & DONT_RESOLVE_DLL_REFERENCES))
1604 (*pwm)->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
1605 fixup_imports( *pwm, load_path );
1607 TRACE("Found loaded module %s for %s at %p, count=%d\n",
1608 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
1609 (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
1610 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1611 return STATUS_SUCCESS;
1614 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
1615 MODULE_GetLoadOrderW( loadorder, main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
1617 nts = STATUS_DLL_NOT_FOUND;
1618 for (i = 0; i < LOADORDER_NTYPES; i++)
1620 if (loadorder[i] == LOADORDER_INVALID) break;
1622 switch (loadorder[i])
1624 case LOADORDER_DLL:
1625 TRACE("Trying native dll %s\n", debugstr_w(filename));
1626 if (!handle) continue; /* it cannot possibly be loaded */
1627 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1628 filetype = "native";
1629 break;
1630 case LOADORDER_BI:
1631 TRACE("Trying built-in %s\n", debugstr_w(filename));
1632 nts = load_builtin_dll( load_path, filename, flags, pwm );
1633 filetype = "builtin";
1634 break;
1635 default:
1636 nts = STATUS_INTERNAL_ERROR;
1637 break;
1640 if (nts == STATUS_SUCCESS)
1642 /* Initialize DLL just loaded */
1643 TRACE("Loaded module %s (%s) at %p\n",
1644 debugstr_w(filename), filetype, (*pwm)->ldr.BaseAddress);
1645 /* Set the ldr.LoadCount here so that an attach failure will */
1646 /* decrement the dependencies through the MODULE_FreeLibrary call. */
1647 (*pwm)->ldr.LoadCount = 1;
1648 if (handle) NtClose( handle );
1649 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1650 return nts;
1652 if (nts != STATUS_DLL_NOT_FOUND) break;
1655 WARN("Failed to load module %s; status=%lx\n", debugstr_w(libname), nts);
1656 if (handle) NtClose( handle );
1657 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1658 return nts;
1661 /******************************************************************
1662 * LdrLoadDll (NTDLL.@)
1664 NTSTATUS WINAPI LdrLoadDll(LPCWSTR path_name, DWORD flags,
1665 const UNICODE_STRING *libname, HMODULE* hModule)
1667 WINE_MODREF *wm;
1668 NTSTATUS nts;
1670 RtlEnterCriticalSection( &loader_section );
1672 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1673 nts = load_dll( path_name, libname->Buffer, flags, &wm );
1675 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
1677 nts = process_attach( wm, NULL );
1678 if (nts != STATUS_SUCCESS)
1680 LdrUnloadDll(wm->ldr.BaseAddress);
1681 wm = NULL;
1684 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
1686 RtlLeaveCriticalSection( &loader_section );
1687 return nts;
1690 /******************************************************************
1691 * LdrQueryProcessModuleInformation
1694 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
1695 ULONG buf_size, ULONG* req_size)
1697 SYSTEM_MODULE* sm = &smi->Modules[0];
1698 ULONG size = sizeof(ULONG);
1699 NTSTATUS nts = STATUS_SUCCESS;
1700 ANSI_STRING str;
1701 char* ptr;
1702 PLIST_ENTRY mark, entry;
1703 PLDR_MODULE mod;
1705 smi->ModulesCount = 0;
1707 RtlEnterCriticalSection( &loader_section );
1708 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1709 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1711 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1712 size += sizeof(*sm);
1713 if (size <= buf_size)
1715 sm->Reserved1 = 0; /* FIXME */
1716 sm->Reserved2 = 0; /* FIXME */
1717 sm->ImageBaseAddress = mod->BaseAddress;
1718 sm->ImageSize = mod->SizeOfImage;
1719 sm->Flags = mod->Flags;
1720 sm->Id = 0; /* FIXME */
1721 sm->Rank = 0; /* FIXME */
1722 sm->Unknown = 0; /* FIXME */
1723 str.Length = 0;
1724 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
1725 str.Buffer = (char*)sm->Name;
1726 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
1727 ptr = strrchr(str.Buffer, '\\');
1728 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
1730 smi->ModulesCount++;
1731 sm++;
1733 else nts = STATUS_INFO_LENGTH_MISMATCH;
1735 RtlLeaveCriticalSection( &loader_section );
1737 if (req_size) *req_size = size;
1739 return nts;
1742 /******************************************************************
1743 * LdrShutdownProcess (NTDLL.@)
1746 void WINAPI LdrShutdownProcess(void)
1748 TRACE("()\n");
1749 process_detach( TRUE, (LPVOID)1 );
1752 /******************************************************************
1753 * LdrShutdownThread (NTDLL.@)
1756 void WINAPI LdrShutdownThread(void)
1758 PLIST_ENTRY mark, entry;
1759 PLDR_MODULE mod;
1761 TRACE("()\n");
1763 /* don't do any detach calls if process is exiting */
1764 if (process_detaching) return;
1765 /* FIXME: there is still a race here */
1767 RtlEnterCriticalSection( &loader_section );
1769 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1770 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1772 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1773 InInitializationOrderModuleList);
1774 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1775 continue;
1776 if ( mod->Flags & LDR_NO_DLL_CALLS )
1777 continue;
1779 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1780 DLL_THREAD_DETACH, NULL );
1783 RtlLeaveCriticalSection( &loader_section );
1786 /***********************************************************************
1787 * MODULE_FlushModrefs
1789 * Remove all unused modrefs and call the internal unloading routines
1790 * for the library type.
1792 * The loader_section must be locked while calling this function.
1794 static void MODULE_FlushModrefs(void)
1796 PLIST_ENTRY mark, entry, prev;
1797 PLDR_MODULE mod;
1798 WINE_MODREF*wm;
1800 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1801 for (entry = mark->Blink; entry != mark; entry = prev)
1803 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1804 InInitializationOrderModuleList);
1805 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1807 prev = entry->Blink;
1808 if (mod->LoadCount) continue;
1810 RemoveEntryList(&mod->InLoadOrderModuleList);
1811 RemoveEntryList(&mod->InMemoryOrderModuleList);
1812 RemoveEntryList(&mod->InInitializationOrderModuleList);
1814 TRACE(" unloading %s\n", debugstr_w(mod->FullDllName.Buffer));
1815 if (!TRACE_ON(module))
1816 TRACE_(loaddll)("Unloaded module %s : %s\n",
1817 debugstr_w(mod->FullDllName.Buffer),
1818 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
1820 SERVER_START_REQ( unload_dll )
1822 req->base = mod->BaseAddress;
1823 wine_server_call( req );
1825 SERVER_END_REQ;
1827 NtUnmapViewOfSection( NtCurrentProcess(), mod->BaseAddress );
1828 if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
1829 if (cached_modref == wm) cached_modref = NULL;
1830 RtlFreeUnicodeString( &mod->FullDllName );
1831 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
1832 RtlFreeHeap( GetProcessHeap(), 0, wm );
1836 /***********************************************************************
1837 * MODULE_DecRefCount
1839 * The loader_section must be locked while calling this function.
1841 static void MODULE_DecRefCount( WINE_MODREF *wm )
1843 int i;
1845 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
1846 return;
1848 if ( wm->ldr.LoadCount <= 0 )
1849 return;
1851 --wm->ldr.LoadCount;
1852 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
1854 if ( wm->ldr.LoadCount == 0 )
1856 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
1858 for ( i = 0; i < wm->nDeps; i++ )
1859 if ( wm->deps[i] )
1860 MODULE_DecRefCount( wm->deps[i] );
1862 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
1866 /******************************************************************
1867 * LdrUnloadDll (NTDLL.@)
1871 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
1873 NTSTATUS retv = STATUS_SUCCESS;
1875 TRACE("(%p)\n", hModule);
1877 RtlEnterCriticalSection( &loader_section );
1879 /* if we're stopping the whole process (and forcing the removal of all
1880 * DLLs) the library will be freed anyway
1882 if (!process_detaching)
1884 WINE_MODREF *wm;
1886 free_lib_count++;
1887 if ((wm = get_modref( hModule )) != NULL)
1889 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
1891 /* Recursively decrement reference counts */
1892 MODULE_DecRefCount( wm );
1894 /* Call process detach notifications */
1895 if ( free_lib_count <= 1 )
1897 process_detach( FALSE, NULL );
1898 MODULE_FlushModrefs();
1901 TRACE("END\n");
1903 else
1904 retv = STATUS_DLL_NOT_FOUND;
1906 free_lib_count--;
1909 RtlLeaveCriticalSection( &loader_section );
1911 return retv;
1914 /***********************************************************************
1915 * RtlImageNtHeader (NTDLL.@)
1917 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
1919 IMAGE_NT_HEADERS *ret;
1921 __TRY
1923 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
1925 ret = NULL;
1926 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
1928 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
1929 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
1932 __EXCEPT_PAGE_FAULT
1934 return NULL;
1936 __ENDTRY
1937 return ret;
1941 /******************************************************************
1942 * LdrInitializeThunk (NTDLL.@)
1944 * FIXME: the arguments are not correct, main_file is a Wine invention.
1946 void WINAPI LdrInitializeThunk( HANDLE main_file, ULONG unknown2, ULONG unknown3, ULONG unknown4 )
1948 NTSTATUS status;
1949 WINE_MODREF *wm;
1950 LPCWSTR load_path;
1951 PEB *peb = NtCurrentTeb()->Peb;
1952 UNICODE_STRING *main_exe_name = &peb->ProcessParameters->ImagePathName;
1953 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
1955 version_init( main_exe_name->Buffer );
1957 /* allocate the modref for the main exe */
1958 if (!(wm = alloc_module( peb->ImageBaseAddress, main_exe_name->Buffer )))
1960 status = STATUS_NO_MEMORY;
1961 goto error;
1963 wm->ldr.LoadCount = -1; /* can't unload main exe */
1965 /* the main exe needs to be the first in the load order list */
1966 RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
1967 InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
1969 /* Install signal handlers; this cannot be done before, since we cannot
1970 * send exceptions to the debugger before the create process event that
1971 * is sent by REQ_INIT_PROCESS_DONE.
1972 * We do need the handlers in place by the time the request is over, so
1973 * we set them up here. If we segfault between here and the server call
1974 * something is very wrong... */
1975 if (!SIGNAL_Init()) exit(1);
1977 /* Signal the parent process to continue */
1978 SERVER_START_REQ( init_process_done )
1980 req->module = peb->ImageBaseAddress;
1981 req->module_size = wm->ldr.SizeOfImage;
1982 req->entry = (char *)peb->ImageBaseAddress + nt->OptionalHeader.AddressOfEntryPoint;
1983 /* API requires a double indirection */
1984 req->name = &main_exe_name->Buffer;
1985 req->exe_file = main_file;
1986 req->gui = (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_WINDOWS_CUI);
1987 wine_server_add_data( req, main_exe_name->Buffer, main_exe_name->Length );
1988 wine_server_call( req );
1990 SERVER_END_REQ;
1992 if (main_file) NtClose( main_file ); /* we no longer need it */
1994 RtlEnterCriticalSection( &loader_section );
1996 load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1997 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
1998 if ((status = alloc_process_tls()) != STATUS_SUCCESS) goto error;
1999 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto error;
2000 if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS)
2002 if (last_failed_modref)
2003 ERR( "%s failed to initialize, aborting\n", debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
2004 goto error;
2006 attach_implicitly_loaded_dlls( (LPVOID)1 );
2008 RtlLeaveCriticalSection( &loader_section );
2010 if (nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE) VIRTUAL_UseLargeAddressSpace();
2011 return;
2013 error:
2014 ERR( "Main exe initialization for %s failed, status %lx\n", debugstr_w(main_exe_name->Buffer), status );
2015 exit(1);
2019 /***********************************************************************
2020 * RtlImageDirectoryEntryToData (NTDLL.@)
2022 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
2024 const IMAGE_NT_HEADERS *nt;
2025 DWORD addr;
2027 if ((ULONG_PTR)module & 1) /* mapped as data file */
2029 module = (HMODULE)((ULONG_PTR)module & ~1);
2030 image = FALSE;
2032 if (!(nt = RtlImageNtHeader( module ))) return NULL;
2033 if (dir >= nt->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2034 if (!(addr = nt->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2035 *size = nt->OptionalHeader.DataDirectory[dir].Size;
2036 if (image || addr < nt->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2038 /* not mapped as image, need to find the section containing the virtual address */
2039 return RtlImageRvaToVa( nt, module, addr, NULL );
2043 /***********************************************************************
2044 * RtlImageRvaToSection (NTDLL.@)
2046 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
2047 HMODULE module, DWORD rva )
2049 int i;
2050 const IMAGE_SECTION_HEADER *sec;
2052 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
2053 nt->FileHeader.SizeOfOptionalHeader);
2054 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
2056 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2057 return (PIMAGE_SECTION_HEADER)sec;
2059 return NULL;
2063 /***********************************************************************
2064 * RtlImageRvaToVa (NTDLL.@)
2066 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
2067 DWORD rva, IMAGE_SECTION_HEADER **section )
2069 IMAGE_SECTION_HEADER *sec;
2071 if (section && *section) /* try this section first */
2073 sec = *section;
2074 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2075 goto found;
2077 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
2078 found:
2079 if (section) *section = sec;
2080 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
2084 /***********************************************************************
2085 * NtLoadDriver (NTDLL.@)
2086 * ZwLoadDriver (NTDLL.@)
2088 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
2090 FIXME("(%p), stub!\n",DriverServiceName);
2091 return STATUS_NOT_IMPLEMENTED;
2095 /***********************************************************************
2096 * NtUnloadDriver (NTDLL.@)
2097 * ZwUnloadDriver (NTDLL.@)
2099 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
2101 FIXME("(%p), stub!\n",DriverServiceName);
2102 return STATUS_NOT_IMPLEMENTED;
2106 /******************************************************************
2107 * DllMain (NTDLL.@)
2109 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
2111 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
2112 return TRUE;
2116 /******************************************************************
2117 * __wine_init_windows_dir (NTDLL.@)
2119 * Windows and system dir initialization once kernel32 has been loaded.
2121 void __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
2123 PLIST_ENTRY mark, entry;
2124 LPWSTR buffer, p;
2126 RtlCreateUnicodeString( &system_dir, sysdir );
2128 /* prepend the system dir to the name of the already created modules */
2129 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2130 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2132 LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
2134 assert( mod->Flags & LDR_WINE_INTERNAL );
2136 buffer = RtlAllocateHeap( GetProcessHeap(), 0,
2137 system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
2138 if (!buffer) continue;
2139 strcpyW( buffer, system_dir.Buffer );
2140 p = buffer + strlenW( buffer );
2141 if (p > buffer && p[-1] != '\\') *p++ = '\\';
2142 strcpyW( p, mod->FullDllName.Buffer );
2143 RtlInitUnicodeString( &mod->FullDllName, buffer );
2144 RtlInitUnicodeString( &mod->BaseDllName, p );
2149 /***********************************************************************
2150 * __wine_process_init
2152 void __wine_process_init( int argc, char *argv[] )
2154 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
2156 WINE_MODREF *wm;
2157 NTSTATUS status;
2158 ANSI_STRING func_name;
2159 void (* DECLSPEC_NORETURN init_func)();
2160 extern mode_t FILE_umask;
2162 thread_init();
2164 /* retrieve current umask */
2165 FILE_umask = umask(0777);
2166 umask( FILE_umask );
2168 /* setup the load callback and create ntdll modref */
2169 wine_dll_set_callback( load_builtin_callback );
2171 if ((status = load_builtin_dll( NULL, kernel32W, 0, &wm )) != STATUS_SUCCESS)
2173 MESSAGE( "wine: could not load kernel32.dll, status %lx\n", status );
2174 exit(1);
2176 RtlInitAnsiString( &func_name, "__wine_kernel_init" );
2177 if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
2178 0, (void **)&init_func )) != STATUS_SUCCESS)
2180 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %lx\n", status );
2181 exit(1);
2183 init_func();