Moved some more definitions out of undocshell.h into the exported
[wine/multimedia.git] / dlls / ntdll / loader.c
blob40f2063d0c678b0a3ae231eb75aa113385200b1c
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 #include "windef.h"
29 #include "winbase.h"
30 #include "winnt.h"
31 #include "winreg.h"
32 #include "winternl.h"
34 #include "module.h"
35 #include "wine/exception.h"
36 #include "excpt.h"
37 #include "wine/unicode.h"
38 #include "wine/debug.h"
39 #include "wine/server.h"
40 #include "ntdll_misc.h"
42 WINE_DEFAULT_DEBUG_CHANNEL(module);
43 WINE_DECLARE_DEBUG_CHANNEL(relay);
44 WINE_DECLARE_DEBUG_CHANNEL(snoop);
45 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
47 typedef DWORD (CALLBACK *DLLENTRYPROC)(HMODULE,DWORD,LPVOID);
49 static int process_detaching = 0; /* set on process detach to avoid deadlocks with thread detach */
50 static int free_lib_count; /* recursion depth of LdrUnloadDll calls */
52 /* filter for page-fault exceptions */
53 static WINE_EXCEPTION_FILTER(page_fault)
55 if (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION)
56 return EXCEPTION_EXECUTE_HANDLER;
57 return EXCEPTION_CONTINUE_SEARCH;
60 static const char * const reason_names[] =
62 "PROCESS_DETACH",
63 "PROCESS_ATTACH",
64 "THREAD_ATTACH",
65 "THREAD_DETACH"
68 static const WCHAR dllW[] = {'.','d','l','l',0};
70 /* internal representation of 32bit modules. per process. */
71 typedef struct _wine_modref
73 LDR_MODULE ldr;
74 int nDeps;
75 struct _wine_modref **deps;
76 } WINE_MODREF;
78 /* info about the current builtin dll load */
79 /* used to keep track of things across the register_dll constructor call */
80 struct builtin_load_info
82 const WCHAR *load_path;
83 NTSTATUS status;
84 WINE_MODREF *wm;
87 static struct builtin_load_info default_load_info;
88 static struct builtin_load_info *builtin_load_info = &default_load_info;
90 static UINT tls_module_count; /* number of modules with TLS directory */
91 static UINT tls_total_size; /* total size of TLS storage */
92 static const IMAGE_TLS_DIRECTORY **tls_dirs; /* array of TLS directories */
94 static UNICODE_STRING system_dir; /* system directory */
96 static CRITICAL_SECTION loader_section;
97 static CRITICAL_SECTION_DEBUG critsect_debug =
99 0, 0, &loader_section,
100 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
101 0, 0, { 0, (DWORD)(__FILE__ ": loader_section") }
103 static CRITICAL_SECTION loader_section = { &critsect_debug, -1, 0, 0, 0, 0 };
105 static WINE_MODREF *cached_modref;
106 static WINE_MODREF *current_modref;
108 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm );
109 static FARPROC find_named_export( HMODULE module, IMAGE_EXPORT_DIRECTORY *exports,
110 DWORD exp_size, const char *name, int hint );
112 /* convert PE image VirtualAddress to Real Address */
113 inline static void *get_rva( HMODULE module, DWORD va )
115 return (void *)((char *)module + va);
118 /* check whether the file name contains a path */
119 inline static int contains_path( LPCWSTR name )
121 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
124 /* convert from straight ASCII to Unicode without depending on the current codepage */
125 inline static void ascii_to_unicode( WCHAR *dst, const char *src, size_t len )
127 while (len--) *dst++ = (unsigned char)*src++;
130 /*************************************************************************
131 * get_modref
133 * Looks for the referenced HMODULE in the current process
134 * The loader_section must be locked while calling this function.
136 static WINE_MODREF *get_modref( HMODULE hmod )
138 PLIST_ENTRY mark, entry;
139 PLDR_MODULE mod;
141 if (cached_modref && cached_modref->ldr.BaseAddress == hmod) return cached_modref;
143 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
144 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
146 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
147 if (mod->BaseAddress == hmod)
148 return cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
149 if (mod->BaseAddress > (void*)hmod) break;
151 return NULL;
155 /**********************************************************************
156 * find_basename_module
158 * Find a module from its base name.
159 * The loader_section must be locked while calling this function
161 static WINE_MODREF *find_basename_module( LPCWSTR name )
163 PLIST_ENTRY mark, entry;
165 if (cached_modref && !strcmpiW( name, cached_modref->ldr.BaseDllName.Buffer ))
166 return cached_modref;
168 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
169 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
171 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
172 if (!strcmpiW( name, mod->BaseDllName.Buffer ))
174 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
175 return cached_modref;
178 return NULL;
182 /**********************************************************************
183 * find_fullname_module
185 * Find a module from its full path name.
186 * The loader_section must be locked while calling this function
188 static WINE_MODREF *find_fullname_module( LPCWSTR name )
190 PLIST_ENTRY mark, entry;
192 if (cached_modref && !strcmpiW( name, cached_modref->ldr.FullDllName.Buffer ))
193 return cached_modref;
195 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
196 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
198 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
199 if (!strcmpiW( name, mod->FullDllName.Buffer ))
201 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
202 return cached_modref;
205 return NULL;
209 /*************************************************************************
210 * find_forwarded_export
212 * Find the final function pointer for a forwarded function.
213 * The loader_section must be locked while calling this function.
215 static FARPROC find_forwarded_export( HMODULE module, const char *forward )
217 IMAGE_EXPORT_DIRECTORY *exports;
218 DWORD exp_size;
219 WINE_MODREF *wm;
220 WCHAR mod_name[32];
221 char *end = strchr(forward, '.');
222 FARPROC proc = NULL;
224 if (!end) return NULL;
225 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name) - sizeof(dllW)) return NULL;
226 ascii_to_unicode( mod_name, forward, end - forward );
227 memcpy( mod_name + (end - forward), dllW, sizeof(dllW) );
229 if (!(wm = find_basename_module( mod_name )))
231 ERR("module not found for forward '%s' used by %s\n",
232 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer) );
233 return NULL;
235 if ((exports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
236 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
237 proc = find_named_export( wm->ldr.BaseAddress, exports, exp_size, end + 1, -1 );
239 if (!proc)
241 ERR("function not found for forward '%s' used by %s."
242 " If you are using builtin %s, try using the native one instead.\n",
243 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer),
244 debugstr_w(get_modref(module)->ldr.BaseDllName.Buffer) );
246 return proc;
250 /*************************************************************************
251 * find_ordinal_export
253 * Find an exported function by ordinal.
254 * The exports base must have been subtracted from the ordinal already.
255 * The loader_section must be locked while calling this function.
257 static FARPROC find_ordinal_export( HMODULE module, IMAGE_EXPORT_DIRECTORY *exports,
258 DWORD exp_size, int ordinal )
260 FARPROC proc;
261 DWORD *functions = get_rva( module, exports->AddressOfFunctions );
263 if (ordinal >= exports->NumberOfFunctions)
265 TRACE(" ordinal %ld out of range!\n", ordinal + exports->Base );
266 return NULL;
268 if (!functions[ordinal]) return NULL;
270 proc = get_rva( module, functions[ordinal] );
272 /* if the address falls into the export dir, it's a forward */
273 if (((char *)proc >= (char *)exports) && ((char *)proc < (char *)exports + exp_size))
274 return find_forwarded_export( module, (char *)proc );
276 if (TRACE_ON(snoop))
278 proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal );
280 if (TRACE_ON(relay) && current_modref)
282 proc = RELAY_GetProcAddress( module, exports, exp_size, proc,
283 current_modref->ldr.BaseDllName.Buffer );
285 return proc;
289 /*************************************************************************
290 * find_named_export
292 * Find an exported function by name.
293 * The loader_section must be locked while calling this function.
295 static FARPROC find_named_export( HMODULE module, IMAGE_EXPORT_DIRECTORY *exports,
296 DWORD exp_size, const char *name, int hint )
298 WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
299 DWORD *names = get_rva( module, exports->AddressOfNames );
300 int min = 0, max = exports->NumberOfNames - 1;
302 /* first check the hint */
303 if (hint >= 0 && hint <= max)
305 char *ename = get_rva( module, names[hint] );
306 if (!strcmp( ename, name ))
307 return find_ordinal_export( module, exports, exp_size, ordinals[hint] );
310 /* then do a binary search */
311 while (min <= max)
313 int res, pos = (min + max) / 2;
314 char *ename = get_rva( module, names[pos] );
315 if (!(res = strcmp( ename, name )))
316 return find_ordinal_export( module, exports, exp_size, ordinals[pos] );
317 if (res > 0) max = pos - 1;
318 else min = pos + 1;
320 return NULL;
325 /*************************************************************************
326 * import_dll
328 * Import the dll specified by the given import descriptor.
329 * The loader_section must be locked while calling this function.
331 static WINE_MODREF *import_dll( HMODULE module, IMAGE_IMPORT_DESCRIPTOR *descr, LPCWSTR load_path )
333 NTSTATUS status;
334 WINE_MODREF *wmImp;
335 HMODULE imp_mod;
336 IMAGE_EXPORT_DIRECTORY *exports;
337 DWORD exp_size;
338 IMAGE_THUNK_DATA *import_list, *thunk_list;
339 WCHAR buffer[32];
340 char *name = get_rva( module, descr->Name );
341 DWORD len = strlen(name) + 1;
343 thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
344 if (descr->u.OriginalFirstThunk)
345 import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
346 else
347 import_list = thunk_list;
349 if (len * sizeof(WCHAR) <= sizeof(buffer))
351 ascii_to_unicode( buffer, name, len );
352 status = load_dll( load_path, buffer, 0, &wmImp );
354 else /* need to allocate a larger buffer */
356 WCHAR *ptr = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR) );
357 if (!ptr) return NULL;
358 ascii_to_unicode( ptr, name, len );
359 status = load_dll( load_path, ptr, 0, &wmImp );
360 RtlFreeHeap( GetProcessHeap(), 0, ptr );
363 if (status)
365 if (status == STATUS_DLL_NOT_FOUND)
366 ERR("Module (file) %s (which is needed by %s) not found\n",
367 name, debugstr_w(current_modref->ldr.FullDllName.Buffer));
368 else
369 ERR("Loading module (file) %s (which is needed by %s) failed (error %lx).\n",
370 name, debugstr_w(current_modref->ldr.FullDllName.Buffer), status);
371 imp_mod = NULL;
372 exports = NULL;
374 else
376 imp_mod = wmImp->ldr.BaseAddress;
377 exports = RtlImageDirectoryEntryToData( imp_mod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
380 if (!exports)
382 /* set all imported function to deadbeef */
383 while (import_list->u1.Ordinal)
385 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
387 ERR("No implementation for %s.%ld", name, IMAGE_ORDINAL(import_list->u1.Ordinal));
389 else
391 IMAGE_IMPORT_BY_NAME *pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
392 ERR("No implementation for %s.%s", name, pe_name->Name );
394 ERR(" imported from %s, setting to 0xdeadbeef\n",
395 debugstr_w(current_modref->ldr.FullDllName.Buffer) );
396 thunk_list->u1.Function = (PDWORD)0xdeadbeef;
398 import_list++;
399 thunk_list++;
401 return wmImp;
404 while (import_list->u1.Ordinal)
406 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
408 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
410 thunk_list->u1.Function = (PDWORD)find_ordinal_export( imp_mod, exports, exp_size,
411 ordinal - exports->Base );
412 if (!thunk_list->u1.Function)
414 ERR("No implementation for %s.%d imported from %s, setting to 0xdeadbeef\n",
415 name, ordinal, debugstr_w(current_modref->ldr.FullDllName.Buffer) );
416 thunk_list->u1.Function = (PDWORD)0xdeadbeef;
418 TRACE("--- Ordinal %s.%d = %p\n", name, ordinal, thunk_list->u1.Function );
420 else /* import by name */
422 IMAGE_IMPORT_BY_NAME *pe_name;
423 pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
424 thunk_list->u1.Function = (PDWORD)find_named_export( imp_mod, exports, exp_size,
425 pe_name->Name, pe_name->Hint );
426 if (!thunk_list->u1.Function)
428 ERR("No implementation for %s.%s imported from %s, setting to 0xdeadbeef\n",
429 name, pe_name->Name, debugstr_w(current_modref->ldr.FullDllName.Buffer) );
430 thunk_list->u1.Function = (PDWORD)0xdeadbeef;
432 TRACE("--- %s %s.%d = %p\n", pe_name->Name, name, pe_name->Hint, thunk_list->u1.Function);
434 import_list++;
435 thunk_list++;
437 return wmImp;
441 /****************************************************************
442 * fixup_imports
444 * Fixup all imports of a given module.
445 * The loader_section must be locked while calling this function.
447 static NTSTATUS fixup_imports( WINE_MODREF *wm, LPCWSTR load_path )
449 int i, nb_imports;
450 IMAGE_IMPORT_DESCRIPTOR *imports;
451 WINE_MODREF *prev;
452 DWORD size;
453 NTSTATUS status;
455 if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
456 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
457 return STATUS_SUCCESS;
459 nb_imports = size / sizeof(*imports);
460 for (i = 0; i < nb_imports; i++)
462 if (!imports[i].Name)
464 nb_imports = i;
465 break;
468 if (!nb_imports) return STATUS_SUCCESS; /* no imports */
470 /* Allocate module dependency list */
471 wm->nDeps = nb_imports;
472 wm->deps = RtlAllocateHeap( ntdll_get_process_heap(), 0, nb_imports*sizeof(WINE_MODREF *) );
474 /* load the imported modules. They are automatically
475 * added to the modref list of the process.
477 prev = current_modref;
478 current_modref = wm;
479 status = STATUS_SUCCESS;
480 for (i = 0; i < nb_imports; i++)
482 if (!(wm->deps[i] = import_dll( wm->ldr.BaseAddress, &imports[i], load_path )))
483 status = STATUS_DLL_NOT_FOUND;
485 current_modref = prev;
486 return status;
490 /*************************************************************************
491 * alloc_module
493 * Allocate a WINE_MODREF structure and add it to the process list
494 * The loader_section must be locked while calling this function.
496 static WINE_MODREF *alloc_module( HMODULE hModule, LPCWSTR filename )
498 WINE_MODREF *wm;
499 WCHAR *p;
500 IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
501 PLIST_ENTRY entry, mark;
503 if (!(wm = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm) ))) return NULL;
505 wm->nDeps = 0;
506 wm->deps = NULL;
508 wm->ldr.BaseAddress = hModule;
509 wm->ldr.EntryPoint = NULL;
510 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
511 wm->ldr.Flags = 0;
512 wm->ldr.LoadCount = 0;
513 wm->ldr.TlsIndex = -1;
514 wm->ldr.SectionHandle = NULL;
515 wm->ldr.CheckSum = 0;
516 wm->ldr.TimeDateStamp = 0;
518 RtlCreateUnicodeString( &wm->ldr.FullDllName, filename );
519 if ((p = strrchrW( wm->ldr.FullDllName.Buffer, '\\' ))) p++;
520 else p = wm->ldr.FullDllName.Buffer;
521 RtlInitUnicodeString( &wm->ldr.BaseDllName, p );
523 if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
525 wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
526 if (nt->OptionalHeader.AddressOfEntryPoint)
527 wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
530 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
531 &wm->ldr.InLoadOrderModuleList);
533 /* insert module in MemoryList, sorted in increasing base addresses */
534 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
535 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
537 if (CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList)->BaseAddress > wm->ldr.BaseAddress)
538 break;
540 entry->Blink->Flink = &wm->ldr.InMemoryOrderModuleList;
541 wm->ldr.InMemoryOrderModuleList.Blink = entry->Blink;
542 wm->ldr.InMemoryOrderModuleList.Flink = entry;
543 entry->Blink = &wm->ldr.InMemoryOrderModuleList;
545 /* wait until init is called for inserting into this list */
546 wm->ldr.InInitializationOrderModuleList.Flink = NULL;
547 wm->ldr.InInitializationOrderModuleList.Blink = NULL;
548 return wm;
552 /*************************************************************************
553 * alloc_process_tls
555 * Allocate the process-wide structure for module TLS storage.
557 static NTSTATUS alloc_process_tls(void)
559 PLIST_ENTRY mark, entry;
560 PLDR_MODULE mod;
561 IMAGE_TLS_DIRECTORY *dir;
562 ULONG size, i;
564 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
565 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
567 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
568 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
569 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
570 continue;
571 size = (dir->EndAddressOfRawData - dir->StartAddressOfRawData) + dir->SizeOfZeroFill;
572 if (!size) continue;
573 tls_total_size += size;
574 tls_module_count++;
576 if (!tls_module_count) return STATUS_SUCCESS;
578 TRACE( "count %u size %u\n", tls_module_count, tls_total_size );
580 tls_dirs = RtlAllocateHeap( ntdll_get_process_heap(), 0, tls_module_count * sizeof(*tls_dirs) );
581 if (!tls_dirs) return STATUS_NO_MEMORY;
583 for (i = 0, entry = mark->Flink; entry != mark; entry = entry->Flink)
585 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
586 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
587 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
588 continue;
589 tls_dirs[i] = dir;
590 *dir->AddressOfIndex = i;
591 mod->TlsIndex = i;
592 mod->LoadCount = -1; /* can't unload it */
593 i++;
595 return STATUS_SUCCESS;
599 /*************************************************************************
600 * alloc_thread_tls
602 * Allocate the per-thread structure for module TLS storage.
604 static NTSTATUS alloc_thread_tls(void)
606 void **pointers;
607 char *data;
608 UINT i;
610 if (!tls_module_count) return STATUS_SUCCESS;
612 if (!(pointers = RtlAllocateHeap( ntdll_get_process_heap(), 0,
613 tls_module_count * sizeof(*pointers) )))
614 return STATUS_NO_MEMORY;
616 if (!(data = RtlAllocateHeap( ntdll_get_process_heap(), 0, tls_total_size )))
618 RtlFreeHeap( ntdll_get_process_heap(), 0, pointers );
619 return STATUS_NO_MEMORY;
622 for (i = 0; i < tls_module_count; i++)
624 const IMAGE_TLS_DIRECTORY *dir = tls_dirs[i];
625 ULONG size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
627 TRACE( "thread %04lx idx %d: %ld/%ld bytes from %p to %p\n",
628 GetCurrentThreadId(), i, size, dir->SizeOfZeroFill,
629 (void *)dir->StartAddressOfRawData, data );
631 pointers[i] = data;
632 memcpy( data, (void *)dir->StartAddressOfRawData, size );
633 data += size;
634 memset( data, 0, dir->SizeOfZeroFill );
635 data += dir->SizeOfZeroFill;
637 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
638 return STATUS_SUCCESS;
642 /*************************************************************************
643 * call_tls_callbacks
645 static void call_tls_callbacks( HMODULE module, UINT reason )
647 const IMAGE_TLS_DIRECTORY *dir;
648 const PIMAGE_TLS_CALLBACK *callback;
649 ULONG dirsize;
651 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
652 if (!dir || !dir->AddressOfCallBacks) return;
654 for (callback = dir->AddressOfCallBacks; *callback; callback++)
656 if (TRACE_ON(relay))
657 DPRINTF("%04lx:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
658 GetCurrentThreadId(), *callback, module, reason_names[reason] );
659 (*callback)( module, reason, NULL );
660 if (TRACE_ON(relay))
661 DPRINTF("%04lx:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
662 GetCurrentThreadId(), *callback, module, reason_names[reason] );
667 /*************************************************************************
668 * MODULE_InitDLL
670 static BOOL MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
672 WCHAR mod_name[32];
673 BOOL retv = TRUE;
674 DLLENTRYPROC entry = wm->ldr.EntryPoint;
675 void *module = wm->ldr.BaseAddress;
677 /* Skip calls for modules loaded with special load flags */
679 if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return TRUE;
680 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.BaseAddress, reason );
681 if (!entry) return TRUE;
683 if (TRACE_ON(relay))
685 size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
686 memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
687 mod_name[len / sizeof(WCHAR)] = 0;
688 DPRINTF("%04lx:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
689 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
690 reason_names[reason], lpReserved );
692 else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
693 reason_names[reason], lpReserved );
695 retv = entry( module, reason, lpReserved );
697 /* The state of the module list may have changed due to the call
698 to the dll. We cannot assume that this module has not been
699 deleted. */
700 if (TRACE_ON(relay))
701 DPRINTF("%04lx:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
702 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
703 reason_names[reason], lpReserved, retv );
704 else TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
706 return retv;
710 /*************************************************************************
711 * process_attach
713 * Send the process attach notification to all DLLs the given module
714 * depends on (recursively). This is somewhat complicated due to the fact that
716 * - we have to respect the module dependencies, i.e. modules implicitly
717 * referenced by another module have to be initialized before the module
718 * itself can be initialized
720 * - the initialization routine of a DLL can itself call LoadLibrary,
721 * thereby introducing a whole new set of dependencies (even involving
722 * the 'old' modules) at any time during the whole process
724 * (Note that this routine can be recursively entered not only directly
725 * from itself, but also via LoadLibrary from one of the called initialization
726 * routines.)
728 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
729 * the process *detach* notifications to be sent in the correct order.
730 * This must not only take into account module dependencies, but also
731 * 'hidden' dependencies created by modules calling LoadLibrary in their
732 * attach notification routine.
734 * The strategy is rather simple: we move a WINE_MODREF to the head of the
735 * list after the attach notification has returned. This implies that the
736 * detach notifications are called in the reverse of the sequence the attach
737 * notifications *returned*.
739 * The loader_section must be locked while calling this function.
741 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
743 NTSTATUS status = STATUS_SUCCESS;
744 int i;
746 /* prevent infinite recursion in case of cyclical dependencies */
747 if ( ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
748 || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
749 return status;
751 TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
753 /* Tag current MODREF to prevent recursive loop */
754 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
756 /* Recursively attach all DLLs this one depends on */
757 for ( i = 0; i < wm->nDeps; i++ )
759 if (!wm->deps[i]) continue;
760 if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
763 /* Call DLL entry point */
764 if (status == STATUS_SUCCESS)
766 WINE_MODREF *prev = current_modref;
767 current_modref = wm;
768 if (MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved ))
769 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
770 else
771 status = STATUS_DLL_INIT_FAILED;
772 current_modref = prev;
775 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
776 &wm->ldr.InInitializationOrderModuleList);
778 /* Remove recursion flag */
779 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
781 TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
782 return status;
785 /*************************************************************************
786 * process_detach
788 * Send DLL process detach notifications. See the comment about calling
789 * sequence at process_attach. Unless the bForceDetach flag
790 * is set, only DLLs with zero refcount are notified.
792 static void process_detach( BOOL bForceDetach, LPVOID lpReserved )
794 PLIST_ENTRY mark, entry;
795 PLDR_MODULE mod;
797 RtlEnterCriticalSection( &loader_section );
798 if (bForceDetach) process_detaching = 1;
799 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
802 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
804 mod = CONTAINING_RECORD(entry, LDR_MODULE,
805 InInitializationOrderModuleList);
806 /* Check whether to detach this DLL */
807 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
808 continue;
809 if ( mod->LoadCount && !bForceDetach )
810 continue;
812 /* Call detach notification */
813 mod->Flags &= ~LDR_PROCESS_ATTACHED;
814 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
815 DLL_PROCESS_DETACH, lpReserved );
817 /* Restart at head of WINE_MODREF list, as entries might have
818 been added and/or removed while performing the call ... */
819 break;
821 } while (entry != mark);
823 RtlLeaveCriticalSection( &loader_section );
826 /*************************************************************************
827 * MODULE_DllThreadAttach
829 * Send DLL thread attach notifications. These are sent in the
830 * reverse sequence of process detach notification.
833 NTSTATUS MODULE_DllThreadAttach( LPVOID lpReserved )
835 PLIST_ENTRY mark, entry;
836 PLDR_MODULE mod;
837 NTSTATUS status;
839 /* don't do any attach calls if process is exiting */
840 if (process_detaching) return STATUS_SUCCESS;
841 /* FIXME: there is still a race here */
843 RtlEnterCriticalSection( &loader_section );
845 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto done;
847 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
848 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
850 mod = CONTAINING_RECORD(entry, LDR_MODULE,
851 InInitializationOrderModuleList);
852 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
853 continue;
854 if ( mod->Flags & LDR_NO_DLL_CALLS )
855 continue;
857 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
858 DLL_THREAD_ATTACH, lpReserved );
861 done:
862 RtlLeaveCriticalSection( &loader_section );
863 return status;
866 /******************************************************************
867 * LdrDisableThreadCalloutsForDll (NTDLL.@)
870 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
872 WINE_MODREF *wm;
873 NTSTATUS ret = STATUS_SUCCESS;
875 RtlEnterCriticalSection( &loader_section );
877 wm = get_modref( hModule );
878 if (!wm || wm->ldr.TlsIndex != -1)
879 ret = STATUS_DLL_NOT_FOUND;
880 else
881 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
883 RtlLeaveCriticalSection( &loader_section );
885 return ret;
888 /******************************************************************
889 * LdrFindEntryForAddress (NTDLL.@)
891 * The loader_section must be locked while calling this function
893 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
895 PLIST_ENTRY mark, entry;
896 PLDR_MODULE mod;
898 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
899 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
901 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
902 if ((const void *)mod->BaseAddress <= addr &&
903 (char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
905 *pmod = mod;
906 return STATUS_SUCCESS;
908 if ((const void *)mod->BaseAddress > addr) break;
910 return STATUS_NO_MORE_ENTRIES;
913 /******************************************************************
914 * LdrLockLoaderLock (NTDLL.@)
916 * Note: flags are not implemented.
917 * Flag 0x01 is used to raise exceptions on errors.
918 * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
920 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG *magic )
922 if (flags) FIXME( "flags %lx not supported\n", flags );
924 if (result) *result = 1;
925 if (!magic) return STATUS_INVALID_PARAMETER_3;
926 RtlEnterCriticalSection( &loader_section );
927 *magic = GetCurrentThreadId();
928 return STATUS_SUCCESS;
932 /******************************************************************
933 * LdrUnlockLoaderUnlock (NTDLL.@)
935 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG magic )
937 if (magic)
939 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
940 RtlLeaveCriticalSection( &loader_section );
942 return STATUS_SUCCESS;
946 /******************************************************************
947 * LdrGetDllHandle (NTDLL.@)
949 NTSTATUS WINAPI LdrGetDllHandle(ULONG x, ULONG y, const UNICODE_STRING *name, HMODULE *base)
951 NTSTATUS status = STATUS_DLL_NOT_FOUND;
952 WCHAR dllname[MAX_PATH+4], *p;
953 UNICODE_STRING str;
954 PLIST_ENTRY mark, entry;
955 PLDR_MODULE mod;
957 if (x != 0 || y != 0)
958 FIXME("Unknown behavior, please report\n");
960 /* Append .DLL to name if no extension present */
961 if (!(p = strrchrW( name->Buffer, '.')) || strchrW( p, '/' ) || strchrW( p, '\\'))
963 if (name->Length >= MAX_PATH) return STATUS_NAME_TOO_LONG;
964 strcpyW( dllname, name->Buffer );
965 strcatW( dllname, dllW );
966 RtlInitUnicodeString( &str, dllname );
967 name = &str;
970 RtlEnterCriticalSection( &loader_section );
972 if (cached_modref)
974 if (RtlEqualUnicodeString( name, &cached_modref->ldr.FullDllName, TRUE ) ||
975 RtlEqualUnicodeString( name, &cached_modref->ldr.BaseDllName, TRUE ))
977 *base = cached_modref->ldr.BaseAddress;
978 status = STATUS_SUCCESS;
979 goto done;
983 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
984 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
986 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
988 if (RtlEqualUnicodeString( name, &mod->FullDllName, TRUE ) ||
989 RtlEqualUnicodeString( name, &mod->BaseDllName, TRUE ))
991 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
992 *base = mod->BaseAddress;
993 status = STATUS_SUCCESS;
994 break;
997 done:
998 RtlLeaveCriticalSection( &loader_section );
999 TRACE("%lx %lx %s -> %p\n", x, y, debugstr_us(name), status ? NULL : *base);
1000 return status;
1004 /******************************************************************
1005 * LdrGetProcedureAddress (NTDLL.@)
1007 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1008 ULONG ord, PVOID *address)
1010 IMAGE_EXPORT_DIRECTORY *exports;
1011 DWORD exp_size;
1012 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1014 RtlEnterCriticalSection( &loader_section );
1016 if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1017 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1019 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1 )
1020 : find_ordinal_export( module, exports, exp_size, ord - exports->Base );
1021 if (proc)
1023 *address = proc;
1024 ret = STATUS_SUCCESS;
1027 else
1029 /* check if the module itself is invalid to return the proper error */
1030 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1033 RtlLeaveCriticalSection( &loader_section );
1034 return ret;
1038 /***********************************************************************
1039 * load_builtin_callback
1041 * Load a library in memory; callback function for wine_dll_register
1043 static void load_builtin_callback( void *module, const char *filename )
1045 static const WCHAR emptyW[1];
1046 void *addr;
1047 IMAGE_NT_HEADERS *nt;
1048 WINE_MODREF *wm;
1049 WCHAR *fullname, *p;
1050 const WCHAR *load_path;
1052 if (!module)
1054 ERR("could not map image for %s\n", filename ? filename : "main exe" );
1055 return;
1057 if (!(nt = RtlImageNtHeader( module )))
1059 ERR( "bad module for %s\n", filename ? filename : "main exe" );
1060 builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1061 return;
1063 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL))
1065 /* if we already have an executable, ignore this one */
1066 if (!NtCurrentTeb()->Peb->ImageBaseAddress)
1068 NtCurrentTeb()->Peb->ImageBaseAddress = module;
1069 return; /* don't create the modref here, will be done later on */
1073 /* create the MODREF */
1075 if (!(fullname = RtlAllocateHeap( GetProcessHeap(), 0,
1076 system_dir.MaximumLength + (strlen(filename) + 1) * sizeof(WCHAR) )))
1078 ERR( "can't load %s\n", filename );
1079 builtin_load_info->status = STATUS_NO_MEMORY;
1080 return;
1082 memcpy( fullname, system_dir.Buffer, system_dir.Length );
1083 p = fullname + system_dir.Length / sizeof(WCHAR);
1084 if (p > fullname && p[-1] != '\\') *p++ = '\\';
1085 ascii_to_unicode( p, filename, strlen(filename) + 1 );
1087 wm = alloc_module( module, fullname );
1088 RtlFreeHeap( GetProcessHeap(), 0, fullname );
1089 if (!wm)
1091 ERR( "can't load %s\n", filename );
1092 builtin_load_info->status = STATUS_NO_MEMORY;
1093 return;
1095 wm->ldr.Flags |= LDR_WINE_INTERNAL;
1096 NtAllocateVirtualMemory( GetCurrentProcess(), &addr, module, &nt->OptionalHeader.SizeOfImage,
1097 MEM_SYSTEM | MEM_IMAGE, PAGE_EXECUTE_WRITECOPY );
1099 /* fixup imports */
1101 load_path = builtin_load_info->load_path;
1102 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1103 if (!load_path) load_path = emptyW;
1104 if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1106 /* the module has only be inserted in the load & memory order lists */
1107 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1108 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1109 /* FIXME: free the modref */
1110 builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1111 return;
1113 builtin_load_info->wm = wm;
1114 TRACE( "loaded %s %p %p\n", filename, wm, module );
1116 /* send the DLL load event */
1118 SERVER_START_REQ( load_dll )
1120 req->handle = 0;
1121 req->base = module;
1122 req->size = nt->OptionalHeader.SizeOfImage;
1123 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1124 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1125 req->name = &wm->ldr.FullDllName.Buffer;
1126 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1127 wine_server_call( req );
1129 SERVER_END_REQ;
1131 /* setup relay debugging entry points */
1132 if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1136 /******************************************************************************
1137 * load_native_dll (internal)
1139 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1140 DWORD flags, WINE_MODREF** pwm )
1142 void *module;
1143 HANDLE mapping;
1144 OBJECT_ATTRIBUTES attr;
1145 LARGE_INTEGER size;
1146 IMAGE_NT_HEADERS *nt;
1147 DWORD len = 0;
1148 WINE_MODREF *wm;
1149 NTSTATUS status;
1151 TRACE( "loading %s\n", debugstr_w(name) );
1153 attr.Length = sizeof(attr);
1154 attr.RootDirectory = 0;
1155 attr.ObjectName = NULL;
1156 attr.Attributes = 0;
1157 attr.SecurityDescriptor = NULL;
1158 attr.SecurityQualityOfService = NULL;
1159 size.QuadPart = 0;
1161 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1162 &attr, &size, 0, SEC_IMAGE, file );
1163 if (status != STATUS_SUCCESS) return status;
1165 module = NULL;
1166 status = NtMapViewOfSection( mapping, GetCurrentProcess(),
1167 &module, 0, 0, &size, &len, ViewShare, 0, PAGE_READONLY );
1168 NtClose( mapping );
1169 if (status != STATUS_SUCCESS) return status;
1171 /* create the MODREF */
1173 if (!(wm = alloc_module( module, name ))) return STATUS_NO_MEMORY;
1175 /* fixup imports */
1177 if (!(flags & DONT_RESOLVE_DLL_REFERENCES))
1179 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1181 /* the module has only be inserted in the load & memory order lists */
1182 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1183 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1185 /* FIXME: there are several more dangling references
1186 * left. Including dlls loaded by this dll before the
1187 * failed one. Unrolling is rather difficult with the
1188 * current structure and we can leave them lying
1189 * around with no problems, so we don't care.
1190 * As these might reference our wm, we don't free it.
1192 return status;
1195 else wm->ldr.Flags |= LDR_DONT_RESOLVE_REFS;
1197 /* send DLL load event */
1199 nt = RtlImageNtHeader( module );
1201 SERVER_START_REQ( load_dll )
1203 req->handle = file;
1204 req->base = module;
1205 req->size = nt->OptionalHeader.SizeOfImage;
1206 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1207 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1208 req->name = &wm->ldr.FullDllName.Buffer;
1209 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1210 wine_server_call( req );
1212 SERVER_END_REQ;
1214 if (TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1216 *pwm = wm;
1217 return STATUS_SUCCESS;
1221 /***********************************************************************
1222 * load_builtin_dll
1224 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, DWORD flags, WINE_MODREF** pwm )
1226 char error[256], dllname[MAX_PATH];
1227 int file_exists;
1228 const WCHAR *name, *p;
1229 DWORD len, i;
1230 void *handle;
1231 struct builtin_load_info info, *prev_info;
1233 /* Fix the name in case we have a full path and extension */
1234 name = path;
1235 if ((p = strrchrW( name, '\\' ))) name = p + 1;
1236 if ((p = strrchrW( name, '/' ))) name = p + 1;
1238 /* we don't want to depend on the current codepage here */
1239 len = strlenW( name ) + 1;
1240 if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1241 for (i = 0; i < len; i++)
1243 if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1244 dllname[i] = (char)name[i];
1245 if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1248 /* load_library will modify info.status. Note also that load_library can be
1249 * called several times, if the .so file we're loading has dependencies.
1250 * info.status will gather all the errors we may get while loading all these
1251 * libraries
1253 info.load_path = load_path;
1254 info.status = STATUS_SUCCESS;
1255 info.wm = NULL;
1256 prev_info = builtin_load_info;
1257 builtin_load_info = &info;
1258 handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1259 builtin_load_info = prev_info;
1261 if (!handle)
1263 if (!file_exists)
1265 /* The file does not exist -> WARN() */
1266 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
1267 return STATUS_DLL_NOT_FOUND;
1269 /* ERR() for all other errors (missing functions, ...) */
1270 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
1271 return STATUS_PROCEDURE_NOT_FOUND;
1273 if (info.status != STATUS_SUCCESS) return info.status;
1275 if (!info.wm)
1277 /* The constructor wasn't called, this means the .so is already
1278 * loaded under a different name. We can't support multiple names
1279 * for the same module, so return an error. */
1280 return STATUS_INVALID_IMAGE_FORMAT;
1283 info.wm->ldr.SectionHandle = handle;
1284 if (strcmpiW( info.wm->ldr.BaseDllName.Buffer, name ))
1286 ERR( "loaded .so for %s but got %s instead - probably 16-bit dll\n",
1287 debugstr_w(name), debugstr_w(info.wm->ldr.BaseDllName.Buffer) );
1288 /* wine_dll_unload( handle );*/
1289 return STATUS_INVALID_IMAGE_FORMAT;
1291 *pwm = info.wm;
1292 return STATUS_SUCCESS;
1296 /***********************************************************************
1297 * find_dll_file
1299 * Find the file (or already loaded module) for a given dll name.
1301 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
1302 WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
1304 WCHAR *file_part, *ext;
1305 ULONG len;
1307 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
1309 /* we need to search for it */
1310 /* but first append .dll because RtlDosSearchPath extension handling is broken */
1311 if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
1313 WCHAR *dllname;
1315 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
1316 (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
1317 return STATUS_NO_MEMORY;
1318 strcpyW( dllname, libname );
1319 strcatW( dllname, dllW );
1320 len = RtlDosSearchPath_U( load_path, dllname, NULL, *size, filename, &file_part );
1321 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1323 else len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
1325 if (len)
1327 if (len >= *size)
1329 *size = len + sizeof(WCHAR);
1330 return STATUS_BUFFER_TOO_SMALL;
1332 if ((*pwm = find_fullname_module( filename )) != NULL) return STATUS_SUCCESS;
1334 /* check for already loaded module in a different path */
1335 if (!contains_path( libname ))
1337 if ((*pwm = find_basename_module( file_part )) != NULL) return STATUS_SUCCESS;
1339 *handle = pCreateFileW( filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0 );
1340 return STATUS_SUCCESS;
1343 /* not found */
1345 if (!contains_path( libname ))
1347 /* if libname doesn't contain a path at all, we simply return the name as is,
1348 * to be loaded as builtin */
1349 len = strlenW(libname) * sizeof(WCHAR);
1350 if (len >= *size) goto overflow;
1351 strcpyW( filename, libname );
1352 if (!strchrW( filename, '.' ))
1354 len += sizeof(dllW) - sizeof(WCHAR);
1355 if (len >= *size) goto overflow;
1356 strcatW( filename, dllW );
1358 *pwm = find_basename_module( filename );
1359 return STATUS_SUCCESS;
1363 /* absolute path name, or relative path name but not found above */
1365 len = RtlGetFullPathName_U( libname, *size, filename, &file_part );
1366 if (len >= *size) goto overflow;
1367 if (file_part && !strchrW( file_part, '.' ))
1369 len += sizeof(dllW) - sizeof(WCHAR);
1370 if (len >= *size) goto overflow;
1371 strcatW( file_part, dllW );
1373 if ((*pwm = find_fullname_module( filename )) != NULL) return STATUS_SUCCESS;
1374 *handle = pCreateFileW( filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0 );
1375 return STATUS_SUCCESS;
1377 overflow:
1378 *size = len + sizeof(WCHAR);
1379 return STATUS_BUFFER_TOO_SMALL;
1383 /***********************************************************************
1384 * load_dll (internal)
1386 * Load a PE style module according to the load order.
1387 * The loader_section must be locked while calling this function.
1389 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
1391 int i;
1392 enum loadorder_type loadorder[LOADORDER_NTYPES];
1393 WCHAR buffer[32];
1394 WCHAR *filename;
1395 ULONG size;
1396 const char *filetype = "";
1397 WINE_MODREF *main_exe;
1398 HANDLE handle = INVALID_HANDLE_VALUE;
1399 NTSTATUS nts;
1401 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
1403 filename = buffer;
1404 size = sizeof(buffer);
1405 for (;;)
1407 nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
1408 if (nts == STATUS_SUCCESS) break;
1409 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1410 if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
1411 /* grow the buffer and retry */
1412 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
1415 if (*pwm) /* found already loaded module */
1417 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
1419 if (((*pwm)->ldr.Flags & LDR_DONT_RESOLVE_REFS) &&
1420 !(flags & DONT_RESOLVE_DLL_REFERENCES))
1422 (*pwm)->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
1423 fixup_imports( *pwm, load_path );
1425 TRACE("Found loaded module %s for %s at %p, count=%d\n",
1426 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
1427 (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
1428 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1429 return STATUS_SUCCESS;
1432 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
1433 MODULE_GetLoadOrderW( loadorder, main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
1435 nts = STATUS_DLL_NOT_FOUND;
1436 for (i = 0; i < LOADORDER_NTYPES; i++)
1438 if (loadorder[i] == LOADORDER_INVALID) break;
1440 switch (loadorder[i])
1442 case LOADORDER_DLL:
1443 TRACE("Trying native dll %s\n", debugstr_w(filename));
1444 if (handle == INVALID_HANDLE_VALUE) continue; /* it cannot possibly be loaded */
1445 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1446 filetype = "native";
1447 break;
1448 case LOADORDER_BI:
1449 TRACE("Trying built-in %s\n", debugstr_w(filename));
1450 nts = load_builtin_dll( load_path, filename, flags, pwm );
1451 filetype = "builtin";
1452 break;
1453 default:
1454 nts = STATUS_INTERNAL_ERROR;
1455 break;
1458 if (nts == STATUS_SUCCESS)
1460 /* Initialize DLL just loaded */
1461 TRACE("Loaded module %s (%s) at %p\n",
1462 debugstr_w(filename), filetype, (*pwm)->ldr.BaseAddress);
1463 if (!TRACE_ON(module))
1464 TRACE_(loaddll)("Loaded module %s : %s\n", debugstr_w(filename), filetype);
1465 /* Set the ldr.LoadCount here so that an attach failure will */
1466 /* decrement the dependencies through the MODULE_FreeLibrary call. */
1467 (*pwm)->ldr.LoadCount = 1;
1468 if (handle != INVALID_HANDLE_VALUE) NtClose( handle );
1469 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1470 return nts;
1472 if (nts != STATUS_DLL_NOT_FOUND) break;
1475 WARN("Failed to load module %s; status=%lx\n", debugstr_w(libname), nts);
1476 if (handle != INVALID_HANDLE_VALUE) NtClose( handle );
1477 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1478 return nts;
1481 /******************************************************************
1482 * LdrLoadDll (NTDLL.@)
1484 NTSTATUS WINAPI LdrLoadDll(LPCWSTR path_name, DWORD flags,
1485 const UNICODE_STRING *libname, HMODULE* hModule)
1487 WINE_MODREF *wm;
1488 NTSTATUS nts;
1490 RtlEnterCriticalSection( &loader_section );
1492 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1493 nts = load_dll( path_name, libname->Buffer, flags, &wm );
1495 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
1497 nts = process_attach( wm, NULL );
1498 if (nts != STATUS_SUCCESS)
1500 WARN("Attach failed for module %s\n", debugstr_w(libname->Buffer));
1501 LdrUnloadDll(wm->ldr.BaseAddress);
1502 wm = NULL;
1505 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
1507 RtlLeaveCriticalSection( &loader_section );
1508 return nts;
1511 /******************************************************************
1512 * LdrQueryProcessModuleInformation
1515 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
1516 ULONG buf_size, ULONG* req_size)
1518 SYSTEM_MODULE* sm = &smi->Modules[0];
1519 ULONG size = sizeof(ULONG);
1520 NTSTATUS nts = STATUS_SUCCESS;
1521 ANSI_STRING str;
1522 char* ptr;
1523 PLIST_ENTRY mark, entry;
1524 PLDR_MODULE mod;
1526 smi->ModulesCount = 0;
1528 RtlEnterCriticalSection( &loader_section );
1529 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1530 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1532 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1533 size += sizeof(*sm);
1534 if (size <= buf_size)
1536 sm->Reserved1 = 0; /* FIXME */
1537 sm->Reserved2 = 0; /* FIXME */
1538 sm->ImageBaseAddress = mod->BaseAddress;
1539 sm->ImageSize = mod->SizeOfImage;
1540 sm->Flags = mod->Flags;
1541 sm->Id = 0; /* FIXME */
1542 sm->Rank = 0; /* FIXME */
1543 sm->Unknown = 0; /* FIXME */
1544 str.Length = 0;
1545 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
1546 str.Buffer = sm->Name;
1547 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
1548 ptr = strrchr(sm->Name, '\\');
1549 sm->NameOffset = (ptr != NULL) ? (ptr - (char*)sm->Name + 1) : 0;
1551 smi->ModulesCount++;
1552 sm++;
1554 else nts = STATUS_INFO_LENGTH_MISMATCH;
1556 RtlLeaveCriticalSection( &loader_section );
1558 if (req_size) *req_size = size;
1560 return nts;
1563 /******************************************************************
1564 * LdrShutdownProcess (NTDLL.@)
1567 void WINAPI LdrShutdownProcess(void)
1569 TRACE("()\n");
1570 process_detach( TRUE, (LPVOID)1 );
1573 /******************************************************************
1574 * LdrShutdownThread (NTDLL.@)
1577 void WINAPI LdrShutdownThread(void)
1579 PLIST_ENTRY mark, entry;
1580 PLDR_MODULE mod;
1582 TRACE("()\n");
1584 /* don't do any detach calls if process is exiting */
1585 if (process_detaching) return;
1586 /* FIXME: there is still a race here */
1588 RtlEnterCriticalSection( &loader_section );
1590 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1591 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1593 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1594 InInitializationOrderModuleList);
1595 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1596 continue;
1597 if ( mod->Flags & LDR_NO_DLL_CALLS )
1598 continue;
1600 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1601 DLL_THREAD_DETACH, NULL );
1604 RtlLeaveCriticalSection( &loader_section );
1607 /***********************************************************************
1608 * MODULE_FlushModrefs
1610 * Remove all unused modrefs and call the internal unloading routines
1611 * for the library type.
1613 * The loader_section must be locked while calling this function.
1615 static void MODULE_FlushModrefs(void)
1617 PLIST_ENTRY mark, entry, prev;
1618 PLDR_MODULE mod;
1619 WINE_MODREF*wm;
1621 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1622 for (entry = mark->Blink; entry != mark; entry = prev)
1624 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1625 InInitializationOrderModuleList);
1626 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1628 prev = entry->Blink;
1629 if (mod->LoadCount) continue;
1631 RemoveEntryList(&mod->InLoadOrderModuleList);
1632 RemoveEntryList(&mod->InMemoryOrderModuleList);
1633 RemoveEntryList(&mod->InInitializationOrderModuleList);
1635 TRACE(" unloading %s\n", debugstr_w(mod->FullDllName.Buffer));
1636 if (!TRACE_ON(module))
1637 TRACE_(loaddll)("Unloaded module %s : %s\n",
1638 debugstr_w(mod->FullDllName.Buffer),
1639 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
1641 SERVER_START_REQ( unload_dll )
1643 req->base = mod->BaseAddress;
1644 wine_server_call( req );
1646 SERVER_END_REQ;
1648 if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
1649 NtUnmapViewOfSection( GetCurrentProcess(), mod->BaseAddress );
1650 if (cached_modref == wm) cached_modref = NULL;
1651 RtlFreeUnicodeString( &mod->FullDllName );
1652 RtlFreeHeap( ntdll_get_process_heap(), 0, wm->deps );
1653 RtlFreeHeap( ntdll_get_process_heap(), 0, wm );
1657 /***********************************************************************
1658 * MODULE_DecRefCount
1660 * The loader_section must be locked while calling this function.
1662 static void MODULE_DecRefCount( WINE_MODREF *wm )
1664 int i;
1666 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
1667 return;
1669 if ( wm->ldr.LoadCount <= 0 )
1670 return;
1672 --wm->ldr.LoadCount;
1673 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
1675 if ( wm->ldr.LoadCount == 0 )
1677 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
1679 for ( i = 0; i < wm->nDeps; i++ )
1680 if ( wm->deps[i] )
1681 MODULE_DecRefCount( wm->deps[i] );
1683 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
1687 /******************************************************************
1688 * LdrUnloadDll (NTDLL.@)
1692 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
1694 NTSTATUS retv = STATUS_SUCCESS;
1696 TRACE("(%p)\n", hModule);
1698 RtlEnterCriticalSection( &loader_section );
1700 /* if we're stopping the whole process (and forcing the removal of all
1701 * DLLs) the library will be freed anyway
1703 if (!process_detaching)
1705 WINE_MODREF *wm;
1707 free_lib_count++;
1708 if ((wm = get_modref( hModule )) != NULL)
1710 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
1712 /* Recursively decrement reference counts */
1713 MODULE_DecRefCount( wm );
1715 /* Call process detach notifications */
1716 if ( free_lib_count <= 1 )
1718 process_detach( FALSE, NULL );
1719 MODULE_FlushModrefs();
1722 TRACE("END\n");
1724 else
1725 retv = STATUS_DLL_NOT_FOUND;
1727 free_lib_count--;
1730 RtlLeaveCriticalSection( &loader_section );
1732 return retv;
1735 /***********************************************************************
1736 * RtlImageNtHeader (NTDLL.@)
1738 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
1740 IMAGE_NT_HEADERS *ret;
1742 __TRY
1744 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
1746 ret = NULL;
1747 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
1749 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
1750 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
1753 __EXCEPT(page_fault)
1755 return NULL;
1757 __ENDTRY
1758 return ret;
1762 /******************************************************************
1763 * init_system_dir
1765 * System dir initialization once kernel32 has been loaded.
1767 static inline void init_system_dir(void)
1769 PLIST_ENTRY mark, entry;
1770 LPWSTR buffer, p;
1772 if (!MODULE_GetSystemDirectory( &system_dir ))
1774 ERR( "Couldn't get system dir\n");
1775 exit(1);
1778 /* prepend the system dir to the name of the already created modules */
1779 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1780 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1782 LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
1784 assert( mod->Flags & LDR_WINE_INTERNAL );
1786 buffer = RtlAllocateHeap( GetProcessHeap(), 0,
1787 system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
1788 if (!buffer) continue;
1789 strcpyW( buffer, system_dir.Buffer );
1790 p = buffer + strlenW( buffer );
1791 if (p > buffer && p[-1] != '\\') *p++ = '\\';
1792 strcpyW( p, mod->FullDllName.Buffer );
1793 RtlInitUnicodeString( &mod->FullDllName, buffer );
1794 RtlInitUnicodeString( &mod->BaseDllName, p );
1799 /******************************************************************
1800 * LdrInitializeThunk (NTDLL.@)
1802 * FIXME: the arguments are not correct, main_file is a Wine invention.
1804 void WINAPI LdrInitializeThunk( HANDLE main_file, ULONG unknown2, ULONG unknown3, ULONG unknown4 )
1806 NTSTATUS status;
1807 WINE_MODREF *wm;
1808 LPCWSTR load_path;
1809 PEB *peb = NtCurrentTeb()->Peb;
1810 UNICODE_STRING *main_exe_name = &peb->ProcessParameters->ImagePathName;
1811 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
1813 init_system_dir();
1815 /* allocate the modref for the main exe */
1816 if (!(wm = alloc_module( peb->ImageBaseAddress, main_exe_name->Buffer )))
1818 status = STATUS_NO_MEMORY;
1819 goto error;
1821 wm->ldr.LoadCount = -1; /* can't unload main exe */
1823 /* the main exe needs to be the first in the load order list */
1824 RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
1825 InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
1827 /* Install signal handlers; this cannot be done before, since we cannot
1828 * send exceptions to the debugger before the create process event that
1829 * is sent by REQ_INIT_PROCESS_DONE.
1830 * We do need the handlers in place by the time the request is over, so
1831 * we set them up here. If we segfault between here and the server call
1832 * something is very wrong... */
1833 if (!SIGNAL_Init()) exit(1);
1835 /* Signal the parent process to continue */
1836 SERVER_START_REQ( init_process_done )
1838 req->module = peb->ImageBaseAddress;
1839 req->module_size = wm->ldr.SizeOfImage;
1840 req->entry = (char *)peb->ImageBaseAddress + nt->OptionalHeader.AddressOfEntryPoint;
1841 /* API requires a double indirection */
1842 req->name = &main_exe_name->Buffer;
1843 req->exe_file = main_file;
1844 req->gui = (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_WINDOWS_CUI);
1845 wine_server_add_data( req, main_exe_name->Buffer, main_exe_name->Length );
1846 wine_server_call( req );
1848 SERVER_END_REQ;
1850 if (main_file) NtClose( main_file ); /* we no longer need it */
1852 if (TRACE_ON(relay) || TRACE_ON(snoop))
1854 RELAY_InitDebugLists();
1856 if (TRACE_ON(relay)) /* setup relay for already loaded dlls */
1858 LIST_ENTRY *entry, *mark = &peb->LdrData->InLoadOrderModuleList;
1859 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1861 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1862 if (mod->Flags & LDR_WINE_INTERNAL) RELAY_SetupDLL( mod->BaseAddress );
1867 RtlEnterCriticalSection( &loader_section );
1869 load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1870 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
1871 if ((status = alloc_process_tls()) != STATUS_SUCCESS) goto error;
1872 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto error;
1873 if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS) goto error;
1875 RtlLeaveCriticalSection( &loader_section );
1876 return;
1878 error:
1879 ERR( "Main exe initialization for %s failed, status %lx\n", debugstr_w(main_exe_name->Buffer), status );
1880 exit(1);
1884 /***********************************************************************
1885 * RtlImageDirectoryEntryToData (NTDLL.@)
1887 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
1889 const IMAGE_NT_HEADERS *nt;
1890 DWORD addr;
1892 if ((ULONG_PTR)module & 1) /* mapped as data file */
1894 module = (HMODULE)((ULONG_PTR)module & ~1);
1895 image = FALSE;
1897 if (!(nt = RtlImageNtHeader( module ))) return NULL;
1898 if (dir >= nt->OptionalHeader.NumberOfRvaAndSizes) return NULL;
1899 if (!(addr = nt->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
1900 *size = nt->OptionalHeader.DataDirectory[dir].Size;
1901 if (image || addr < nt->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
1903 /* not mapped as image, need to find the section containing the virtual address */
1904 return RtlImageRvaToVa( nt, module, addr, NULL );
1908 /***********************************************************************
1909 * RtlImageRvaToSection (NTDLL.@)
1911 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
1912 HMODULE module, DWORD rva )
1914 int i;
1915 IMAGE_SECTION_HEADER *sec = (IMAGE_SECTION_HEADER*)((char*)&nt->OptionalHeader +
1916 nt->FileHeader.SizeOfOptionalHeader);
1917 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
1919 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
1920 return sec;
1922 return NULL;
1926 /***********************************************************************
1927 * RtlImageRvaToVa (NTDLL.@)
1929 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
1930 DWORD rva, IMAGE_SECTION_HEADER **section )
1932 IMAGE_SECTION_HEADER *sec;
1934 if (section && *section) /* try this section first */
1936 sec = *section;
1937 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
1938 goto found;
1940 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
1941 found:
1942 if (section) *section = sec;
1943 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
1947 /***********************************************************************
1948 * __wine_process_init
1950 void __wine_process_init( int argc, char *argv[] )
1952 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
1954 WINE_MODREF *wm;
1955 NTSTATUS status;
1956 ANSI_STRING func_name;
1957 void (* DECLSPEC_NORETURN init_func)();
1958 extern void __wine_dbg_ntdll_init(void);
1960 thread_init();
1961 __wine_dbg_ntdll_init(); /* hack: register debug channels early */
1963 /* setup the load callback and create ntdll modref */
1964 wine_dll_set_callback( load_builtin_callback );
1966 if ((status = load_builtin_dll( NULL, kernel32W, 0, &wm )) != STATUS_SUCCESS)
1968 MESSAGE( "wine: could not load kernel32.dll, status %lx\n", status );
1969 exit(1);
1971 RtlInitAnsiString( &func_name, "__wine_kernel_init" );
1972 if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
1973 0, (void **)&init_func )) != STATUS_SUCCESS)
1975 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %lx\n", status );
1976 exit(1);
1978 RtlInitAnsiString( &func_name, "CreateFileW" );
1979 if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
1980 0, (void **)&pCreateFileW )) != STATUS_SUCCESS)
1982 MESSAGE( "wine: could not find CreateFileW in kernel32.dll, status %lx\n", status );
1983 exit(1);
1985 init_func();