- call CertFreeCertificateContext from CertDeleteCertificateFromStore
[wine/multimedia.git] / dlls / ntdll / loader.c
blobfa04f82132e633ed2548014da3ca4ebff65b3f68
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 "windef.h"
32 #include "winnt.h"
33 #include "winternl.h"
35 #include "module.h"
36 #include "wine/exception.h"
37 #include "excpt.h"
38 #include "wine/library.h"
39 #include "wine/unicode.h"
40 #include "wine/debug.h"
41 #include "wine/server.h"
42 #include "ntdll_misc.h"
44 WINE_DEFAULT_DEBUG_CHANNEL(module);
45 WINE_DECLARE_DEBUG_CHANNEL(relay);
46 WINE_DECLARE_DEBUG_CHANNEL(snoop);
47 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
48 WINE_DECLARE_DEBUG_CHANNEL(imports);
50 typedef DWORD (CALLBACK *DLLENTRYPROC)(HMODULE,DWORD,LPVOID);
52 static int process_detaching = 0; /* set on process detach to avoid deadlocks with thread detach */
53 static int free_lib_count; /* recursion depth of LdrUnloadDll calls */
55 /* filter for page-fault exceptions */
56 static WINE_EXCEPTION_FILTER(page_fault)
58 if (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION)
59 return EXCEPTION_EXECUTE_HANDLER;
60 return EXCEPTION_CONTINUE_SEARCH;
63 static const char * const reason_names[] =
65 "PROCESS_DETACH",
66 "PROCESS_ATTACH",
67 "THREAD_ATTACH",
68 "THREAD_DETACH"
71 static const WCHAR dllW[] = {'.','d','l','l',0};
73 /* internal representation of 32bit modules. per process. */
74 typedef struct _wine_modref
76 LDR_MODULE ldr;
77 int nDeps;
78 struct _wine_modref **deps;
79 } WINE_MODREF;
81 /* info about the current builtin dll load */
82 /* used to keep track of things across the register_dll constructor call */
83 struct builtin_load_info
85 const WCHAR *load_path;
86 NTSTATUS status;
87 WINE_MODREF *wm;
90 static struct builtin_load_info default_load_info;
91 static struct builtin_load_info *builtin_load_info = &default_load_info;
93 static UINT tls_module_count; /* number of modules with TLS directory */
94 static UINT tls_total_size; /* total size of TLS storage */
95 static const IMAGE_TLS_DIRECTORY **tls_dirs; /* array of TLS directories */
97 UNICODE_STRING system_dir = { 0, 0, NULL }; /* system directory */
99 static RTL_CRITICAL_SECTION loader_section;
100 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
102 0, 0, &loader_section,
103 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
104 0, 0, { 0, (DWORD)(__FILE__ ": loader_section") }
106 static RTL_CRITICAL_SECTION loader_section = { &critsect_debug, -1, 0, 0, 0, 0 };
108 static WINE_MODREF *cached_modref;
109 static WINE_MODREF *current_modref;
110 static WINE_MODREF *last_failed_modref;
112 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm );
113 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
114 DWORD exp_size, const char *name, int hint );
116 /* convert PE image VirtualAddress to Real Address */
117 inline static void *get_rva( HMODULE module, DWORD va )
119 return (void *)((char *)module + va);
122 /* check whether the file name contains a path */
123 inline static int contains_path( LPCWSTR name )
125 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
128 /* convert from straight ASCII to Unicode without depending on the current codepage */
129 inline static void ascii_to_unicode( WCHAR *dst, const char *src, size_t len )
131 while (len--) *dst++ = (unsigned char)*src++;
135 /*************************************************************************
136 * call_dll_entry_point
138 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
139 * their entry point, so we need a small asm wrapper.
141 #ifdef __i386__
142 extern BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module, UINT reason, void *reserved );
143 __ASM_GLOBAL_FUNC(call_dll_entry_point,
144 "pushl %ebp\n\t"
145 "movl %esp,%ebp\n\t"
146 "pushl %ebx\n\t"
147 "pushl 20(%ebp)\n\t"
148 "pushl 16(%ebp)\n\t"
149 "pushl 12(%ebp)\n\t"
150 "movl 8(%ebp),%eax\n\t"
151 "call *%eax\n\t"
152 "leal -4(%ebp),%esp\n\t"
153 "popl %ebx\n\t"
154 "popl %ebp\n\t"
155 "ret" );
156 #else /* __i386__ */
157 static inline BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module,
158 UINT reason, void *reserved )
160 return proc( module, reason, reserved );
162 #endif /* __i386__ */
165 #ifdef __i386__
166 /*************************************************************************
167 * stub_entry_point
169 * Entry point for stub functions.
171 static void stub_entry_point( const char *dll, const char *name, ... )
173 EXCEPTION_RECORD rec;
175 rec.ExceptionCode = EXCEPTION_WINE_STUB;
176 rec.ExceptionFlags = EH_NONCONTINUABLE;
177 rec.ExceptionRecord = NULL;
178 #ifdef __GNUC__
179 rec.ExceptionAddress = __builtin_return_address(0);
180 #else
181 rec.ExceptionAddress = *((void **)&dll - 1);
182 #endif
183 rec.NumberParameters = 2;
184 rec.ExceptionInformation[0] = (ULONG_PTR)dll;
185 rec.ExceptionInformation[1] = (ULONG_PTR)name;
186 for (;;) RtlRaiseException( &rec );
190 #include "pshpack1.h"
191 struct stub
193 BYTE popl_eax; /* popl %eax */
194 BYTE pushl1; /* pushl $name */
195 const char *name;
196 BYTE pushl2; /* pushl $dll */
197 const char *dll;
198 BYTE pushl_eax; /* pushl %eax */
199 BYTE jmp; /* jmp stub_entry_point */
200 DWORD entry;
202 #include "poppack.h"
204 /*************************************************************************
205 * allocate_stub
207 * Allocate a stub entry point.
209 static ULONG_PTR allocate_stub( const char *dll, const char *name )
211 #define MAX_SIZE 65536
212 static struct stub *stubs;
213 static unsigned int nb_stubs;
214 struct stub *stub;
216 if (nb_stubs >= MAX_SIZE / sizeof(*stub)) return 0xdeadbeef;
218 if (!stubs)
220 ULONG size = MAX_SIZE;
221 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs, 0, &size,
222 MEM_COMMIT, PAGE_EXECUTE_WRITECOPY ) != STATUS_SUCCESS)
223 return 0xdeadbeef;
225 stub = &stubs[nb_stubs++];
226 stub->popl_eax = 0x58; /* popl %eax */
227 stub->pushl1 = 0x68; /* pushl $name */
228 stub->name = name;
229 stub->pushl2 = 0x68; /* pushl $dll */
230 stub->dll = dll;
231 stub->pushl_eax = 0x50; /* pushl %eax */
232 stub->jmp = 0xe9; /* jmp stub_entry_point */
233 stub->entry = (BYTE *)stub_entry_point - (BYTE *)(&stub->entry + 1);
234 return (ULONG_PTR)stub;
237 #else /* __i386__ */
238 static inline ULONG_PTR allocate_stub( const char *dll, const char *name ) { return 0xdeadbeef; }
239 #endif /* __i386__ */
242 /*************************************************************************
243 * get_modref
245 * Looks for the referenced HMODULE in the current process
246 * The loader_section must be locked while calling this function.
248 static WINE_MODREF *get_modref( HMODULE hmod )
250 PLIST_ENTRY mark, entry;
251 PLDR_MODULE mod;
253 if (cached_modref && cached_modref->ldr.BaseAddress == hmod) return cached_modref;
255 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
256 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
258 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
259 if (mod->BaseAddress == hmod)
260 return cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
261 if (mod->BaseAddress > (void*)hmod) break;
263 return NULL;
267 /**********************************************************************
268 * find_basename_module
270 * Find a module from its base name.
271 * The loader_section must be locked while calling this function
273 static WINE_MODREF *find_basename_module( LPCWSTR name )
275 PLIST_ENTRY mark, entry;
277 if (cached_modref && !strcmpiW( name, cached_modref->ldr.BaseDllName.Buffer ))
278 return cached_modref;
280 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
281 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
283 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
284 if (!strcmpiW( name, mod->BaseDllName.Buffer ))
286 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
287 return cached_modref;
290 return NULL;
294 /**********************************************************************
295 * find_fullname_module
297 * Find a module from its full path name.
298 * The loader_section must be locked while calling this function
300 static WINE_MODREF *find_fullname_module( LPCWSTR name )
302 PLIST_ENTRY mark, entry;
304 if (cached_modref && !strcmpiW( name, cached_modref->ldr.FullDllName.Buffer ))
305 return cached_modref;
307 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
308 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
310 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
311 if (!strcmpiW( name, mod->FullDllName.Buffer ))
313 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
314 return cached_modref;
317 return NULL;
321 /*************************************************************************
322 * find_forwarded_export
324 * Find the final function pointer for a forwarded function.
325 * The loader_section must be locked while calling this function.
327 static FARPROC find_forwarded_export( HMODULE module, const char *forward )
329 const IMAGE_EXPORT_DIRECTORY *exports;
330 DWORD exp_size;
331 WINE_MODREF *wm;
332 WCHAR mod_name[32];
333 const char *end = strchr(forward, '.');
334 FARPROC proc = NULL;
336 if (!end) return NULL;
337 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name) - sizeof(dllW)) return NULL;
338 ascii_to_unicode( mod_name, forward, end - forward );
339 memcpy( mod_name + (end - forward), dllW, sizeof(dllW) );
341 if (!(wm = find_basename_module( mod_name )))
343 ERR("module not found for forward '%s' used by %s\n",
344 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer) );
345 return NULL;
347 if ((exports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
348 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
349 proc = find_named_export( wm->ldr.BaseAddress, exports, exp_size, end + 1, -1 );
351 if (!proc)
353 ERR("function not found for forward '%s' used by %s."
354 " If you are using builtin %s, try using the native one instead.\n",
355 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer),
356 debugstr_w(get_modref(module)->ldr.BaseDllName.Buffer) );
358 return proc;
362 /*************************************************************************
363 * find_ordinal_export
365 * Find an exported function by ordinal.
366 * The exports base must have been subtracted from the ordinal already.
367 * The loader_section must be locked while calling this function.
369 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
370 DWORD exp_size, int ordinal )
372 FARPROC proc;
373 const DWORD *functions = get_rva( module, exports->AddressOfFunctions );
375 if (ordinal >= exports->NumberOfFunctions)
377 TRACE(" ordinal %ld out of range!\n", ordinal + exports->Base );
378 return NULL;
380 if (!functions[ordinal]) return NULL;
382 proc = get_rva( module, functions[ordinal] );
384 /* if the address falls into the export dir, it's a forward */
385 if (((const char *)proc >= (const char *)exports) &&
386 ((const char *)proc < (const char *)exports + exp_size))
387 return find_forwarded_export( module, (const char *)proc );
389 if (TRACE_ON(snoop))
391 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
392 proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
394 if (TRACE_ON(relay))
396 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
397 proc = RELAY_GetProcAddress( module, exports, exp_size, proc, user );
399 return proc;
403 /*************************************************************************
404 * find_named_export
406 * Find an exported function by name.
407 * The loader_section must be locked while calling this function.
409 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
410 DWORD exp_size, const char *name, int hint )
412 const WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
413 const DWORD *names = get_rva( module, exports->AddressOfNames );
414 int min = 0, max = exports->NumberOfNames - 1;
416 /* first check the hint */
417 if (hint >= 0 && hint <= max)
419 char *ename = get_rva( module, names[hint] );
420 if (!strcmp( ename, name ))
421 return find_ordinal_export( module, exports, exp_size, ordinals[hint] );
424 /* then do a binary search */
425 while (min <= max)
427 int res, pos = (min + max) / 2;
428 char *ename = get_rva( module, names[pos] );
429 if (!(res = strcmp( ename, name )))
430 return find_ordinal_export( module, exports, exp_size, ordinals[pos] );
431 if (res > 0) max = pos - 1;
432 else min = pos + 1;
434 return NULL;
439 /*************************************************************************
440 * import_dll
442 * Import the dll specified by the given import descriptor.
443 * The loader_section must be locked while calling this function.
445 static WINE_MODREF *import_dll( HMODULE module, const IMAGE_IMPORT_DESCRIPTOR *descr, LPCWSTR load_path )
447 NTSTATUS status;
448 WINE_MODREF *wmImp;
449 HMODULE imp_mod;
450 const IMAGE_EXPORT_DIRECTORY *exports;
451 DWORD exp_size;
452 const IMAGE_THUNK_DATA *import_list;
453 IMAGE_THUNK_DATA *thunk_list;
454 WCHAR buffer[32];
455 const char *name = get_rva( module, descr->Name );
456 DWORD len = strlen(name) + 1;
457 PVOID protect_base;
458 DWORD protect_size = 0;
459 DWORD protect_old;
461 thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
462 if (descr->u.OriginalFirstThunk)
463 import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
464 else
465 import_list = thunk_list;
467 if (len * sizeof(WCHAR) <= sizeof(buffer))
469 ascii_to_unicode( buffer, name, len );
470 status = load_dll( load_path, buffer, 0, &wmImp );
472 else /* need to allocate a larger buffer */
474 WCHAR *ptr = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR) );
475 if (!ptr) return NULL;
476 ascii_to_unicode( ptr, name, len );
477 status = load_dll( load_path, ptr, 0, &wmImp );
478 RtlFreeHeap( GetProcessHeap(), 0, ptr );
481 if (status)
483 if (status == STATUS_DLL_NOT_FOUND)
484 ERR("Library %s (which is needed by %s) not found\n",
485 name, debugstr_w(current_modref->ldr.FullDllName.Buffer));
486 else
487 ERR("Loading library %s (which is needed by %s) failed (error %lx).\n",
488 name, debugstr_w(current_modref->ldr.FullDllName.Buffer), status);
489 return NULL;
492 /* unprotect the import address table since it can be located in
493 * readonly section */
494 while (import_list[protect_size].u1.Ordinal) protect_size++;
495 protect_base = thunk_list;
496 protect_size *= sizeof(*thunk_list);
497 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base,
498 &protect_size, PAGE_WRITECOPY, &protect_old );
500 imp_mod = wmImp->ldr.BaseAddress;
501 exports = RtlImageDirectoryEntryToData( imp_mod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
503 if (!exports)
505 /* set all imported function to deadbeef */
506 while (import_list->u1.Ordinal)
508 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
510 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
511 WARN("No implementation for %s.%d", name, ordinal );
512 thunk_list->u1.Function = allocate_stub( name, (const char *)ordinal );
514 else
516 IMAGE_IMPORT_BY_NAME *pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
517 WARN("No implementation for %s.%s", name, pe_name->Name );
518 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
520 WARN(" imported from %s, allocating stub %p\n",
521 debugstr_w(current_modref->ldr.FullDllName.Buffer),
522 (void *)thunk_list->u1.Function );
523 import_list++;
524 thunk_list++;
526 goto done;
529 while (import_list->u1.Ordinal)
531 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
533 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
535 thunk_list->u1.Function = (ULONG_PTR)find_ordinal_export( imp_mod, exports, exp_size,
536 ordinal - exports->Base );
537 if (!thunk_list->u1.Function)
539 thunk_list->u1.Function = allocate_stub( name, (const char *)ordinal );
540 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
541 name, ordinal, debugstr_w(current_modref->ldr.FullDllName.Buffer),
542 (void *)thunk_list->u1.Function );
544 TRACE_(imports)("--- Ordinal %s.%d = %p\n", name, ordinal, (void *)thunk_list->u1.Function );
546 else /* import by name */
548 IMAGE_IMPORT_BY_NAME *pe_name;
549 pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
550 thunk_list->u1.Function = (ULONG_PTR)find_named_export( imp_mod, exports, exp_size,
551 (const char*)pe_name->Name, pe_name->Hint );
552 if (!thunk_list->u1.Function)
554 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
555 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
556 name, pe_name->Name, debugstr_w(current_modref->ldr.FullDllName.Buffer),
557 (void *)thunk_list->u1.Function );
559 TRACE_(imports)("--- %s %s.%d = %p\n",
560 pe_name->Name, name, pe_name->Hint, (void *)thunk_list->u1.Function);
562 import_list++;
563 thunk_list++;
566 done:
567 /* restore old protection of the import address table */
568 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base, &protect_size, protect_old, NULL );
569 return wmImp;
573 /****************************************************************
574 * fixup_imports
576 * Fixup all imports of a given module.
577 * The loader_section must be locked while calling this function.
579 static NTSTATUS fixup_imports( WINE_MODREF *wm, LPCWSTR load_path )
581 int i, nb_imports;
582 const IMAGE_IMPORT_DESCRIPTOR *imports;
583 WINE_MODREF *prev;
584 DWORD size;
585 NTSTATUS status;
587 if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
588 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
589 return STATUS_SUCCESS;
591 nb_imports = size / sizeof(*imports);
592 for (i = 0; i < nb_imports; i++)
594 if (!imports[i].Name)
596 nb_imports = i;
597 break;
600 if (!nb_imports) return STATUS_SUCCESS; /* no imports */
602 /* Allocate module dependency list */
603 wm->nDeps = nb_imports;
604 wm->deps = RtlAllocateHeap( GetProcessHeap(), 0, nb_imports*sizeof(WINE_MODREF *) );
606 /* load the imported modules. They are automatically
607 * added to the modref list of the process.
609 prev = current_modref;
610 current_modref = wm;
611 status = STATUS_SUCCESS;
612 for (i = 0; i < nb_imports; i++)
614 if (!(wm->deps[i] = import_dll( wm->ldr.BaseAddress, &imports[i], load_path )))
615 status = STATUS_DLL_NOT_FOUND;
617 current_modref = prev;
618 return status;
622 /*************************************************************************
623 * alloc_module
625 * Allocate a WINE_MODREF structure and add it to the process list
626 * The loader_section must be locked while calling this function.
628 static WINE_MODREF *alloc_module( HMODULE hModule, LPCWSTR filename )
630 WINE_MODREF *wm;
631 const WCHAR *p;
632 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
633 PLIST_ENTRY entry, mark;
635 if (!(wm = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm) ))) return NULL;
637 wm->nDeps = 0;
638 wm->deps = NULL;
640 wm->ldr.BaseAddress = hModule;
641 wm->ldr.EntryPoint = NULL;
642 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
643 wm->ldr.Flags = 0;
644 wm->ldr.LoadCount = 0;
645 wm->ldr.TlsIndex = -1;
646 wm->ldr.SectionHandle = NULL;
647 wm->ldr.CheckSum = 0;
648 wm->ldr.TimeDateStamp = 0;
650 RtlCreateUnicodeString( &wm->ldr.FullDllName, filename );
651 if ((p = strrchrW( wm->ldr.FullDllName.Buffer, '\\' ))) p++;
652 else p = wm->ldr.FullDllName.Buffer;
653 RtlInitUnicodeString( &wm->ldr.BaseDllName, p );
655 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
657 wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
658 if (nt->OptionalHeader.AddressOfEntryPoint)
659 wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
662 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
663 &wm->ldr.InLoadOrderModuleList);
665 /* insert module in MemoryList, sorted in increasing base addresses */
666 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
667 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
669 if (CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList)->BaseAddress > wm->ldr.BaseAddress)
670 break;
672 entry->Blink->Flink = &wm->ldr.InMemoryOrderModuleList;
673 wm->ldr.InMemoryOrderModuleList.Blink = entry->Blink;
674 wm->ldr.InMemoryOrderModuleList.Flink = entry;
675 entry->Blink = &wm->ldr.InMemoryOrderModuleList;
677 /* wait until init is called for inserting into this list */
678 wm->ldr.InInitializationOrderModuleList.Flink = NULL;
679 wm->ldr.InInitializationOrderModuleList.Blink = NULL;
680 return wm;
684 /*************************************************************************
685 * alloc_process_tls
687 * Allocate the process-wide structure for module TLS storage.
689 static NTSTATUS alloc_process_tls(void)
691 PLIST_ENTRY mark, entry;
692 PLDR_MODULE mod;
693 const IMAGE_TLS_DIRECTORY *dir;
694 ULONG size, i;
696 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
697 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
699 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
700 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
701 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
702 continue;
703 size = (dir->EndAddressOfRawData - dir->StartAddressOfRawData) + dir->SizeOfZeroFill;
704 if (!size) continue;
705 tls_total_size += size;
706 tls_module_count++;
708 if (!tls_module_count) return STATUS_SUCCESS;
710 TRACE( "count %u size %u\n", tls_module_count, tls_total_size );
712 tls_dirs = RtlAllocateHeap( GetProcessHeap(), 0, tls_module_count * sizeof(*tls_dirs) );
713 if (!tls_dirs) return STATUS_NO_MEMORY;
715 for (i = 0, entry = mark->Flink; entry != mark; entry = entry->Flink)
717 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
718 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
719 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
720 continue;
721 tls_dirs[i] = dir;
722 *(DWORD *)dir->AddressOfIndex = i;
723 mod->TlsIndex = i;
724 mod->LoadCount = -1; /* can't unload it */
725 i++;
727 return STATUS_SUCCESS;
731 /*************************************************************************
732 * alloc_thread_tls
734 * Allocate the per-thread structure for module TLS storage.
736 static NTSTATUS alloc_thread_tls(void)
738 void **pointers;
739 char *data;
740 UINT i;
742 if (!tls_module_count) return STATUS_SUCCESS;
744 if (!(pointers = RtlAllocateHeap( GetProcessHeap(), 0,
745 tls_module_count * sizeof(*pointers) )))
746 return STATUS_NO_MEMORY;
748 if (!(data = RtlAllocateHeap( GetProcessHeap(), 0, tls_total_size )))
750 RtlFreeHeap( GetProcessHeap(), 0, pointers );
751 return STATUS_NO_MEMORY;
754 for (i = 0; i < tls_module_count; i++)
756 const IMAGE_TLS_DIRECTORY *dir = tls_dirs[i];
757 ULONG size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
759 TRACE( "thread %04lx idx %d: %ld/%ld bytes from %p to %p\n",
760 GetCurrentThreadId(), i, size, dir->SizeOfZeroFill,
761 (void *)dir->StartAddressOfRawData, data );
763 pointers[i] = data;
764 memcpy( data, (void *)dir->StartAddressOfRawData, size );
765 data += size;
766 memset( data, 0, dir->SizeOfZeroFill );
767 data += dir->SizeOfZeroFill;
769 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
770 return STATUS_SUCCESS;
774 /*************************************************************************
775 * call_tls_callbacks
777 static void call_tls_callbacks( HMODULE module, UINT reason )
779 const IMAGE_TLS_DIRECTORY *dir;
780 const PIMAGE_TLS_CALLBACK *callback;
781 ULONG dirsize;
783 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
784 if (!dir || !dir->AddressOfCallBacks) return;
786 for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
788 if (TRACE_ON(relay))
789 DPRINTF("%04lx:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
790 GetCurrentThreadId(), *callback, module, reason_names[reason] );
791 (*callback)( module, reason, NULL );
792 if (TRACE_ON(relay))
793 DPRINTF("%04lx:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
794 GetCurrentThreadId(), *callback, module, reason_names[reason] );
799 /*************************************************************************
800 * MODULE_InitDLL
802 static BOOL MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
804 WCHAR mod_name[32];
805 BOOL retv = TRUE;
806 DLLENTRYPROC entry = wm->ldr.EntryPoint;
807 void *module = wm->ldr.BaseAddress;
809 /* Skip calls for modules loaded with special load flags */
811 if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return TRUE;
812 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.BaseAddress, reason );
813 if (!entry) return TRUE;
815 if (TRACE_ON(relay))
817 size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
818 memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
819 mod_name[len / sizeof(WCHAR)] = 0;
820 DPRINTF("%04lx:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
821 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
822 reason_names[reason], lpReserved );
824 else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
825 reason_names[reason], lpReserved );
827 retv = call_dll_entry_point( entry, module, reason, lpReserved );
829 /* The state of the module list may have changed due to the call
830 to the dll. We cannot assume that this module has not been
831 deleted. */
832 if (TRACE_ON(relay))
833 DPRINTF("%04lx:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
834 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
835 reason_names[reason], lpReserved, retv );
836 else TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
838 return retv;
842 /*************************************************************************
843 * process_attach
845 * Send the process attach notification to all DLLs the given module
846 * depends on (recursively). This is somewhat complicated due to the fact that
848 * - we have to respect the module dependencies, i.e. modules implicitly
849 * referenced by another module have to be initialized before the module
850 * itself can be initialized
852 * - the initialization routine of a DLL can itself call LoadLibrary,
853 * thereby introducing a whole new set of dependencies (even involving
854 * the 'old' modules) at any time during the whole process
856 * (Note that this routine can be recursively entered not only directly
857 * from itself, but also via LoadLibrary from one of the called initialization
858 * routines.)
860 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
861 * the process *detach* notifications to be sent in the correct order.
862 * This must not only take into account module dependencies, but also
863 * 'hidden' dependencies created by modules calling LoadLibrary in their
864 * attach notification routine.
866 * The strategy is rather simple: we move a WINE_MODREF to the head of the
867 * list after the attach notification has returned. This implies that the
868 * detach notifications are called in the reverse of the sequence the attach
869 * notifications *returned*.
871 * The loader_section must be locked while calling this function.
873 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
875 NTSTATUS status = STATUS_SUCCESS;
876 int i;
878 if (process_detaching) return status;
880 /* prevent infinite recursion in case of cyclical dependencies */
881 if ( ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
882 || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
883 return status;
885 TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
887 /* Tag current MODREF to prevent recursive loop */
888 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
890 /* Recursively attach all DLLs this one depends on */
891 for ( i = 0; i < wm->nDeps; i++ )
893 if (!wm->deps[i]) continue;
894 if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
897 /* Call DLL entry point */
898 if (status == STATUS_SUCCESS)
900 WINE_MODREF *prev = current_modref;
901 current_modref = wm;
902 if (MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved ))
904 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
906 else
908 /* point to the name so LdrInitializeThunk can print it */
909 last_failed_modref = wm;
910 WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
911 status = STATUS_DLL_INIT_FAILED;
913 current_modref = prev;
916 if (!wm->ldr.InInitializationOrderModuleList.Flink)
917 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
918 &wm->ldr.InInitializationOrderModuleList);
920 /* Remove recursion flag */
921 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
923 TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
924 return status;
927 /*************************************************************************
928 * process_detach
930 * Send DLL process detach notifications. See the comment about calling
931 * sequence at process_attach. Unless the bForceDetach flag
932 * is set, only DLLs with zero refcount are notified.
934 static void process_detach( BOOL bForceDetach, LPVOID lpReserved )
936 PLIST_ENTRY mark, entry;
937 PLDR_MODULE mod;
939 RtlEnterCriticalSection( &loader_section );
940 if (bForceDetach) process_detaching = 1;
941 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
944 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
946 mod = CONTAINING_RECORD(entry, LDR_MODULE,
947 InInitializationOrderModuleList);
948 /* Check whether to detach this DLL */
949 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
950 continue;
951 if ( mod->LoadCount && !bForceDetach )
952 continue;
954 /* Call detach notification */
955 mod->Flags &= ~LDR_PROCESS_ATTACHED;
956 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
957 DLL_PROCESS_DETACH, lpReserved );
959 /* Restart at head of WINE_MODREF list, as entries might have
960 been added and/or removed while performing the call ... */
961 break;
963 } while (entry != mark);
965 RtlLeaveCriticalSection( &loader_section );
968 /*************************************************************************
969 * MODULE_DllThreadAttach
971 * Send DLL thread attach notifications. These are sent in the
972 * reverse sequence of process detach notification.
975 NTSTATUS MODULE_DllThreadAttach( LPVOID lpReserved )
977 PLIST_ENTRY mark, entry;
978 PLDR_MODULE mod;
979 NTSTATUS status;
981 /* don't do any attach calls if process is exiting */
982 if (process_detaching) return STATUS_SUCCESS;
983 /* FIXME: there is still a race here */
985 RtlEnterCriticalSection( &loader_section );
987 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto done;
989 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
990 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
992 mod = CONTAINING_RECORD(entry, LDR_MODULE,
993 InInitializationOrderModuleList);
994 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
995 continue;
996 if ( mod->Flags & LDR_NO_DLL_CALLS )
997 continue;
999 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1000 DLL_THREAD_ATTACH, lpReserved );
1003 done:
1004 RtlLeaveCriticalSection( &loader_section );
1005 return status;
1008 /******************************************************************
1009 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1012 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1014 WINE_MODREF *wm;
1015 NTSTATUS ret = STATUS_SUCCESS;
1017 RtlEnterCriticalSection( &loader_section );
1019 wm = get_modref( hModule );
1020 if (!wm || wm->ldr.TlsIndex != -1)
1021 ret = STATUS_DLL_NOT_FOUND;
1022 else
1023 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1025 RtlLeaveCriticalSection( &loader_section );
1027 return ret;
1030 /******************************************************************
1031 * LdrFindEntryForAddress (NTDLL.@)
1033 * The loader_section must be locked while calling this function
1035 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
1037 PLIST_ENTRY mark, entry;
1038 PLDR_MODULE mod;
1040 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1041 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1043 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
1044 if ((const void *)mod->BaseAddress <= addr &&
1045 (const char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
1047 *pmod = mod;
1048 return STATUS_SUCCESS;
1050 if ((const void *)mod->BaseAddress > addr) break;
1052 return STATUS_NO_MORE_ENTRIES;
1055 /******************************************************************
1056 * LdrLockLoaderLock (NTDLL.@)
1058 * Note: flags are not implemented.
1059 * Flag 0x01 is used to raise exceptions on errors.
1060 * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
1062 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG *magic )
1064 if (flags) FIXME( "flags %lx not supported\n", flags );
1066 if (result) *result = 1;
1067 if (!magic) return STATUS_INVALID_PARAMETER_3;
1068 RtlEnterCriticalSection( &loader_section );
1069 *magic = GetCurrentThreadId();
1070 return STATUS_SUCCESS;
1074 /******************************************************************
1075 * LdrUnlockLoaderUnlock (NTDLL.@)
1077 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG magic )
1079 if (magic)
1081 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1082 RtlLeaveCriticalSection( &loader_section );
1084 return STATUS_SUCCESS;
1088 /******************************************************************
1089 * LdrGetDllHandle (NTDLL.@)
1091 NTSTATUS WINAPI LdrGetDllHandle(ULONG x, ULONG y, const UNICODE_STRING *name, HMODULE *base)
1093 NTSTATUS status = STATUS_DLL_NOT_FOUND;
1094 WCHAR dllname[MAX_PATH+4], *p;
1095 UNICODE_STRING str;
1096 PLIST_ENTRY mark, entry;
1097 PLDR_MODULE mod;
1099 if (x != 0 || y != 0)
1100 FIXME("Unknown behavior, please report\n");
1102 /* Append .DLL to name if no extension present */
1103 if (!(p = strrchrW( name->Buffer, '.')) || strchrW( p, '/' ) || strchrW( p, '\\'))
1105 if (name->Length >= MAX_PATH) return STATUS_NAME_TOO_LONG;
1106 strcpyW( dllname, name->Buffer );
1107 strcatW( dllname, dllW );
1108 RtlInitUnicodeString( &str, dllname );
1109 name = &str;
1112 RtlEnterCriticalSection( &loader_section );
1114 if (cached_modref)
1116 if (RtlEqualUnicodeString( name, &cached_modref->ldr.FullDllName, TRUE ) ||
1117 RtlEqualUnicodeString( name, &cached_modref->ldr.BaseDllName, TRUE ))
1119 *base = cached_modref->ldr.BaseAddress;
1120 status = STATUS_SUCCESS;
1121 goto done;
1125 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1126 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1128 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1130 if (RtlEqualUnicodeString( name, &mod->FullDllName, TRUE ) ||
1131 RtlEqualUnicodeString( name, &mod->BaseDllName, TRUE ))
1133 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1134 *base = mod->BaseAddress;
1135 status = STATUS_SUCCESS;
1136 break;
1139 done:
1140 RtlLeaveCriticalSection( &loader_section );
1141 TRACE("%lx %lx %s -> %p\n", x, y, debugstr_us(name), status ? NULL : *base);
1142 return status;
1146 /******************************************************************
1147 * LdrGetProcedureAddress (NTDLL.@)
1149 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1150 ULONG ord, PVOID *address)
1152 IMAGE_EXPORT_DIRECTORY *exports;
1153 DWORD exp_size;
1154 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1156 RtlEnterCriticalSection( &loader_section );
1158 if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1159 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1161 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1 )
1162 : find_ordinal_export( module, exports, exp_size, ord - exports->Base );
1163 if (proc)
1165 *address = proc;
1166 ret = STATUS_SUCCESS;
1169 else
1171 /* check if the module itself is invalid to return the proper error */
1172 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1175 RtlLeaveCriticalSection( &loader_section );
1176 return ret;
1180 /***********************************************************************
1181 * load_builtin_callback
1183 * Load a library in memory; callback function for wine_dll_register
1185 static void load_builtin_callback( void *module, const char *filename )
1187 static const WCHAR emptyW[1];
1188 void *addr;
1189 IMAGE_NT_HEADERS *nt;
1190 WINE_MODREF *wm;
1191 WCHAR *fullname, *p;
1192 const WCHAR *load_path;
1194 if (!module)
1196 ERR("could not map image for %s\n", filename ? filename : "main exe" );
1197 return;
1199 if (!(nt = RtlImageNtHeader( module )))
1201 ERR( "bad module for %s\n", filename ? filename : "main exe" );
1202 builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1203 return;
1205 addr = module;
1206 NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 0, &nt->OptionalHeader.SizeOfImage,
1207 MEM_SYSTEM | MEM_IMAGE, PAGE_EXECUTE_WRITECOPY );
1208 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL))
1210 /* if we already have an executable, ignore this one */
1211 if (!NtCurrentTeb()->Peb->ImageBaseAddress)
1213 NtCurrentTeb()->Peb->ImageBaseAddress = module;
1214 return; /* don't create the modref here, will be done later on */
1218 /* create the MODREF */
1220 if (!(fullname = RtlAllocateHeap( GetProcessHeap(), 0,
1221 system_dir.MaximumLength + (strlen(filename) + 1) * sizeof(WCHAR) )))
1223 ERR( "can't load %s\n", filename );
1224 builtin_load_info->status = STATUS_NO_MEMORY;
1225 return;
1227 memcpy( fullname, system_dir.Buffer, system_dir.Length );
1228 p = fullname + system_dir.Length / sizeof(WCHAR);
1229 if (p > fullname && p[-1] != '\\') *p++ = '\\';
1230 ascii_to_unicode( p, filename, strlen(filename) + 1 );
1232 wm = alloc_module( module, fullname );
1233 RtlFreeHeap( GetProcessHeap(), 0, fullname );
1234 if (!wm)
1236 ERR( "can't load %s\n", filename );
1237 builtin_load_info->status = STATUS_NO_MEMORY;
1238 return;
1240 wm->ldr.Flags |= LDR_WINE_INTERNAL;
1242 /* fixup imports */
1244 load_path = builtin_load_info->load_path;
1245 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1246 if (!load_path) load_path = emptyW;
1247 if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1249 /* the module has only be inserted in the load & memory order lists */
1250 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1251 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1252 /* FIXME: free the modref */
1253 builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1254 return;
1256 builtin_load_info->wm = wm;
1257 TRACE( "loaded %s %p %p\n", filename, wm, module );
1259 /* send the DLL load event */
1261 SERVER_START_REQ( load_dll )
1263 req->handle = 0;
1264 req->base = module;
1265 req->size = nt->OptionalHeader.SizeOfImage;
1266 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1267 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1268 req->name = &wm->ldr.FullDllName.Buffer;
1269 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1270 wine_server_call( req );
1272 SERVER_END_REQ;
1274 /* setup relay debugging entry points */
1275 if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1279 /******************************************************************************
1280 * load_native_dll (internal)
1282 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1283 DWORD flags, WINE_MODREF** pwm )
1285 void *module;
1286 HANDLE mapping;
1287 OBJECT_ATTRIBUTES attr;
1288 LARGE_INTEGER size;
1289 IMAGE_NT_HEADERS *nt;
1290 DWORD len = 0;
1291 WINE_MODREF *wm;
1292 NTSTATUS status;
1294 TRACE( "loading %s\n", debugstr_w(name) );
1296 attr.Length = sizeof(attr);
1297 attr.RootDirectory = 0;
1298 attr.ObjectName = NULL;
1299 attr.Attributes = 0;
1300 attr.SecurityDescriptor = NULL;
1301 attr.SecurityQualityOfService = NULL;
1302 size.QuadPart = 0;
1304 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1305 &attr, &size, 0, SEC_IMAGE, file );
1306 if (status != STATUS_SUCCESS) return status;
1308 module = NULL;
1309 status = NtMapViewOfSection( mapping, NtCurrentProcess(),
1310 &module, 0, 0, &size, &len, ViewShare, 0, PAGE_READONLY );
1311 NtClose( mapping );
1312 if (status != STATUS_SUCCESS) return status;
1314 /* create the MODREF */
1316 if (!(wm = alloc_module( module, name ))) return STATUS_NO_MEMORY;
1318 /* fixup imports */
1320 if (!(flags & DONT_RESOLVE_DLL_REFERENCES))
1322 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1324 /* the module has only be inserted in the load & memory order lists */
1325 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1326 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1328 /* FIXME: there are several more dangling references
1329 * left. Including dlls loaded by this dll before the
1330 * failed one. Unrolling is rather difficult with the
1331 * current structure and we can leave them lying
1332 * around with no problems, so we don't care.
1333 * As these might reference our wm, we don't free it.
1335 return status;
1338 else wm->ldr.Flags |= LDR_DONT_RESOLVE_REFS;
1340 /* send DLL load event */
1342 nt = RtlImageNtHeader( module );
1344 /* don't keep the file open if the mapping is from removable media */
1345 if (!VIRTUAL_HasMapping( module )) file = 0;
1347 SERVER_START_REQ( load_dll )
1349 req->handle = file;
1350 req->base = module;
1351 req->size = nt->OptionalHeader.SizeOfImage;
1352 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1353 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1354 req->name = &wm->ldr.FullDllName.Buffer;
1355 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1356 wine_server_call( req );
1358 SERVER_END_REQ;
1360 if (TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1362 TRACE_(loaddll)( " Loaded module %s : native\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
1364 *pwm = wm;
1365 return STATUS_SUCCESS;
1369 /***********************************************************************
1370 * load_builtin_dll
1372 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, DWORD flags, WINE_MODREF** pwm )
1374 char error[256], dllname[MAX_PATH];
1375 int file_exists;
1376 const WCHAR *name, *p;
1377 DWORD len, i;
1378 void *handle;
1379 struct builtin_load_info info, *prev_info;
1381 /* Fix the name in case we have a full path and extension */
1382 name = path;
1383 if ((p = strrchrW( name, '\\' ))) name = p + 1;
1384 if ((p = strrchrW( name, '/' ))) name = p + 1;
1386 /* we don't want to depend on the current codepage here */
1387 len = strlenW( name ) + 1;
1388 if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1389 for (i = 0; i < len; i++)
1391 if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1392 dllname[i] = (char)name[i];
1393 if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1396 /* load_library will modify info.status. Note also that load_library can be
1397 * called several times, if the .so file we're loading has dependencies.
1398 * info.status will gather all the errors we may get while loading all these
1399 * libraries
1401 info.load_path = load_path;
1402 info.status = STATUS_SUCCESS;
1403 info.wm = NULL;
1404 prev_info = builtin_load_info;
1405 builtin_load_info = &info;
1406 handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1407 builtin_load_info = prev_info;
1409 if (!handle)
1411 if (!file_exists)
1413 /* The file does not exist -> WARN() */
1414 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
1415 return STATUS_DLL_NOT_FOUND;
1417 /* ERR() for all other errors (missing functions, ...) */
1418 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
1419 return STATUS_PROCEDURE_NOT_FOUND;
1421 if (info.status != STATUS_SUCCESS) return info.status;
1423 if (!info.wm)
1425 /* The constructor wasn't called, this means the .so is already
1426 * loaded under a different name. We can't support multiple names
1427 * for the same module, so return an error. */
1428 return STATUS_INVALID_IMAGE_FORMAT;
1431 TRACE_(loaddll)( "Loaded module %s : builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer) );
1433 info.wm->ldr.SectionHandle = handle;
1434 if (strcmpiW( info.wm->ldr.BaseDllName.Buffer, name ))
1436 ERR( "loaded .so for %s but got %s instead - probably 16-bit dll\n",
1437 debugstr_w(name), debugstr_w(info.wm->ldr.BaseDllName.Buffer) );
1438 /* wine_dll_unload( handle );*/
1439 return STATUS_INVALID_IMAGE_FORMAT;
1441 *pwm = info.wm;
1442 return STATUS_SUCCESS;
1446 /***********************************************************************
1447 * find_dll_file
1449 * Find the file (or already loaded module) for a given dll name.
1451 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
1452 WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
1454 OBJECT_ATTRIBUTES attr;
1455 IO_STATUS_BLOCK io;
1456 UNICODE_STRING nt_name;
1457 WCHAR *file_part, *ext, *dllname;
1458 ULONG len;
1460 /* first append .dll if needed */
1462 dllname = NULL;
1463 if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
1465 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
1466 (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
1467 return STATUS_NO_MEMORY;
1468 strcpyW( dllname, libname );
1469 strcatW( dllname, dllW );
1470 libname = dllname;
1473 nt_name.Buffer = NULL;
1474 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
1476 /* we need to search for it */
1477 len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
1478 if (len)
1480 if (len >= *size) goto overflow;
1481 if ((*pwm = find_fullname_module( filename )) != NULL) goto found;
1483 /* check for already loaded module in a different path */
1484 if (!contains_path( libname ))
1486 if ((*pwm = find_basename_module( file_part )) != NULL) goto found;
1488 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
1490 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1491 return STATUS_NO_MEMORY;
1493 attr.Length = sizeof(attr);
1494 attr.RootDirectory = 0;
1495 attr.Attributes = OBJ_CASE_INSENSITIVE;
1496 attr.ObjectName = &nt_name;
1497 attr.SecurityDescriptor = NULL;
1498 attr.SecurityQualityOfService = NULL;
1499 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1500 goto found;
1503 /* not found */
1505 if (!contains_path( libname ))
1507 /* if libname doesn't contain a path at all, we simply return the name as is,
1508 * to be loaded as builtin */
1509 len = strlenW(libname) * sizeof(WCHAR);
1510 if (len >= *size) goto overflow;
1511 strcpyW( filename, libname );
1512 *pwm = find_basename_module( filename );
1513 goto found;
1517 /* absolute path name, or relative path name but not found above */
1519 if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
1521 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1522 return STATUS_NO_MEMORY;
1524 len = nt_name.Length - 4*sizeof(WCHAR); /* for \??\ prefix */
1525 if (len >= *size) goto overflow;
1526 memcpy( filename, nt_name.Buffer + 4, len + sizeof(WCHAR) );
1527 if (!(*pwm = find_fullname_module( filename )))
1529 attr.Length = sizeof(attr);
1530 attr.RootDirectory = 0;
1531 attr.Attributes = OBJ_CASE_INSENSITIVE;
1532 attr.ObjectName = &nt_name;
1533 attr.SecurityDescriptor = NULL;
1534 attr.SecurityQualityOfService = NULL;
1535 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1537 found:
1538 RtlFreeUnicodeString( &nt_name );
1539 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1540 return STATUS_SUCCESS;
1542 overflow:
1543 RtlFreeUnicodeString( &nt_name );
1544 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1545 *size = len + sizeof(WCHAR);
1546 return STATUS_BUFFER_TOO_SMALL;
1550 /***********************************************************************
1551 * load_dll (internal)
1553 * Load a PE style module according to the load order.
1554 * The loader_section must be locked while calling this function.
1556 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
1558 int i;
1559 enum loadorder_type loadorder[LOADORDER_NTYPES];
1560 WCHAR buffer[32];
1561 WCHAR *filename;
1562 ULONG size;
1563 const char *filetype = "";
1564 WINE_MODREF *main_exe;
1565 HANDLE handle = 0;
1566 NTSTATUS nts;
1568 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
1570 filename = buffer;
1571 size = sizeof(buffer);
1572 for (;;)
1574 nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
1575 if (nts == STATUS_SUCCESS) break;
1576 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1577 if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
1578 /* grow the buffer and retry */
1579 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
1582 if (*pwm) /* found already loaded module */
1584 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
1586 if (((*pwm)->ldr.Flags & LDR_DONT_RESOLVE_REFS) &&
1587 !(flags & DONT_RESOLVE_DLL_REFERENCES))
1589 (*pwm)->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
1590 fixup_imports( *pwm, load_path );
1592 TRACE("Found loaded module %s for %s at %p, count=%d\n",
1593 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
1594 (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
1595 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1596 return STATUS_SUCCESS;
1599 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
1600 MODULE_GetLoadOrderW( loadorder, main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
1602 nts = STATUS_DLL_NOT_FOUND;
1603 for (i = 0; i < LOADORDER_NTYPES; i++)
1605 if (loadorder[i] == LOADORDER_INVALID) break;
1607 switch (loadorder[i])
1609 case LOADORDER_DLL:
1610 TRACE("Trying native dll %s\n", debugstr_w(filename));
1611 if (!handle) continue; /* it cannot possibly be loaded */
1612 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1613 filetype = "native";
1614 break;
1615 case LOADORDER_BI:
1616 TRACE("Trying built-in %s\n", debugstr_w(filename));
1617 nts = load_builtin_dll( load_path, filename, flags, pwm );
1618 filetype = "builtin";
1619 break;
1620 default:
1621 nts = STATUS_INTERNAL_ERROR;
1622 break;
1625 if (nts == STATUS_SUCCESS)
1627 /* Initialize DLL just loaded */
1628 TRACE("Loaded module %s (%s) at %p\n",
1629 debugstr_w(filename), filetype, (*pwm)->ldr.BaseAddress);
1630 /* Set the ldr.LoadCount here so that an attach failure will */
1631 /* decrement the dependencies through the MODULE_FreeLibrary call. */
1632 (*pwm)->ldr.LoadCount = 1;
1633 if (handle) NtClose( handle );
1634 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1635 return nts;
1637 if (nts != STATUS_DLL_NOT_FOUND) break;
1640 WARN("Failed to load module %s; status=%lx\n", debugstr_w(libname), nts);
1641 if (handle) NtClose( handle );
1642 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1643 return nts;
1646 /******************************************************************
1647 * LdrLoadDll (NTDLL.@)
1649 NTSTATUS WINAPI LdrLoadDll(LPCWSTR path_name, DWORD flags,
1650 const UNICODE_STRING *libname, HMODULE* hModule)
1652 WINE_MODREF *wm;
1653 NTSTATUS nts;
1655 RtlEnterCriticalSection( &loader_section );
1657 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1658 nts = load_dll( path_name, libname->Buffer, flags, &wm );
1660 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
1662 nts = process_attach( wm, NULL );
1663 if (nts != STATUS_SUCCESS)
1665 LdrUnloadDll(wm->ldr.BaseAddress);
1666 wm = NULL;
1669 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
1671 RtlLeaveCriticalSection( &loader_section );
1672 return nts;
1675 /******************************************************************
1676 * LdrQueryProcessModuleInformation
1679 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
1680 ULONG buf_size, ULONG* req_size)
1682 SYSTEM_MODULE* sm = &smi->Modules[0];
1683 ULONG size = sizeof(ULONG);
1684 NTSTATUS nts = STATUS_SUCCESS;
1685 ANSI_STRING str;
1686 char* ptr;
1687 PLIST_ENTRY mark, entry;
1688 PLDR_MODULE mod;
1690 smi->ModulesCount = 0;
1692 RtlEnterCriticalSection( &loader_section );
1693 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1694 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1696 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1697 size += sizeof(*sm);
1698 if (size <= buf_size)
1700 sm->Reserved1 = 0; /* FIXME */
1701 sm->Reserved2 = 0; /* FIXME */
1702 sm->ImageBaseAddress = mod->BaseAddress;
1703 sm->ImageSize = mod->SizeOfImage;
1704 sm->Flags = mod->Flags;
1705 sm->Id = 0; /* FIXME */
1706 sm->Rank = 0; /* FIXME */
1707 sm->Unknown = 0; /* FIXME */
1708 str.Length = 0;
1709 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
1710 str.Buffer = (char*)sm->Name;
1711 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
1712 ptr = strrchr(str.Buffer, '\\');
1713 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
1715 smi->ModulesCount++;
1716 sm++;
1718 else nts = STATUS_INFO_LENGTH_MISMATCH;
1720 RtlLeaveCriticalSection( &loader_section );
1722 if (req_size) *req_size = size;
1724 return nts;
1727 /******************************************************************
1728 * LdrShutdownProcess (NTDLL.@)
1731 void WINAPI LdrShutdownProcess(void)
1733 TRACE("()\n");
1734 process_detach( TRUE, (LPVOID)1 );
1737 /******************************************************************
1738 * LdrShutdownThread (NTDLL.@)
1741 void WINAPI LdrShutdownThread(void)
1743 PLIST_ENTRY mark, entry;
1744 PLDR_MODULE mod;
1746 TRACE("()\n");
1748 /* don't do any detach calls if process is exiting */
1749 if (process_detaching) return;
1750 /* FIXME: there is still a race here */
1752 RtlEnterCriticalSection( &loader_section );
1754 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1755 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1757 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1758 InInitializationOrderModuleList);
1759 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1760 continue;
1761 if ( mod->Flags & LDR_NO_DLL_CALLS )
1762 continue;
1764 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1765 DLL_THREAD_DETACH, NULL );
1768 RtlLeaveCriticalSection( &loader_section );
1771 /***********************************************************************
1772 * MODULE_FlushModrefs
1774 * Remove all unused modrefs and call the internal unloading routines
1775 * for the library type.
1777 * The loader_section must be locked while calling this function.
1779 static void MODULE_FlushModrefs(void)
1781 PLIST_ENTRY mark, entry, prev;
1782 PLDR_MODULE mod;
1783 WINE_MODREF*wm;
1785 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1786 for (entry = mark->Blink; entry != mark; entry = prev)
1788 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1789 InInitializationOrderModuleList);
1790 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1792 prev = entry->Blink;
1793 if (mod->LoadCount) continue;
1795 RemoveEntryList(&mod->InLoadOrderModuleList);
1796 RemoveEntryList(&mod->InMemoryOrderModuleList);
1797 RemoveEntryList(&mod->InInitializationOrderModuleList);
1799 TRACE(" unloading %s\n", debugstr_w(mod->FullDllName.Buffer));
1800 if (!TRACE_ON(module))
1801 TRACE_(loaddll)("Unloaded module %s : %s\n",
1802 debugstr_w(mod->FullDllName.Buffer),
1803 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
1805 SERVER_START_REQ( unload_dll )
1807 req->base = mod->BaseAddress;
1808 wine_server_call( req );
1810 SERVER_END_REQ;
1812 NtUnmapViewOfSection( NtCurrentProcess(), mod->BaseAddress );
1813 if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
1814 if (cached_modref == wm) cached_modref = NULL;
1815 RtlFreeUnicodeString( &mod->FullDllName );
1816 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
1817 RtlFreeHeap( GetProcessHeap(), 0, wm );
1821 /***********************************************************************
1822 * MODULE_DecRefCount
1824 * The loader_section must be locked while calling this function.
1826 static void MODULE_DecRefCount( WINE_MODREF *wm )
1828 int i;
1830 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
1831 return;
1833 if ( wm->ldr.LoadCount <= 0 )
1834 return;
1836 --wm->ldr.LoadCount;
1837 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
1839 if ( wm->ldr.LoadCount == 0 )
1841 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
1843 for ( i = 0; i < wm->nDeps; i++ )
1844 if ( wm->deps[i] )
1845 MODULE_DecRefCount( wm->deps[i] );
1847 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
1851 /******************************************************************
1852 * LdrUnloadDll (NTDLL.@)
1856 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
1858 NTSTATUS retv = STATUS_SUCCESS;
1860 TRACE("(%p)\n", hModule);
1862 RtlEnterCriticalSection( &loader_section );
1864 /* if we're stopping the whole process (and forcing the removal of all
1865 * DLLs) the library will be freed anyway
1867 if (!process_detaching)
1869 WINE_MODREF *wm;
1871 free_lib_count++;
1872 if ((wm = get_modref( hModule )) != NULL)
1874 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
1876 /* Recursively decrement reference counts */
1877 MODULE_DecRefCount( wm );
1879 /* Call process detach notifications */
1880 if ( free_lib_count <= 1 )
1882 process_detach( FALSE, NULL );
1883 MODULE_FlushModrefs();
1886 TRACE("END\n");
1888 else
1889 retv = STATUS_DLL_NOT_FOUND;
1891 free_lib_count--;
1894 RtlLeaveCriticalSection( &loader_section );
1896 return retv;
1899 /***********************************************************************
1900 * RtlImageNtHeader (NTDLL.@)
1902 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
1904 IMAGE_NT_HEADERS *ret;
1906 __TRY
1908 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
1910 ret = NULL;
1911 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
1913 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
1914 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
1917 __EXCEPT(page_fault)
1919 return NULL;
1921 __ENDTRY
1922 return ret;
1926 /******************************************************************
1927 * LdrInitializeThunk (NTDLL.@)
1929 * FIXME: the arguments are not correct, main_file is a Wine invention.
1931 void WINAPI LdrInitializeThunk( HANDLE main_file, ULONG unknown2, ULONG unknown3, ULONG unknown4 )
1933 NTSTATUS status;
1934 WINE_MODREF *wm;
1935 LPCWSTR load_path;
1936 PEB *peb = NtCurrentTeb()->Peb;
1937 UNICODE_STRING *main_exe_name = &peb->ProcessParameters->ImagePathName;
1938 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
1940 version_init( main_exe_name->Buffer );
1942 /* allocate the modref for the main exe */
1943 if (!(wm = alloc_module( peb->ImageBaseAddress, main_exe_name->Buffer )))
1945 status = STATUS_NO_MEMORY;
1946 goto error;
1948 wm->ldr.LoadCount = -1; /* can't unload main exe */
1950 /* the main exe needs to be the first in the load order list */
1951 RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
1952 InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
1954 /* Install signal handlers; this cannot be done before, since we cannot
1955 * send exceptions to the debugger before the create process event that
1956 * is sent by REQ_INIT_PROCESS_DONE.
1957 * We do need the handlers in place by the time the request is over, so
1958 * we set them up here. If we segfault between here and the server call
1959 * something is very wrong... */
1960 if (!SIGNAL_Init()) exit(1);
1962 /* Signal the parent process to continue */
1963 SERVER_START_REQ( init_process_done )
1965 req->module = peb->ImageBaseAddress;
1966 req->module_size = wm->ldr.SizeOfImage;
1967 req->entry = (char *)peb->ImageBaseAddress + nt->OptionalHeader.AddressOfEntryPoint;
1968 /* API requires a double indirection */
1969 req->name = &main_exe_name->Buffer;
1970 req->exe_file = main_file;
1971 req->gui = (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_WINDOWS_CUI);
1972 wine_server_add_data( req, main_exe_name->Buffer, main_exe_name->Length );
1973 wine_server_call( req );
1975 SERVER_END_REQ;
1977 if (main_file) NtClose( main_file ); /* we no longer need it */
1979 RtlEnterCriticalSection( &loader_section );
1981 load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1982 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
1983 if ((status = alloc_process_tls()) != STATUS_SUCCESS) goto error;
1984 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto error;
1985 if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS)
1987 if (last_failed_modref)
1988 ERR( "%s failed to initialize, aborting\n", debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
1989 goto error;
1992 RtlLeaveCriticalSection( &loader_section );
1994 if (nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE) VIRTUAL_UseLargeAddressSpace();
1995 return;
1997 error:
1998 ERR( "Main exe initialization for %s failed, status %lx\n", debugstr_w(main_exe_name->Buffer), status );
1999 exit(1);
2003 /***********************************************************************
2004 * RtlImageDirectoryEntryToData (NTDLL.@)
2006 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
2008 const IMAGE_NT_HEADERS *nt;
2009 DWORD addr;
2011 if ((ULONG_PTR)module & 1) /* mapped as data file */
2013 module = (HMODULE)((ULONG_PTR)module & ~1);
2014 image = FALSE;
2016 if (!(nt = RtlImageNtHeader( module ))) return NULL;
2017 if (dir >= nt->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2018 if (!(addr = nt->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2019 *size = nt->OptionalHeader.DataDirectory[dir].Size;
2020 if (image || addr < nt->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2022 /* not mapped as image, need to find the section containing the virtual address */
2023 return RtlImageRvaToVa( nt, module, addr, NULL );
2027 /***********************************************************************
2028 * RtlImageRvaToSection (NTDLL.@)
2030 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
2031 HMODULE module, DWORD rva )
2033 int i;
2034 const IMAGE_SECTION_HEADER *sec;
2036 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
2037 nt->FileHeader.SizeOfOptionalHeader);
2038 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
2040 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2041 return (PIMAGE_SECTION_HEADER)sec;
2043 return NULL;
2047 /***********************************************************************
2048 * RtlImageRvaToVa (NTDLL.@)
2050 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
2051 DWORD rva, IMAGE_SECTION_HEADER **section )
2053 IMAGE_SECTION_HEADER *sec;
2055 if (section && *section) /* try this section first */
2057 sec = *section;
2058 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2059 goto found;
2061 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
2062 found:
2063 if (section) *section = sec;
2064 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
2068 /***********************************************************************
2069 * NtLoadDriver (NTDLL.@)
2070 * ZwLoadDriver (NTDLL.@)
2072 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
2074 FIXME("(%p), stub!\n",DriverServiceName);
2075 return STATUS_NOT_IMPLEMENTED;
2079 /***********************************************************************
2080 * NtUnloadDriver (NTDLL.@)
2081 * ZwUnloadDriver (NTDLL.@)
2083 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
2085 FIXME("(%p), stub!\n",DriverServiceName);
2086 return STATUS_NOT_IMPLEMENTED;
2090 /******************************************************************
2091 * DllMain (NTDLL.@)
2093 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
2095 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
2096 return TRUE;
2100 /******************************************************************
2101 * __wine_init_windows_dir (NTDLL.@)
2103 * Windows and system dir initialization once kernel32 has been loaded.
2105 void __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
2107 PLIST_ENTRY mark, entry;
2108 LPWSTR buffer, p;
2110 RtlCreateUnicodeString( &system_dir, sysdir );
2112 /* prepend the system dir to the name of the already created modules */
2113 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2114 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2116 LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
2118 assert( mod->Flags & LDR_WINE_INTERNAL );
2120 buffer = RtlAllocateHeap( GetProcessHeap(), 0,
2121 system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
2122 if (!buffer) continue;
2123 strcpyW( buffer, system_dir.Buffer );
2124 p = buffer + strlenW( buffer );
2125 if (p > buffer && p[-1] != '\\') *p++ = '\\';
2126 strcpyW( p, mod->FullDllName.Buffer );
2127 RtlInitUnicodeString( &mod->FullDllName, buffer );
2128 RtlInitUnicodeString( &mod->BaseDllName, p );
2133 /***********************************************************************
2134 * __wine_process_init
2136 void __wine_process_init( int argc, char *argv[] )
2138 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
2140 WINE_MODREF *wm;
2141 NTSTATUS status;
2142 ANSI_STRING func_name;
2143 void (* DECLSPEC_NORETURN init_func)();
2144 extern mode_t FILE_umask;
2146 thread_init();
2148 /* retrieve current umask */
2149 FILE_umask = umask(0777);
2150 umask( FILE_umask );
2152 /* setup the load callback and create ntdll modref */
2153 wine_dll_set_callback( load_builtin_callback );
2155 if ((status = load_builtin_dll( NULL, kernel32W, 0, &wm )) != STATUS_SUCCESS)
2157 MESSAGE( "wine: could not load kernel32.dll, status %lx\n", status );
2158 exit(1);
2160 RtlInitAnsiString( &func_name, "__wine_kernel_init" );
2161 if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
2162 0, (void **)&init_func )) != STATUS_SUCCESS)
2164 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %lx\n", status );
2165 exit(1);
2167 init_func();