winepulse: API Compatibility with 1.5.2 onward, v2
[wine/multimedia.git] / dlls / ntdll / loader.c
blob5dc79110658c0cb02e51dbb7f41be3d5abcee653
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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
22 #include "config.h"
23 #include "wine/port.h"
25 #include <assert.h>
26 #include <stdarg.h>
27 #ifdef HAVE_SYS_MMAN_H
28 # include <sys/mman.h>
29 #endif
31 #define NONAMELESSUNION
32 #define NONAMELESSSTRUCT
34 #include "ntstatus.h"
35 #define WIN32_NO_STATUS
36 #include "windef.h"
37 #include "winnt.h"
38 #include "winternl.h"
40 #include "wine/exception.h"
41 #include "wine/library.h"
42 #include "wine/unicode.h"
43 #include "wine/debug.h"
44 #include "wine/server.h"
45 #include "ntdll_misc.h"
46 #include "ddk/wdm.h"
48 WINE_DEFAULT_DEBUG_CHANNEL(module);
49 WINE_DECLARE_DEBUG_CHANNEL(relay);
50 WINE_DECLARE_DEBUG_CHANNEL(snoop);
51 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
52 WINE_DECLARE_DEBUG_CHANNEL(imports);
54 /* we don't want to include winuser.h */
55 #define RT_MANIFEST ((ULONG_PTR)24)
56 #define ISOLATIONAWARE_MANIFEST_RESOURCE_ID ((ULONG_PTR)2)
58 typedef DWORD (CALLBACK *DLLENTRYPROC)(HMODULE,DWORD,LPVOID);
60 static int process_detaching = 0; /* set on process detach to avoid deadlocks with thread detach */
61 static int free_lib_count; /* recursion depth of LdrUnloadDll calls */
63 static const char * const reason_names[] =
65 "PROCESS_DETACH",
66 "PROCESS_ATTACH",
67 "THREAD_ATTACH",
68 "THREAD_DETACH",
69 NULL, NULL, NULL, NULL,
70 "WINE_PREATTACH"
73 static const WCHAR dllW[] = {'.','d','l','l',0};
75 /* internal representation of 32bit modules. per process. */
76 typedef struct _wine_modref
78 LDR_MODULE ldr;
79 int nDeps;
80 struct _wine_modref **deps;
81 } WINE_MODREF;
83 /* info about the current builtin dll load */
84 /* used to keep track of things across the register_dll constructor call */
85 struct builtin_load_info
87 const WCHAR *load_path;
88 const WCHAR *filename;
89 NTSTATUS status;
90 WINE_MODREF *wm;
93 static struct builtin_load_info default_load_info;
94 static struct builtin_load_info *builtin_load_info = &default_load_info;
96 static HANDLE main_exe_file;
97 static UINT tls_module_count; /* number of modules with TLS directory */
98 static UINT tls_total_size; /* total size of TLS storage */
99 static const IMAGE_TLS_DIRECTORY **tls_dirs; /* array of TLS directories */
100 #define TLS_ALIGNMENT (2 * sizeof(void *))
101 #define TLS_ALIGN(size) (((size) + TLS_ALIGNMENT - 1) & ~(TLS_ALIGNMENT - 1))
103 static RTL_CRITICAL_SECTION loader_section;
104 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
106 0, 0, &loader_section,
107 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
108 0, 0, { (DWORD_PTR)(__FILE__ ": loader_section") }
110 static RTL_CRITICAL_SECTION loader_section = { &critsect_debug, -1, 0, 0, 0, 0 };
112 static WINE_MODREF *cached_modref;
113 static WINE_MODREF *current_modref;
114 static WINE_MODREF *last_failed_modref;
116 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm );
117 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved );
118 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
119 DWORD exp_size, DWORD ordinal, LPCWSTR load_path );
120 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
121 DWORD exp_size, const char *name, int hint, LPCWSTR load_path );
123 /* convert PE image VirtualAddress to Real Address */
124 static inline void *get_rva( HMODULE module, DWORD va )
126 return (void *)((char *)module + va);
129 /* check whether the file name contains a path */
130 static inline int contains_path( LPCWSTR name )
132 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
135 /* convert from straight ASCII to Unicode without depending on the current codepage */
136 static inline void ascii_to_unicode( WCHAR *dst, const char *src, size_t len )
138 while (len--) *dst++ = (unsigned char)*src++;
142 /*************************************************************************
143 * call_dll_entry_point
145 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
146 * their entry point, so we need a small asm wrapper.
148 #ifdef __i386__
149 extern BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module, UINT reason, void *reserved );
150 __ASM_GLOBAL_FUNC(call_dll_entry_point,
151 "pushl %ebp\n\t"
152 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
153 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
154 "movl %esp,%ebp\n\t"
155 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
156 "pushl %ebx\n\t"
157 __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
158 "subl $8,%esp\n\t"
159 "pushl 20(%ebp)\n\t"
160 "pushl 16(%ebp)\n\t"
161 "pushl 12(%ebp)\n\t"
162 "movl 8(%ebp),%eax\n\t"
163 "call *%eax\n\t"
164 "leal -4(%ebp),%esp\n\t"
165 "popl %ebx\n\t"
166 __ASM_CFI(".cfi_same_value %ebx\n\t")
167 "popl %ebp\n\t"
168 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
169 __ASM_CFI(".cfi_same_value %ebp\n\t")
170 "ret" )
171 #else /* __i386__ */
172 static inline BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module,
173 UINT reason, void *reserved )
175 return proc( module, reason, reserved );
177 #endif /* __i386__ */
180 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__)
181 /*************************************************************************
182 * stub_entry_point
184 * Entry point for stub functions.
186 static void stub_entry_point( const char *dll, const char *name, void *ret_addr )
188 EXCEPTION_RECORD rec;
190 rec.ExceptionCode = EXCEPTION_WINE_STUB;
191 rec.ExceptionFlags = EH_NONCONTINUABLE;
192 rec.ExceptionRecord = NULL;
193 rec.ExceptionAddress = ret_addr;
194 rec.NumberParameters = 2;
195 rec.ExceptionInformation[0] = (ULONG_PTR)dll;
196 rec.ExceptionInformation[1] = (ULONG_PTR)name;
197 for (;;) RtlRaiseException( &rec );
201 #include "pshpack1.h"
202 #ifdef __i386__
203 struct stub
205 BYTE pushl1; /* pushl $name */
206 const char *name;
207 BYTE pushl2; /* pushl $dll */
208 const char *dll;
209 BYTE call; /* call stub_entry_point */
210 DWORD entry;
212 #elif defined(__arm__)
213 struct stub
215 BYTE ldr_r0[4]; /* ldr r0, $dll */
216 BYTE mov_pc_pc1[4]; /* mov pc,pc */
217 const char *dll;
218 BYTE ldr_r1[4]; /* ldr r1, $name */
219 BYTE mov_pc_pc2[4]; /* mov pc,pc */
220 const char *name;
221 BYTE mov_r2_lr[4]; /* mov r2, lr */
222 BYTE ldr_pc_pc[4]; /* ldr pc, [pc, #-4] */
223 const void* entry;
225 #else
226 struct stub
228 BYTE movq_rdi[2]; /* movq $dll,%rdi */
229 const char *dll;
230 BYTE movq_rsi[2]; /* movq $name,%rsi */
231 const char *name;
232 BYTE movq_rsp_rdx[4]; /* movq (%rsp),%rdx */
233 BYTE movq_rax[2]; /* movq $entry, %rax */
234 const void* entry;
235 BYTE jmpq_rax[2]; /* jmp %rax */
237 #endif
238 #include "poppack.h"
240 /*************************************************************************
241 * allocate_stub
243 * Allocate a stub entry point.
245 static ULONG_PTR allocate_stub( const char *dll, const char *name )
247 #define MAX_SIZE 65536
248 static struct stub *stubs;
249 static unsigned int nb_stubs;
250 struct stub *stub;
252 if (nb_stubs >= MAX_SIZE / sizeof(*stub)) return 0xdeadbeef;
254 if (!stubs)
256 SIZE_T size = MAX_SIZE;
257 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs, 0, &size,
258 MEM_COMMIT, PAGE_EXECUTE_READWRITE ) != STATUS_SUCCESS)
259 return 0xdeadbeef;
261 stub = &stubs[nb_stubs++];
262 #ifdef __i386__
263 stub->pushl1 = 0x68; /* pushl $name */
264 stub->name = name;
265 stub->pushl2 = 0x68; /* pushl $dll */
266 stub->dll = dll;
267 stub->call = 0xe8; /* call stub_entry_point */
268 stub->entry = (BYTE *)stub_entry_point - (BYTE *)(&stub->entry + 1);
269 #elif defined(__arm__)
270 stub->ldr_r0[0] = 0x00; /* ldr r0, $dll */
271 stub->ldr_r0[1] = 0x00;
272 stub->ldr_r0[2] = 0x9f;
273 stub->ldr_r0[3] = 0xe5;
274 stub->mov_pc_pc1[0] = 0x0f; /* mov pc,pc */
275 stub->mov_pc_pc1[1] = 0xf0;
276 stub->mov_pc_pc1[2] = 0xa0;
277 stub->mov_pc_pc1[3] = 0xe1;
278 stub->dll = dll;
279 stub->ldr_r1[0] = 0x00; /* ldr r1, $name */
280 stub->ldr_r1[1] = 0x10;
281 stub->ldr_r1[2] = 0x9f;
282 stub->ldr_r1[3] = 0xe5;
283 stub->mov_pc_pc2[0] = 0x0f; /* mov pc,pc */
284 stub->mov_pc_pc2[1] = 0xf0;
285 stub->mov_pc_pc2[2] = 0xa0;
286 stub->mov_pc_pc2[3] = 0xe1;
287 stub->name = name;
288 stub->mov_r2_lr[0] = 0x0e; /* mov r2, lr */
289 stub->mov_r2_lr[1] = 0x20;
290 stub->mov_r2_lr[2] = 0xa0;
291 stub->mov_r2_lr[3] = 0xe1;
292 stub->ldr_pc_pc[0] = 0x04; /* ldr pc, [pc, #-4] */
293 stub->ldr_pc_pc[1] = 0xf0;
294 stub->ldr_pc_pc[2] = 0x1f;
295 stub->ldr_pc_pc[3] = 0xe5;
296 stub->entry = stub_entry_point;
297 #else
298 stub->movq_rdi[0] = 0x48; /* movq $dll,%rdi */
299 stub->movq_rdi[1] = 0xbf;
300 stub->dll = dll;
301 stub->movq_rsi[0] = 0x48; /* movq $name,%rsi */
302 stub->movq_rsi[1] = 0xbe;
303 stub->name = name;
304 stub->movq_rsp_rdx[0] = 0x48; /* movq (%rsp),%rdx */
305 stub->movq_rsp_rdx[1] = 0x8b;
306 stub->movq_rsp_rdx[2] = 0x14;
307 stub->movq_rsp_rdx[3] = 0x24;
308 stub->movq_rax[0] = 0x48; /* movq $entry, %rax */
309 stub->movq_rax[1] = 0xb8;
310 stub->entry = stub_entry_point;
311 stub->jmpq_rax[0] = 0xff; /* jmp %rax */
312 stub->jmpq_rax[1] = 0xe0;
313 #endif
314 return (ULONG_PTR)stub;
317 #else /* __i386__ */
318 static inline ULONG_PTR allocate_stub( const char *dll, const char *name ) { return 0xdeadbeef; }
319 #endif /* __i386__ */
322 /*************************************************************************
323 * get_modref
325 * Looks for the referenced HMODULE in the current process
326 * The loader_section must be locked while calling this function.
328 static WINE_MODREF *get_modref( HMODULE hmod )
330 PLIST_ENTRY mark, entry;
331 PLDR_MODULE mod;
333 if (cached_modref && cached_modref->ldr.BaseAddress == hmod) return cached_modref;
335 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
336 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
338 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
339 if (mod->BaseAddress == hmod)
340 return cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
341 if (mod->BaseAddress > (void*)hmod) break;
343 return NULL;
347 /**********************************************************************
348 * find_basename_module
350 * Find a module from its base name.
351 * The loader_section must be locked while calling this function
353 static WINE_MODREF *find_basename_module( LPCWSTR name )
355 PLIST_ENTRY mark, entry;
357 if (cached_modref && !strcmpiW( name, cached_modref->ldr.BaseDllName.Buffer ))
358 return cached_modref;
360 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
361 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
363 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
364 if (!strcmpiW( name, mod->BaseDllName.Buffer ))
366 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
367 return cached_modref;
370 return NULL;
374 /**********************************************************************
375 * find_fullname_module
377 * Find a module from its full path name.
378 * The loader_section must be locked while calling this function
380 static WINE_MODREF *find_fullname_module( LPCWSTR name )
382 PLIST_ENTRY mark, entry;
384 if (cached_modref && !strcmpiW( name, cached_modref->ldr.FullDllName.Buffer ))
385 return cached_modref;
387 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
388 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
390 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
391 if (!strcmpiW( name, mod->FullDllName.Buffer ))
393 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
394 return cached_modref;
397 return NULL;
401 /*************************************************************************
402 * find_forwarded_export
404 * Find the final function pointer for a forwarded function.
405 * The loader_section must be locked while calling this function.
407 static FARPROC find_forwarded_export( HMODULE module, const char *forward, LPCWSTR load_path )
409 const IMAGE_EXPORT_DIRECTORY *exports;
410 DWORD exp_size;
411 WINE_MODREF *wm;
412 WCHAR mod_name[32];
413 const char *end = strrchr(forward, '.');
414 FARPROC proc = NULL;
416 if (!end) return NULL;
417 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name)) return NULL;
418 ascii_to_unicode( mod_name, forward, end - forward );
419 mod_name[end - forward] = 0;
420 if (!strchrW( mod_name, '.' ))
422 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name) - sizeof(dllW)) return NULL;
423 memcpy( mod_name + (end - forward), dllW, sizeof(dllW) );
426 if (!(wm = find_basename_module( mod_name )))
428 TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name), forward );
429 if (load_dll( load_path, mod_name, 0, &wm ) == STATUS_SUCCESS &&
430 !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
432 if (process_attach( wm, NULL ) != STATUS_SUCCESS)
434 LdrUnloadDll( wm->ldr.BaseAddress );
435 wm = NULL;
439 if (!wm)
441 ERR( "module not found for forward '%s' used by %s\n",
442 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer) );
443 return NULL;
446 if ((exports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
447 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
449 const char *name = end + 1;
450 if (*name == '#') /* ordinal */
451 proc = find_ordinal_export( wm->ldr.BaseAddress, exports, exp_size, atoi(name+1), load_path );
452 else
453 proc = find_named_export( wm->ldr.BaseAddress, exports, exp_size, name, -1, load_path );
456 if (!proc)
458 ERR("function not found for forward '%s' used by %s."
459 " If you are using builtin %s, try using the native one instead.\n",
460 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer),
461 debugstr_w(get_modref(module)->ldr.BaseDllName.Buffer) );
463 return proc;
467 /*************************************************************************
468 * find_ordinal_export
470 * Find an exported function by ordinal.
471 * The exports base must have been subtracted from the ordinal already.
472 * The loader_section must be locked while calling this function.
474 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
475 DWORD exp_size, DWORD ordinal, LPCWSTR load_path )
477 FARPROC proc;
478 const DWORD *functions = get_rva( module, exports->AddressOfFunctions );
480 if (ordinal >= exports->NumberOfFunctions)
482 TRACE(" ordinal %d out of range!\n", ordinal + exports->Base );
483 return NULL;
485 if (!functions[ordinal]) return NULL;
487 proc = get_rva( module, functions[ordinal] );
489 /* if the address falls into the export dir, it's a forward */
490 if (((const char *)proc >= (const char *)exports) &&
491 ((const char *)proc < (const char *)exports + exp_size))
492 return find_forwarded_export( module, (const char *)proc, load_path );
494 if (TRACE_ON(snoop))
496 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
497 proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
499 if (TRACE_ON(relay))
501 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
502 proc = RELAY_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
504 return proc;
508 /*************************************************************************
509 * find_named_export
511 * Find an exported function by name.
512 * The loader_section must be locked while calling this function.
514 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
515 DWORD exp_size, const char *name, int hint, LPCWSTR load_path )
517 const WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
518 const DWORD *names = get_rva( module, exports->AddressOfNames );
519 int min = 0, max = exports->NumberOfNames - 1;
521 /* first check the hint */
522 if (hint >= 0 && hint <= max)
524 char *ename = get_rva( module, names[hint] );
525 if (!strcmp( ename, name ))
526 return find_ordinal_export( module, exports, exp_size, ordinals[hint], load_path );
529 /* then do a binary search */
530 while (min <= max)
532 int res, pos = (min + max) / 2;
533 char *ename = get_rva( module, names[pos] );
534 if (!(res = strcmp( ename, name )))
535 return find_ordinal_export( module, exports, exp_size, ordinals[pos], load_path );
536 if (res > 0) max = pos - 1;
537 else min = pos + 1;
539 return NULL;
544 /*************************************************************************
545 * import_dll
547 * Import the dll specified by the given import descriptor.
548 * The loader_section must be locked while calling this function.
550 static WINE_MODREF *import_dll( HMODULE module, const IMAGE_IMPORT_DESCRIPTOR *descr, LPCWSTR load_path )
552 NTSTATUS status;
553 WINE_MODREF *wmImp;
554 HMODULE imp_mod;
555 const IMAGE_EXPORT_DIRECTORY *exports;
556 DWORD exp_size;
557 const IMAGE_THUNK_DATA *import_list;
558 IMAGE_THUNK_DATA *thunk_list;
559 WCHAR buffer[32];
560 const char *name = get_rva( module, descr->Name );
561 DWORD len = strlen(name);
562 PVOID protect_base;
563 SIZE_T protect_size = 0;
564 DWORD protect_old;
566 thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
567 if (descr->u.OriginalFirstThunk)
568 import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
569 else
570 import_list = thunk_list;
572 while (len && name[len-1] == ' ') len--; /* remove trailing spaces */
574 if (len * sizeof(WCHAR) < sizeof(buffer))
576 ascii_to_unicode( buffer, name, len );
577 buffer[len] = 0;
578 status = load_dll( load_path, buffer, 0, &wmImp );
580 else /* need to allocate a larger buffer */
582 WCHAR *ptr = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
583 if (!ptr) return NULL;
584 ascii_to_unicode( ptr, name, len );
585 ptr[len] = 0;
586 status = load_dll( load_path, ptr, 0, &wmImp );
587 RtlFreeHeap( GetProcessHeap(), 0, ptr );
590 if (status)
592 if (status == STATUS_DLL_NOT_FOUND)
593 ERR("Library %s (which is needed by %s) not found\n",
594 name, debugstr_w(current_modref->ldr.FullDllName.Buffer));
595 else
596 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
597 name, debugstr_w(current_modref->ldr.FullDllName.Buffer), status);
598 return NULL;
601 /* unprotect the import address table since it can be located in
602 * readonly section */
603 while (import_list[protect_size].u1.Ordinal) protect_size++;
604 protect_base = thunk_list;
605 protect_size *= sizeof(*thunk_list);
606 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base,
607 &protect_size, PAGE_READWRITE, &protect_old );
609 imp_mod = wmImp->ldr.BaseAddress;
610 exports = RtlImageDirectoryEntryToData( imp_mod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
612 if (!exports)
614 /* set all imported function to deadbeef */
615 while (import_list->u1.Ordinal)
617 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
619 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
620 WARN("No implementation for %s.%d", name, ordinal );
621 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
623 else
625 IMAGE_IMPORT_BY_NAME *pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
626 WARN("No implementation for %s.%s", name, pe_name->Name );
627 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
629 WARN(" imported from %s, allocating stub %p\n",
630 debugstr_w(current_modref->ldr.FullDllName.Buffer),
631 (void *)thunk_list->u1.Function );
632 import_list++;
633 thunk_list++;
635 goto done;
638 while (import_list->u1.Ordinal)
640 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
642 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
644 thunk_list->u1.Function = (ULONG_PTR)find_ordinal_export( imp_mod, exports, exp_size,
645 ordinal - exports->Base, load_path );
646 if (!thunk_list->u1.Function)
648 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
649 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
650 name, ordinal, debugstr_w(current_modref->ldr.FullDllName.Buffer),
651 (void *)thunk_list->u1.Function );
653 TRACE_(imports)("--- Ordinal %s.%d = %p\n", name, ordinal, (void *)thunk_list->u1.Function );
655 else /* import by name */
657 IMAGE_IMPORT_BY_NAME *pe_name;
658 pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
659 thunk_list->u1.Function = (ULONG_PTR)find_named_export( imp_mod, exports, exp_size,
660 (const char*)pe_name->Name,
661 pe_name->Hint, load_path );
662 if (!thunk_list->u1.Function)
664 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
665 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
666 name, pe_name->Name, debugstr_w(current_modref->ldr.FullDllName.Buffer),
667 (void *)thunk_list->u1.Function );
669 TRACE_(imports)("--- %s %s.%d = %p\n",
670 pe_name->Name, name, pe_name->Hint, (void *)thunk_list->u1.Function);
672 import_list++;
673 thunk_list++;
676 done:
677 /* restore old protection of the import address table */
678 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base, &protect_size, protect_old, NULL );
679 return wmImp;
683 /***********************************************************************
684 * create_module_activation_context
686 static NTSTATUS create_module_activation_context( LDR_MODULE *module )
688 NTSTATUS status;
689 LDR_RESOURCE_INFO info;
690 const IMAGE_RESOURCE_DATA_ENTRY *entry;
692 info.Type = RT_MANIFEST;
693 info.Name = ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
694 info.Language = 0;
695 if (!(status = LdrFindResource_U( module->BaseAddress, &info, 3, &entry )))
697 ACTCTXW ctx;
698 ctx.cbSize = sizeof(ctx);
699 ctx.lpSource = NULL;
700 ctx.dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID | ACTCTX_FLAG_HMODULE_VALID;
701 ctx.hModule = module->BaseAddress;
702 ctx.lpResourceName = (LPCWSTR)ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
703 status = RtlCreateActivationContext( &module->ActivationContext, &ctx );
705 return status;
709 /****************************************************************
710 * fixup_imports
712 * Fixup all imports of a given module.
713 * The loader_section must be locked while calling this function.
715 static NTSTATUS fixup_imports( WINE_MODREF *wm, LPCWSTR load_path )
717 int i, nb_imports;
718 const IMAGE_IMPORT_DESCRIPTOR *imports;
719 WINE_MODREF *prev;
720 DWORD size;
721 NTSTATUS status;
722 ULONG_PTR cookie;
724 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
725 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
727 if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
728 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
729 return STATUS_SUCCESS;
731 nb_imports = 0;
732 while (imports[nb_imports].Name && imports[nb_imports].FirstThunk) nb_imports++;
734 if (!nb_imports) return STATUS_SUCCESS; /* no imports */
736 if (!create_module_activation_context( &wm->ldr ))
737 RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
739 /* Allocate module dependency list */
740 wm->nDeps = nb_imports;
741 wm->deps = RtlAllocateHeap( GetProcessHeap(), 0, nb_imports*sizeof(WINE_MODREF *) );
743 /* load the imported modules. They are automatically
744 * added to the modref list of the process.
746 prev = current_modref;
747 current_modref = wm;
748 status = STATUS_SUCCESS;
749 for (i = 0; i < nb_imports; i++)
751 if (!(wm->deps[i] = import_dll( wm->ldr.BaseAddress, &imports[i], load_path )))
752 status = STATUS_DLL_NOT_FOUND;
754 current_modref = prev;
755 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
756 return status;
760 /*************************************************************************
761 * is_dll_native_subsystem
763 * Check if dll is a proper native driver.
764 * Some dlls (corpol.dll from IE6 for instance) are incorrectly marked as native
765 * while being perfectly normal DLLs. This heuristic should catch such breakages.
767 static BOOL is_dll_native_subsystem( HMODULE module, const IMAGE_NT_HEADERS *nt, LPCWSTR filename )
769 static const WCHAR ntdllW[] = {'n','t','d','l','l','.','d','l','l',0};
770 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
771 const IMAGE_IMPORT_DESCRIPTOR *imports;
772 DWORD i, size;
773 WCHAR buffer[16];
775 if (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_NATIVE) return FALSE;
776 if (nt->OptionalHeader.SectionAlignment < getpagesize()) return TRUE;
778 if ((imports = RtlImageDirectoryEntryToData( module, TRUE,
779 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
781 for (i = 0; imports[i].Name; i++)
783 const char *name = get_rva( module, imports[i].Name );
784 DWORD len = strlen(name);
785 if (len * sizeof(WCHAR) >= sizeof(buffer)) continue;
786 ascii_to_unicode( buffer, name, len + 1 );
787 if (!strcmpiW( buffer, ntdllW ) || !strcmpiW( buffer, kernel32W ))
789 TRACE( "%s imports %s, assuming not native\n", debugstr_w(filename), debugstr_w(buffer) );
790 return FALSE;
794 return TRUE;
798 /*************************************************************************
799 * alloc_module
801 * Allocate a WINE_MODREF structure and add it to the process list
802 * The loader_section must be locked while calling this function.
804 static WINE_MODREF *alloc_module( HMODULE hModule, LPCWSTR filename )
806 WINE_MODREF *wm;
807 const WCHAR *p;
808 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
809 PLIST_ENTRY entry, mark;
811 if (!(wm = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm) ))) return NULL;
813 wm->nDeps = 0;
814 wm->deps = NULL;
816 wm->ldr.BaseAddress = hModule;
817 wm->ldr.EntryPoint = NULL;
818 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
819 wm->ldr.Flags = LDR_DONT_RESOLVE_REFS;
820 wm->ldr.LoadCount = 1;
821 wm->ldr.TlsIndex = -1;
822 wm->ldr.SectionHandle = NULL;
823 wm->ldr.CheckSum = 0;
824 wm->ldr.TimeDateStamp = 0;
825 wm->ldr.ActivationContext = 0;
827 RtlCreateUnicodeString( &wm->ldr.FullDllName, filename );
828 if ((p = strrchrW( wm->ldr.FullDllName.Buffer, '\\' ))) p++;
829 else p = wm->ldr.FullDllName.Buffer;
830 RtlInitUnicodeString( &wm->ldr.BaseDllName, p );
832 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && !is_dll_native_subsystem( hModule, nt, p ))
834 wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
835 if (nt->OptionalHeader.AddressOfEntryPoint)
836 wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
839 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
840 &wm->ldr.InLoadOrderModuleList);
842 /* insert module in MemoryList, sorted in increasing base addresses */
843 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
844 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
846 if (CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList)->BaseAddress > wm->ldr.BaseAddress)
847 break;
849 entry->Blink->Flink = &wm->ldr.InMemoryOrderModuleList;
850 wm->ldr.InMemoryOrderModuleList.Blink = entry->Blink;
851 wm->ldr.InMemoryOrderModuleList.Flink = entry;
852 entry->Blink = &wm->ldr.InMemoryOrderModuleList;
854 /* wait until init is called for inserting into this list */
855 wm->ldr.InInitializationOrderModuleList.Flink = NULL;
856 wm->ldr.InInitializationOrderModuleList.Blink = NULL;
858 if (!(nt->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
860 ULONG flags = MEM_EXECUTE_OPTION_ENABLE;
861 WARN( "disabling no-exec because of %s\n", debugstr_w(wm->ldr.BaseDllName.Buffer) );
862 NtSetInformationProcess( GetCurrentProcess(), ProcessExecuteFlags, &flags, sizeof(flags) );
864 return wm;
868 /*************************************************************************
869 * alloc_process_tls
871 * Allocate the process-wide structure for module TLS storage.
873 static NTSTATUS alloc_process_tls(void)
875 PLIST_ENTRY mark, entry;
876 PLDR_MODULE mod;
877 const IMAGE_TLS_DIRECTORY *dir;
878 ULONG size, i;
880 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
881 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
883 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
884 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
885 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
886 continue;
887 size = (dir->EndAddressOfRawData - dir->StartAddressOfRawData) + dir->SizeOfZeroFill;
888 if (!size && !dir->AddressOfCallBacks) continue;
889 tls_total_size += TLS_ALIGN(size);
890 tls_module_count++;
892 if (!tls_module_count) return STATUS_SUCCESS;
894 TRACE( "count %u size %u\n", tls_module_count, tls_total_size );
896 tls_dirs = RtlAllocateHeap( GetProcessHeap(), 0, tls_module_count * sizeof(*tls_dirs) );
897 if (!tls_dirs) return STATUS_NO_MEMORY;
899 for (i = 0, entry = mark->Flink; entry != mark; entry = entry->Flink)
901 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
902 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
903 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
904 continue;
905 tls_dirs[i] = dir;
906 *(DWORD *)dir->AddressOfIndex = i;
907 mod->TlsIndex = i;
908 mod->LoadCount = -1; /* can't unload it */
909 i++;
911 return STATUS_SUCCESS;
915 /*************************************************************************
916 * alloc_thread_tls
918 * Allocate the per-thread structure for module TLS storage.
920 static NTSTATUS alloc_thread_tls(void)
922 void **pointers;
923 char *data;
924 UINT i, size;
926 if (!tls_module_count) return STATUS_SUCCESS;
928 size = TLS_ALIGN( tls_module_count * sizeof(*pointers) );
929 if (!(pointers = RtlAllocateHeap( GetProcessHeap(), 0, size + tls_total_size )))
930 return STATUS_NO_MEMORY;
931 data = (char *)pointers + size;
933 for (i = 0; i < tls_module_count; i++)
935 const IMAGE_TLS_DIRECTORY *dir = tls_dirs[i];
936 size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
938 TRACE( "thread %04x idx %d: %d/%d bytes from %p to %p\n",
939 GetCurrentThreadId(), i, size, dir->SizeOfZeroFill,
940 (void *)dir->StartAddressOfRawData, data );
942 pointers[i] = data;
943 memcpy( data, (void *)dir->StartAddressOfRawData, size );
944 memset( data + size, 0, dir->SizeOfZeroFill );
945 data += TLS_ALIGN( size + dir->SizeOfZeroFill );
947 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
948 return STATUS_SUCCESS;
952 /*************************************************************************
953 * call_tls_callbacks
955 static void call_tls_callbacks( HMODULE module, UINT reason )
957 const IMAGE_TLS_DIRECTORY *dir;
958 const PIMAGE_TLS_CALLBACK *callback;
959 ULONG dirsize;
961 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
962 if (!dir || !dir->AddressOfCallBacks) return;
964 for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
966 if (TRACE_ON(relay))
967 DPRINTF("%04x:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
968 GetCurrentThreadId(), *callback, module, reason_names[reason] );
969 __TRY
971 (*callback)( module, reason, NULL );
973 __EXCEPT_ALL
975 if (TRACE_ON(relay))
976 DPRINTF("%04x:exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
977 GetCurrentThreadId(), callback, module, reason_names[reason] );
978 return;
980 __ENDTRY
981 if (TRACE_ON(relay))
982 DPRINTF("%04x:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
983 GetCurrentThreadId(), *callback, module, reason_names[reason] );
988 /*************************************************************************
989 * MODULE_InitDLL
991 static NTSTATUS MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
993 WCHAR mod_name[32];
994 NTSTATUS status = STATUS_SUCCESS;
995 DLLENTRYPROC entry = wm->ldr.EntryPoint;
996 void *module = wm->ldr.BaseAddress;
997 BOOL retv = TRUE;
999 /* Skip calls for modules loaded with special load flags */
1001 if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return STATUS_SUCCESS;
1002 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.BaseAddress, reason );
1003 if (!entry) return STATUS_SUCCESS;
1005 if (TRACE_ON(relay))
1007 size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
1008 memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
1009 mod_name[len / sizeof(WCHAR)] = 0;
1010 DPRINTF("%04x:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
1011 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
1012 reason_names[reason], lpReserved );
1014 else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
1015 reason_names[reason], lpReserved );
1017 __TRY
1019 retv = call_dll_entry_point( entry, module, reason, lpReserved );
1020 if (!retv)
1021 status = STATUS_DLL_INIT_FAILED;
1023 __EXCEPT_ALL
1025 if (TRACE_ON(relay))
1026 DPRINTF("%04x:exception in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
1027 GetCurrentThreadId(), entry, module, reason_names[reason], lpReserved );
1028 status = GetExceptionCode();
1030 __ENDTRY
1032 /* The state of the module list may have changed due to the call
1033 to the dll. We cannot assume that this module has not been
1034 deleted. */
1035 if (TRACE_ON(relay))
1036 DPRINTF("%04x:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
1037 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
1038 reason_names[reason], lpReserved, retv );
1039 else TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
1041 return status;
1045 /*************************************************************************
1046 * process_attach
1048 * Send the process attach notification to all DLLs the given module
1049 * depends on (recursively). This is somewhat complicated due to the fact that
1051 * - we have to respect the module dependencies, i.e. modules implicitly
1052 * referenced by another module have to be initialized before the module
1053 * itself can be initialized
1055 * - the initialization routine of a DLL can itself call LoadLibrary,
1056 * thereby introducing a whole new set of dependencies (even involving
1057 * the 'old' modules) at any time during the whole process
1059 * (Note that this routine can be recursively entered not only directly
1060 * from itself, but also via LoadLibrary from one of the called initialization
1061 * routines.)
1063 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
1064 * the process *detach* notifications to be sent in the correct order.
1065 * This must not only take into account module dependencies, but also
1066 * 'hidden' dependencies created by modules calling LoadLibrary in their
1067 * attach notification routine.
1069 * The strategy is rather simple: we move a WINE_MODREF to the head of the
1070 * list after the attach notification has returned. This implies that the
1071 * detach notifications are called in the reverse of the sequence the attach
1072 * notifications *returned*.
1074 * The loader_section must be locked while calling this function.
1076 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
1078 NTSTATUS status = STATUS_SUCCESS;
1079 ULONG_PTR cookie;
1080 int i;
1082 if (process_detaching) return status;
1084 /* prevent infinite recursion in case of cyclical dependencies */
1085 if ( ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
1086 || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
1087 return status;
1089 TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1091 /* Tag current MODREF to prevent recursive loop */
1092 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
1093 if (lpReserved) wm->ldr.LoadCount = -1; /* pin it if imported by the main exe */
1094 if (wm->ldr.ActivationContext) RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
1096 /* Recursively attach all DLLs this one depends on */
1097 for ( i = 0; i < wm->nDeps; i++ )
1099 if (!wm->deps[i]) continue;
1100 if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
1103 /* Call DLL entry point */
1104 if (status == STATUS_SUCCESS)
1106 WINE_MODREF *prev = current_modref;
1107 current_modref = wm;
1108 status = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
1109 if (status == STATUS_SUCCESS)
1110 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
1111 else
1113 MODULE_InitDLL( wm, DLL_PROCESS_DETACH, lpReserved );
1114 /* point to the name so LdrInitializeThunk can print it */
1115 last_failed_modref = wm;
1116 WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
1118 current_modref = prev;
1121 if (!wm->ldr.InInitializationOrderModuleList.Flink)
1122 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
1123 &wm->ldr.InInitializationOrderModuleList);
1125 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
1126 /* Remove recursion flag */
1127 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
1129 TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1130 return status;
1134 /**********************************************************************
1135 * attach_implicitly_loaded_dlls
1137 * Attach to the (builtin) dlls that have been implicitly loaded because
1138 * of a dependency at the Unix level, but not imported at the Win32 level.
1140 static void attach_implicitly_loaded_dlls( LPVOID reserved )
1142 for (;;)
1144 PLIST_ENTRY mark, entry;
1146 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1147 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1149 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1151 if (mod->Flags & (LDR_LOAD_IN_PROGRESS | LDR_PROCESS_ATTACHED)) continue;
1152 TRACE( "found implicitly loaded %s, attaching to it\n",
1153 debugstr_w(mod->BaseDllName.Buffer));
1154 process_attach( CONTAINING_RECORD(mod, WINE_MODREF, ldr), reserved );
1155 break; /* restart the search from the start */
1157 if (entry == mark) break; /* nothing found */
1162 /*************************************************************************
1163 * process_detach
1165 * Send DLL process detach notifications. See the comment about calling
1166 * sequence at process_attach. Unless the bForceDetach flag
1167 * is set, only DLLs with zero refcount are notified.
1169 static void process_detach( BOOL bForceDetach, LPVOID lpReserved )
1171 PLIST_ENTRY mark, entry;
1172 PLDR_MODULE mod;
1174 RtlEnterCriticalSection( &loader_section );
1175 if (bForceDetach) process_detaching = 1;
1176 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1179 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1181 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1182 InInitializationOrderModuleList);
1183 /* Check whether to detach this DLL */
1184 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1185 continue;
1186 if ( mod->LoadCount && !bForceDetach )
1187 continue;
1189 /* Call detach notification */
1190 mod->Flags &= ~LDR_PROCESS_ATTACHED;
1191 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1192 DLL_PROCESS_DETACH, lpReserved );
1194 /* Restart at head of WINE_MODREF list, as entries might have
1195 been added and/or removed while performing the call ... */
1196 break;
1198 } while (entry != mark);
1200 RtlLeaveCriticalSection( &loader_section );
1203 /*************************************************************************
1204 * MODULE_DllThreadAttach
1206 * Send DLL thread attach notifications. These are sent in the
1207 * reverse sequence of process detach notification.
1210 NTSTATUS MODULE_DllThreadAttach( LPVOID lpReserved )
1212 PLIST_ENTRY mark, entry;
1213 PLDR_MODULE mod;
1214 NTSTATUS status;
1216 /* don't do any attach calls if process is exiting */
1217 if (process_detaching) return STATUS_SUCCESS;
1218 /* FIXME: there is still a race here */
1220 RtlEnterCriticalSection( &loader_section );
1222 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto done;
1224 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1225 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1227 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1228 InInitializationOrderModuleList);
1229 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1230 continue;
1231 if ( mod->Flags & LDR_NO_DLL_CALLS )
1232 continue;
1234 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1235 DLL_THREAD_ATTACH, lpReserved );
1238 done:
1239 RtlLeaveCriticalSection( &loader_section );
1240 return status;
1243 /******************************************************************
1244 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1247 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1249 WINE_MODREF *wm;
1250 NTSTATUS ret = STATUS_SUCCESS;
1252 RtlEnterCriticalSection( &loader_section );
1254 wm = get_modref( hModule );
1255 if (!wm || wm->ldr.TlsIndex != -1)
1256 ret = STATUS_DLL_NOT_FOUND;
1257 else
1258 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1260 RtlLeaveCriticalSection( &loader_section );
1262 return ret;
1265 /******************************************************************
1266 * LdrFindEntryForAddress (NTDLL.@)
1268 * The loader_section must be locked while calling this function
1270 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
1272 PLIST_ENTRY mark, entry;
1273 PLDR_MODULE mod;
1275 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1276 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1278 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
1279 if (mod->BaseAddress <= addr &&
1280 (const char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
1282 *pmod = mod;
1283 return STATUS_SUCCESS;
1285 if (mod->BaseAddress > addr) break;
1287 return STATUS_NO_MORE_ENTRIES;
1290 /******************************************************************
1291 * LdrLockLoaderLock (NTDLL.@)
1293 * Note: flags are not implemented.
1294 * Flag 0x01 is used to raise exceptions on errors.
1295 * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
1297 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG *magic )
1299 if (flags) FIXME( "flags %x not supported\n", flags );
1301 if (result) *result = 1;
1302 if (!magic) return STATUS_INVALID_PARAMETER_3;
1303 RtlEnterCriticalSection( &loader_section );
1304 *magic = GetCurrentThreadId();
1305 return STATUS_SUCCESS;
1309 /******************************************************************
1310 * LdrUnlockLoaderUnlock (NTDLL.@)
1312 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG magic )
1314 if (magic)
1316 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1317 RtlLeaveCriticalSection( &loader_section );
1319 return STATUS_SUCCESS;
1323 /******************************************************************
1324 * LdrGetProcedureAddress (NTDLL.@)
1326 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1327 ULONG ord, PVOID *address)
1329 IMAGE_EXPORT_DIRECTORY *exports;
1330 DWORD exp_size;
1331 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1333 RtlEnterCriticalSection( &loader_section );
1335 /* check if the module itself is invalid to return the proper error */
1336 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1337 else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1338 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1340 LPCWSTR load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1341 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1, load_path )
1342 : find_ordinal_export( module, exports, exp_size, ord - exports->Base, load_path );
1343 if (proc)
1345 *address = proc;
1346 ret = STATUS_SUCCESS;
1350 RtlLeaveCriticalSection( &loader_section );
1351 return ret;
1355 /***********************************************************************
1356 * is_fake_dll
1358 * Check if a loaded native dll is a Wine fake dll.
1360 static BOOL is_fake_dll( HANDLE handle )
1362 static const char fakedll_signature[] = "Wine placeholder DLL";
1363 char buffer[sizeof(IMAGE_DOS_HEADER) + sizeof(fakedll_signature)];
1364 const IMAGE_DOS_HEADER *dos = (const IMAGE_DOS_HEADER *)buffer;
1365 IO_STATUS_BLOCK io;
1366 LARGE_INTEGER offset;
1368 offset.QuadPart = 0;
1369 if (NtReadFile( handle, 0, NULL, 0, &io, buffer, sizeof(buffer), &offset, NULL )) return FALSE;
1370 if (io.Information < sizeof(buffer)) return FALSE;
1371 if (dos->e_magic != IMAGE_DOS_SIGNATURE) return FALSE;
1372 if (dos->e_lfanew >= sizeof(*dos) + sizeof(fakedll_signature) &&
1373 !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) return TRUE;
1374 return FALSE;
1378 /***********************************************************************
1379 * get_builtin_fullname
1381 * Build the full pathname for a builtin dll.
1383 static WCHAR *get_builtin_fullname( const WCHAR *path, const char *filename )
1385 static const WCHAR soW[] = {'.','s','o',0};
1386 WCHAR *p, *fullname;
1387 size_t i, len = strlen(filename);
1389 /* check if path can correspond to the dll we have */
1390 if (path && (p = strrchrW( path, '\\' )))
1392 p++;
1393 for (i = 0; i < len; i++)
1394 if (tolowerW(p[i]) != tolowerW( (WCHAR)filename[i]) ) break;
1395 if (i == len && (!p[len] || !strcmpiW( p + len, soW )))
1397 /* the filename matches, use path as the full path */
1398 len += p - path;
1399 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
1401 memcpy( fullname, path, len * sizeof(WCHAR) );
1402 fullname[len] = 0;
1404 return fullname;
1408 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0,
1409 system_dir.MaximumLength + (len + 1) * sizeof(WCHAR) )))
1411 memcpy( fullname, system_dir.Buffer, system_dir.Length );
1412 p = fullname + system_dir.Length / sizeof(WCHAR);
1413 if (p > fullname && p[-1] != '\\') *p++ = '\\';
1414 ascii_to_unicode( p, filename, len + 1 );
1416 return fullname;
1420 /***********************************************************************
1421 * load_builtin_callback
1423 * Load a library in memory; callback function for wine_dll_register
1425 static void load_builtin_callback( void *module, const char *filename )
1427 static const WCHAR emptyW[1];
1428 IMAGE_NT_HEADERS *nt;
1429 WINE_MODREF *wm;
1430 WCHAR *fullname;
1431 const WCHAR *load_path;
1433 if (!module)
1435 ERR("could not map image for %s\n", filename ? filename : "main exe" );
1436 return;
1438 if (!(nt = RtlImageNtHeader( module )))
1440 ERR( "bad module for %s\n", filename ? filename : "main exe" );
1441 builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1442 return;
1445 virtual_create_builtin_view( module );
1447 /* create the MODREF */
1449 if (!(fullname = get_builtin_fullname( builtin_load_info->filename, filename )))
1451 ERR( "can't load %s\n", filename );
1452 builtin_load_info->status = STATUS_NO_MEMORY;
1453 return;
1456 wm = alloc_module( module, fullname );
1457 RtlFreeHeap( GetProcessHeap(), 0, fullname );
1458 if (!wm)
1460 ERR( "can't load %s\n", filename );
1461 builtin_load_info->status = STATUS_NO_MEMORY;
1462 return;
1464 wm->ldr.Flags |= LDR_WINE_INTERNAL;
1466 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
1467 !NtCurrentTeb()->Peb->ImageBaseAddress) /* if we already have an executable, ignore this one */
1469 NtCurrentTeb()->Peb->ImageBaseAddress = module;
1471 else
1473 /* fixup imports */
1475 load_path = builtin_load_info->load_path;
1476 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1477 if (!load_path) load_path = emptyW;
1478 if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1480 /* the module has only be inserted in the load & memory order lists */
1481 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1482 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1483 /* FIXME: free the modref */
1484 builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1485 return;
1489 builtin_load_info->wm = wm;
1490 TRACE( "loaded %s %p %p\n", filename, wm, module );
1492 /* send the DLL load event */
1494 SERVER_START_REQ( load_dll )
1496 req->mapping = 0;
1497 req->base = wine_server_client_ptr( module );
1498 req->size = nt->OptionalHeader.SizeOfImage;
1499 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1500 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1501 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1502 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1503 wine_server_call( req );
1505 SERVER_END_REQ;
1507 /* setup relay debugging entry points */
1508 if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1512 /******************************************************************************
1513 * load_native_dll (internal)
1515 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1516 DWORD flags, WINE_MODREF** pwm )
1518 void *module;
1519 HANDLE mapping;
1520 LARGE_INTEGER size;
1521 IMAGE_NT_HEADERS *nt;
1522 SIZE_T len = 0;
1523 WINE_MODREF *wm;
1524 NTSTATUS status;
1526 TRACE("Trying native dll %s\n", debugstr_w(name));
1528 size.QuadPart = 0;
1529 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1530 NULL, &size, PAGE_EXECUTE_READ, SEC_IMAGE, file );
1531 if (status != STATUS_SUCCESS) return status;
1533 module = NULL;
1534 status = NtMapViewOfSection( mapping, NtCurrentProcess(),
1535 &module, 0, 0, &size, &len, ViewShare, 0, PAGE_EXECUTE_READ );
1536 if (status < 0) goto done;
1538 /* create the MODREF */
1540 if (!(wm = alloc_module( module, name )))
1542 status = STATUS_NO_MEMORY;
1543 goto done;
1546 /* fixup imports */
1548 if (!(flags & DONT_RESOLVE_DLL_REFERENCES))
1550 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1552 /* the module has only be inserted in the load & memory order lists */
1553 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1554 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1556 /* FIXME: there are several more dangling references
1557 * left. Including dlls loaded by this dll before the
1558 * failed one. Unrolling is rather difficult with the
1559 * current structure and we can leave them lying
1560 * around with no problems, so we don't care.
1561 * As these might reference our wm, we don't free it.
1563 goto done;
1567 /* send DLL load event */
1569 nt = RtlImageNtHeader( module );
1571 SERVER_START_REQ( load_dll )
1573 req->mapping = wine_server_obj_handle( mapping );
1574 req->base = wine_server_client_ptr( module );
1575 req->size = nt->OptionalHeader.SizeOfImage;
1576 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1577 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1578 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1579 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1580 wine_server_call( req );
1582 SERVER_END_REQ;
1584 if ((wm->ldr.Flags & LDR_IMAGE_IS_DLL) && TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1586 TRACE_(loaddll)( "Loaded %s at %p: native\n", debugstr_w(wm->ldr.FullDllName.Buffer), module );
1588 wm->ldr.LoadCount = 1;
1589 *pwm = wm;
1590 status = STATUS_SUCCESS;
1591 done:
1592 NtClose( mapping );
1593 return status;
1597 /***********************************************************************
1598 * load_builtin_dll
1600 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, HANDLE file,
1601 DWORD flags, WINE_MODREF** pwm )
1603 char error[256], dllname[MAX_PATH];
1604 const WCHAR *name, *p;
1605 DWORD len, i;
1606 void *handle = NULL;
1607 struct builtin_load_info info, *prev_info;
1609 /* Fix the name in case we have a full path and extension */
1610 name = path;
1611 if ((p = strrchrW( name, '\\' ))) name = p + 1;
1612 if ((p = strrchrW( name, '/' ))) name = p + 1;
1614 /* load_library will modify info.status. Note also that load_library can be
1615 * called several times, if the .so file we're loading has dependencies.
1616 * info.status will gather all the errors we may get while loading all these
1617 * libraries
1619 info.load_path = load_path;
1620 info.filename = NULL;
1621 info.status = STATUS_SUCCESS;
1622 info.wm = NULL;
1624 if (file) /* we have a real file, try to load it */
1626 UNICODE_STRING nt_name;
1627 ANSI_STRING unix_name;
1629 TRACE("Trying built-in %s\n", debugstr_w(path));
1631 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1632 return STATUS_DLL_NOT_FOUND;
1634 if (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ))
1636 RtlFreeUnicodeString( &nt_name );
1637 return STATUS_DLL_NOT_FOUND;
1639 prev_info = builtin_load_info;
1640 info.filename = nt_name.Buffer + 4; /* skip \??\ */
1641 builtin_load_info = &info;
1642 handle = wine_dlopen( unix_name.Buffer, RTLD_NOW, error, sizeof(error) );
1643 builtin_load_info = prev_info;
1644 RtlFreeUnicodeString( &nt_name );
1645 RtlFreeHeap( GetProcessHeap(), 0, unix_name.Buffer );
1646 if (!handle)
1648 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path), error );
1649 return STATUS_INVALID_IMAGE_FORMAT;
1652 else
1654 int file_exists;
1656 TRACE("Trying built-in %s\n", debugstr_w(name));
1658 /* we don't want to depend on the current codepage here */
1659 len = strlenW( name ) + 1;
1660 if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1661 for (i = 0; i < len; i++)
1663 if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1664 dllname[i] = (char)name[i];
1665 if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1668 prev_info = builtin_load_info;
1669 builtin_load_info = &info;
1670 handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1671 builtin_load_info = prev_info;
1672 if (!handle)
1674 if (!file_exists)
1676 /* The file does not exist -> WARN() */
1677 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
1678 return STATUS_DLL_NOT_FOUND;
1680 /* ERR() for all other errors (missing functions, ...) */
1681 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
1682 return STATUS_PROCEDURE_NOT_FOUND;
1686 if (info.status != STATUS_SUCCESS)
1688 wine_dll_unload( handle );
1689 return info.status;
1692 if (!info.wm)
1694 PLIST_ENTRY mark, entry;
1696 /* The constructor wasn't called, this means the .so is already
1697 * loaded under a different name. Try to find the wm for it. */
1699 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1700 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1702 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1703 if (mod->Flags & LDR_WINE_INTERNAL && mod->SectionHandle == handle)
1705 info.wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1706 TRACE( "Found %s at %p for builtin %s\n",
1707 debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress, debugstr_w(path) );
1708 break;
1711 wine_dll_unload( handle ); /* release the libdl refcount */
1712 if (!info.wm) return STATUS_INVALID_IMAGE_FORMAT;
1713 if (info.wm->ldr.LoadCount != -1) info.wm->ldr.LoadCount++;
1715 else
1717 TRACE_(loaddll)( "Loaded %s at %p: builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress );
1718 info.wm->ldr.LoadCount = 1;
1719 info.wm->ldr.SectionHandle = handle;
1722 *pwm = info.wm;
1723 return STATUS_SUCCESS;
1727 /***********************************************************************
1728 * find_actctx_dll
1730 * Find the full path (if any) of the dll from the activation context.
1732 static NTSTATUS find_actctx_dll( LPCWSTR libname, LPWSTR *fullname )
1734 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
1735 static const WCHAR dotManifestW[] = {'.','m','a','n','i','f','e','s','t',0};
1737 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
1738 ACTCTX_SECTION_KEYED_DATA data;
1739 UNICODE_STRING nameW;
1740 NTSTATUS status;
1741 SIZE_T needed, size = 1024;
1742 WCHAR *p;
1744 RtlInitUnicodeString( &nameW, libname );
1745 data.cbSize = sizeof(data);
1746 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
1747 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
1748 &nameW, &data );
1749 if (status != STATUS_SUCCESS) return status;
1751 for (;;)
1753 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1755 status = STATUS_NO_MEMORY;
1756 goto done;
1758 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
1759 AssemblyDetailedInformationInActivationContext,
1760 info, size, &needed );
1761 if (status == STATUS_SUCCESS) break;
1762 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
1763 RtlFreeHeap( GetProcessHeap(), 0, info );
1764 size = needed;
1765 /* restart with larger buffer */
1768 if (!info->lpAssemblyManifestPath || !info->lpAssemblyDirectoryName)
1770 status = STATUS_SXS_KEY_NOT_FOUND;
1771 goto done;
1774 if ((p = strrchrW( info->lpAssemblyManifestPath, '\\' )))
1776 DWORD dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1778 p++;
1779 if (strncmpiW( p, info->lpAssemblyDirectoryName, dirlen ) || strcmpiW( p + dirlen, dotManifestW ))
1781 /* manifest name does not match directory name, so it's not a global
1782 * windows/winsxs manifest; use the manifest directory name instead */
1783 dirlen = p - info->lpAssemblyManifestPath;
1784 needed = (dirlen + 1) * sizeof(WCHAR) + nameW.Length;
1785 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1787 status = STATUS_NO_MEMORY;
1788 goto done;
1790 memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
1791 p += dirlen;
1792 strcpyW( p, libname );
1793 goto done;
1797 needed = (strlenW(user_shared_data->NtSystemRoot) * sizeof(WCHAR) +
1798 sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength + nameW.Length + 2*sizeof(WCHAR));
1800 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1802 status = STATUS_NO_MEMORY;
1803 goto done;
1805 strcpyW( p, user_shared_data->NtSystemRoot );
1806 p += strlenW(p);
1807 memcpy( p, winsxsW, sizeof(winsxsW) );
1808 p += sizeof(winsxsW) / sizeof(WCHAR);
1809 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
1810 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1811 *p++ = '\\';
1812 strcpyW( p, libname );
1813 done:
1814 RtlFreeHeap( GetProcessHeap(), 0, info );
1815 RtlReleaseActivationContext( data.hActCtx );
1816 return status;
1820 /***********************************************************************
1821 * find_dll_file
1823 * Find the file (or already loaded module) for a given dll name.
1825 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
1826 WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
1828 OBJECT_ATTRIBUTES attr;
1829 IO_STATUS_BLOCK io;
1830 UNICODE_STRING nt_name;
1831 WCHAR *file_part, *ext, *dllname;
1832 ULONG len;
1834 /* first append .dll if needed */
1836 dllname = NULL;
1837 if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
1839 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
1840 (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
1841 return STATUS_NO_MEMORY;
1842 strcpyW( dllname, libname );
1843 strcatW( dllname, dllW );
1844 libname = dllname;
1847 nt_name.Buffer = NULL;
1849 if (!contains_path( libname ))
1851 NTSTATUS status;
1852 WCHAR *fullname = NULL;
1854 if ((*pwm = find_basename_module( libname )) != NULL) goto found;
1856 status = find_actctx_dll( libname, &fullname );
1857 if (status == STATUS_SUCCESS)
1859 TRACE ("found %s for %s\n", debugstr_w(fullname), debugstr_w(libname) );
1860 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1861 libname = dllname = fullname;
1863 else if (status != STATUS_SXS_KEY_NOT_FOUND)
1865 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1866 return status;
1870 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
1872 /* we need to search for it */
1873 len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
1874 if (len)
1876 if (len >= *size) goto overflow;
1877 if ((*pwm = find_fullname_module( filename )) || !handle) goto found;
1879 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
1881 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1882 return STATUS_NO_MEMORY;
1884 attr.Length = sizeof(attr);
1885 attr.RootDirectory = 0;
1886 attr.Attributes = OBJ_CASE_INSENSITIVE;
1887 attr.ObjectName = &nt_name;
1888 attr.SecurityDescriptor = NULL;
1889 attr.SecurityQualityOfService = NULL;
1890 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1891 goto found;
1894 /* not found */
1896 if (!contains_path( libname ))
1898 /* if libname doesn't contain a path at all, we simply return the name as is,
1899 * to be loaded as builtin */
1900 len = strlenW(libname) * sizeof(WCHAR);
1901 if (len >= *size) goto overflow;
1902 strcpyW( filename, libname );
1903 goto found;
1907 /* absolute path name, or relative path name but not found above */
1909 if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
1911 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1912 return STATUS_NO_MEMORY;
1914 len = nt_name.Length - 4*sizeof(WCHAR); /* for \??\ prefix */
1915 if (len >= *size) goto overflow;
1916 memcpy( filename, nt_name.Buffer + 4, len + sizeof(WCHAR) );
1917 if (!(*pwm = find_fullname_module( filename )) && handle)
1919 attr.Length = sizeof(attr);
1920 attr.RootDirectory = 0;
1921 attr.Attributes = OBJ_CASE_INSENSITIVE;
1922 attr.ObjectName = &nt_name;
1923 attr.SecurityDescriptor = NULL;
1924 attr.SecurityQualityOfService = NULL;
1925 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1927 found:
1928 RtlFreeUnicodeString( &nt_name );
1929 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1930 return STATUS_SUCCESS;
1932 overflow:
1933 RtlFreeUnicodeString( &nt_name );
1934 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1935 *size = len + sizeof(WCHAR);
1936 return STATUS_BUFFER_TOO_SMALL;
1940 /***********************************************************************
1941 * load_dll (internal)
1943 * Load a PE style module according to the load order.
1944 * The loader_section must be locked while calling this function.
1946 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
1948 enum loadorder loadorder;
1949 WCHAR buffer[32];
1950 WCHAR *filename;
1951 ULONG size;
1952 WINE_MODREF *main_exe;
1953 HANDLE handle = 0;
1954 NTSTATUS nts;
1956 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
1958 *pwm = NULL;
1959 filename = buffer;
1960 size = sizeof(buffer);
1961 for (;;)
1963 nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
1964 if (nts == STATUS_SUCCESS) break;
1965 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1966 if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
1967 /* grow the buffer and retry */
1968 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
1971 if (*pwm) /* found already loaded module */
1973 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
1975 if (!(flags & DONT_RESOLVE_DLL_REFERENCES)) fixup_imports( *pwm, load_path );
1977 TRACE("Found %s for %s at %p, count=%d\n",
1978 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
1979 (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
1980 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1981 return STATUS_SUCCESS;
1984 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
1985 loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
1987 if (handle && is_fake_dll( handle ))
1989 TRACE( "%s is a fake Wine dll\n", debugstr_w(filename) );
1990 NtClose( handle );
1991 handle = 0;
1994 switch(loadorder)
1996 case LO_INVALID:
1997 nts = STATUS_NO_MEMORY;
1998 break;
1999 case LO_DISABLED:
2000 nts = STATUS_DLL_NOT_FOUND;
2001 break;
2002 case LO_NATIVE:
2003 case LO_NATIVE_BUILTIN:
2004 if (!handle) nts = STATUS_DLL_NOT_FOUND;
2005 else
2007 nts = load_native_dll( load_path, filename, handle, flags, pwm );
2008 if (nts == STATUS_INVALID_FILE_FOR_SECTION)
2009 /* not in PE format, maybe it's a builtin */
2010 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
2012 if (nts == STATUS_DLL_NOT_FOUND && loadorder == LO_NATIVE_BUILTIN)
2013 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
2014 break;
2015 case LO_BUILTIN:
2016 case LO_BUILTIN_NATIVE:
2017 case LO_DEFAULT: /* default is builtin,native */
2018 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
2019 if (!handle) break; /* nothing else we can try */
2020 /* file is not a builtin library, try without using the specified file */
2021 if (nts != STATUS_SUCCESS)
2022 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
2023 if (nts == STATUS_SUCCESS && loadorder == LO_DEFAULT &&
2024 (MODULE_InitDLL( *pwm, DLL_WINE_PREATTACH, NULL ) != STATUS_SUCCESS))
2026 /* stub-only dll, try native */
2027 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename) );
2028 LdrUnloadDll( (*pwm)->ldr.BaseAddress );
2029 nts = STATUS_DLL_NOT_FOUND;
2031 if (nts == STATUS_DLL_NOT_FOUND && loadorder != LO_BUILTIN)
2032 nts = load_native_dll( load_path, filename, handle, flags, pwm );
2033 break;
2036 if (nts == STATUS_SUCCESS)
2038 /* Initialize DLL just loaded */
2039 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename),
2040 ((*pwm)->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native",
2041 (*pwm)->ldr.BaseAddress);
2042 if (handle) NtClose( handle );
2043 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2044 return nts;
2047 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
2048 if (handle) NtClose( handle );
2049 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2050 return nts;
2053 /******************************************************************
2054 * LdrLoadDll (NTDLL.@)
2056 NTSTATUS WINAPI DECLSPEC_HOTPATCH LdrLoadDll(LPCWSTR path_name, DWORD flags,
2057 const UNICODE_STRING *libname, HMODULE* hModule)
2059 WINE_MODREF *wm;
2060 NTSTATUS nts;
2062 RtlEnterCriticalSection( &loader_section );
2064 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2065 nts = load_dll( path_name, libname->Buffer, flags, &wm );
2067 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
2069 nts = process_attach( wm, NULL );
2070 if (nts != STATUS_SUCCESS)
2072 LdrUnloadDll(wm->ldr.BaseAddress);
2073 wm = NULL;
2076 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
2078 RtlLeaveCriticalSection( &loader_section );
2079 return nts;
2083 /******************************************************************
2084 * LdrGetDllHandle (NTDLL.@)
2086 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
2088 NTSTATUS status;
2089 WCHAR buffer[128];
2090 WCHAR *filename;
2091 ULONG size;
2092 WINE_MODREF *wm;
2094 RtlEnterCriticalSection( &loader_section );
2096 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2098 filename = buffer;
2099 size = sizeof(buffer);
2100 for (;;)
2102 status = find_dll_file( load_path, name->Buffer, filename, &size, &wm, NULL );
2103 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2104 if (status != STATUS_BUFFER_TOO_SMALL) break;
2105 /* grow the buffer and retry */
2106 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2108 status = STATUS_NO_MEMORY;
2109 break;
2113 if (status == STATUS_SUCCESS)
2115 if (wm) *base = wm->ldr.BaseAddress;
2116 else status = STATUS_DLL_NOT_FOUND;
2119 RtlLeaveCriticalSection( &loader_section );
2120 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
2121 return status;
2125 /******************************************************************
2126 * LdrAddRefDll (NTDLL.@)
2128 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
2130 NTSTATUS ret = STATUS_SUCCESS;
2131 WINE_MODREF *wm;
2133 if (flags) FIXME( "%p flags %x not implemented\n", module, flags );
2135 RtlEnterCriticalSection( &loader_section );
2137 if ((wm = get_modref( module )))
2139 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
2140 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2142 else ret = STATUS_INVALID_PARAMETER;
2144 RtlLeaveCriticalSection( &loader_section );
2145 return ret;
2149 /***********************************************************************
2150 * LdrProcessRelocationBlock (NTDLL.@)
2152 * Apply relocations to a given page of a mapped PE image.
2154 IMAGE_BASE_RELOCATION * WINAPI LdrProcessRelocationBlock( void *page, UINT count,
2155 USHORT *relocs, INT_PTR delta )
2157 while (count--)
2159 USHORT offset = *relocs & 0xfff;
2160 int type = *relocs >> 12;
2161 switch(type)
2163 case IMAGE_REL_BASED_ABSOLUTE:
2164 break;
2165 case IMAGE_REL_BASED_HIGH:
2166 *(short *)((char *)page + offset) += HIWORD(delta);
2167 break;
2168 case IMAGE_REL_BASED_LOW:
2169 *(short *)((char *)page + offset) += LOWORD(delta);
2170 break;
2171 case IMAGE_REL_BASED_HIGHLOW:
2172 *(int *)((char *)page + offset) += delta;
2173 break;
2174 #ifdef __x86_64__
2175 case IMAGE_REL_BASED_DIR64:
2176 *(INT_PTR *)((char *)page + offset) += delta;
2177 break;
2178 #endif
2179 default:
2180 FIXME("Unknown/unsupported fixup type %x.\n", type);
2181 return NULL;
2183 relocs++;
2185 return (IMAGE_BASE_RELOCATION *)relocs; /* return address of next block */
2189 /******************************************************************
2190 * LdrQueryProcessModuleInformation
2193 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
2194 ULONG buf_size, ULONG* req_size)
2196 SYSTEM_MODULE* sm = &smi->Modules[0];
2197 ULONG size = sizeof(ULONG);
2198 NTSTATUS nts = STATUS_SUCCESS;
2199 ANSI_STRING str;
2200 char* ptr;
2201 PLIST_ENTRY mark, entry;
2202 PLDR_MODULE mod;
2203 WORD id = 0;
2205 smi->ModulesCount = 0;
2207 RtlEnterCriticalSection( &loader_section );
2208 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2209 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2211 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2212 size += sizeof(*sm);
2213 if (size <= buf_size)
2215 sm->Reserved1 = 0; /* FIXME */
2216 sm->Reserved2 = 0; /* FIXME */
2217 sm->ImageBaseAddress = mod->BaseAddress;
2218 sm->ImageSize = mod->SizeOfImage;
2219 sm->Flags = mod->Flags;
2220 sm->Id = id++;
2221 sm->Rank = 0; /* FIXME */
2222 sm->Unknown = 0; /* FIXME */
2223 str.Length = 0;
2224 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
2225 str.Buffer = (char*)sm->Name;
2226 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
2227 ptr = strrchr(str.Buffer, '\\');
2228 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
2230 smi->ModulesCount++;
2231 sm++;
2233 else nts = STATUS_INFO_LENGTH_MISMATCH;
2235 RtlLeaveCriticalSection( &loader_section );
2237 if (req_size) *req_size = size;
2239 return nts;
2243 static NTSTATUS query_dword_option( HANDLE hkey, LPCWSTR name, ULONG *value )
2245 NTSTATUS status;
2246 UNICODE_STRING str;
2247 ULONG size;
2248 WCHAR buffer[64];
2249 KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
2251 RtlInitUnicodeString( &str, name );
2253 size = sizeof(buffer) - sizeof(WCHAR);
2254 if ((status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size )))
2255 return status;
2257 if (info->Type != REG_DWORD)
2259 buffer[size / sizeof(WCHAR)] = 0;
2260 *value = strtoulW( (WCHAR *)info->Data, 0, 16 );
2262 else memcpy( value, info->Data, sizeof(*value) );
2263 return status;
2266 static NTSTATUS query_string_option( HANDLE hkey, LPCWSTR name, ULONG type,
2267 void *data, ULONG in_size, ULONG *out_size )
2269 NTSTATUS status;
2270 UNICODE_STRING str;
2271 ULONG size;
2272 char *buffer;
2273 KEY_VALUE_PARTIAL_INFORMATION *info;
2274 static const int info_size = FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data );
2276 RtlInitUnicodeString( &str, name );
2278 size = info_size + in_size;
2279 if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
2280 info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
2281 status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size );
2282 if (!status || status == STATUS_BUFFER_OVERFLOW)
2284 if (out_size) *out_size = info->DataLength;
2285 if (data && !status) memcpy( data, info->Data, info->DataLength );
2287 RtlFreeHeap( GetProcessHeap(), 0, buffer );
2288 return status;
2292 /******************************************************************
2293 * LdrQueryImageFileExecutionOptions (NTDLL.@)
2295 NTSTATUS WINAPI LdrQueryImageFileExecutionOptions( const UNICODE_STRING *key, LPCWSTR value, ULONG type,
2296 void *data, ULONG in_size, ULONG *out_size )
2298 static const WCHAR optionsW[] = {'M','a','c','h','i','n','e','\\',
2299 'S','o','f','t','w','a','r','e','\\',
2300 'M','i','c','r','o','s','o','f','t','\\',
2301 'W','i','n','d','o','w','s',' ','N','T','\\',
2302 'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
2303 'I','m','a','g','e',' ','F','i','l','e',' ',
2304 'E','x','e','c','u','t','i','o','n',' ','O','p','t','i','o','n','s','\\'};
2305 WCHAR path[MAX_PATH + sizeof(optionsW)/sizeof(WCHAR)];
2306 OBJECT_ATTRIBUTES attr;
2307 UNICODE_STRING name_str;
2308 HANDLE hkey;
2309 NTSTATUS status;
2310 ULONG len;
2311 WCHAR *p;
2313 attr.Length = sizeof(attr);
2314 attr.RootDirectory = 0;
2315 attr.ObjectName = &name_str;
2316 attr.Attributes = OBJ_CASE_INSENSITIVE;
2317 attr.SecurityDescriptor = NULL;
2318 attr.SecurityQualityOfService = NULL;
2320 if ((p = memrchrW( key->Buffer, '\\', key->Length / sizeof(WCHAR) ))) p++;
2321 else p = key->Buffer;
2322 len = key->Length - (p - key->Buffer) * sizeof(WCHAR);
2323 name_str.Buffer = path;
2324 name_str.Length = sizeof(optionsW) + len;
2325 name_str.MaximumLength = name_str.Length;
2326 memcpy( path, optionsW, sizeof(optionsW) );
2327 memcpy( path + sizeof(optionsW)/sizeof(WCHAR), p, len );
2328 if ((status = NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr ))) return status;
2330 if (type == REG_DWORD)
2332 if (out_size) *out_size = sizeof(ULONG);
2333 if (in_size >= sizeof(ULONG)) status = query_dword_option( hkey, value, data );
2334 else status = STATUS_BUFFER_OVERFLOW;
2336 else status = query_string_option( hkey, value, type, data, in_size, out_size );
2338 NtClose( hkey );
2339 return status;
2343 /******************************************************************
2344 * RtlDllShutdownInProgress (NTDLL.@)
2346 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
2348 return process_detaching;
2352 /******************************************************************
2353 * LdrShutdownProcess (NTDLL.@)
2356 void WINAPI LdrShutdownProcess(void)
2358 TRACE("()\n");
2359 process_detach( TRUE, (LPVOID)1 );
2362 /******************************************************************
2363 * LdrShutdownThread (NTDLL.@)
2366 void WINAPI LdrShutdownThread(void)
2368 PLIST_ENTRY mark, entry;
2369 PLDR_MODULE mod;
2371 TRACE("()\n");
2373 /* don't do any detach calls if process is exiting */
2374 if (process_detaching) return;
2375 /* FIXME: there is still a race here */
2377 RtlEnterCriticalSection( &loader_section );
2379 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2380 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
2382 mod = CONTAINING_RECORD(entry, LDR_MODULE,
2383 InInitializationOrderModuleList);
2384 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
2385 continue;
2386 if ( mod->Flags & LDR_NO_DLL_CALLS )
2387 continue;
2389 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
2390 DLL_THREAD_DETACH, NULL );
2393 RtlLeaveCriticalSection( &loader_section );
2394 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->ThreadLocalStoragePointer );
2398 /***********************************************************************
2399 * free_modref
2402 static void free_modref( WINE_MODREF *wm )
2404 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
2405 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
2406 if (wm->ldr.InInitializationOrderModuleList.Flink)
2407 RemoveEntryList(&wm->ldr.InInitializationOrderModuleList);
2409 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
2410 if (!TRACE_ON(module))
2411 TRACE_(loaddll)("Unloaded module %s : %s\n",
2412 debugstr_w(wm->ldr.FullDllName.Buffer),
2413 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
2415 SERVER_START_REQ( unload_dll )
2417 req->base = wine_server_client_ptr( wm->ldr.BaseAddress );
2418 wine_server_call( req );
2420 SERVER_END_REQ;
2422 RtlReleaseActivationContext( wm->ldr.ActivationContext );
2423 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.BaseAddress );
2424 if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
2425 if (cached_modref == wm) cached_modref = NULL;
2426 RtlFreeUnicodeString( &wm->ldr.FullDllName );
2427 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
2428 RtlFreeHeap( GetProcessHeap(), 0, wm );
2431 /***********************************************************************
2432 * MODULE_FlushModrefs
2434 * Remove all unused modrefs and call the internal unloading routines
2435 * for the library type.
2437 * The loader_section must be locked while calling this function.
2439 static void MODULE_FlushModrefs(void)
2441 PLIST_ENTRY mark, entry, prev;
2442 PLDR_MODULE mod;
2443 WINE_MODREF*wm;
2445 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2446 for (entry = mark->Blink; entry != mark; entry = prev)
2448 mod = CONTAINING_RECORD(entry, LDR_MODULE, InInitializationOrderModuleList);
2449 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2450 prev = entry->Blink;
2451 if (!mod->LoadCount) free_modref( wm );
2454 /* check load order list too for modules that haven't been initialized yet */
2455 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2456 for (entry = mark->Blink; entry != mark; entry = prev)
2458 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2459 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2460 prev = entry->Blink;
2461 if (!mod->LoadCount) free_modref( wm );
2465 /***********************************************************************
2466 * MODULE_DecRefCount
2468 * The loader_section must be locked while calling this function.
2470 static void MODULE_DecRefCount( WINE_MODREF *wm )
2472 int i;
2474 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
2475 return;
2477 if ( wm->ldr.LoadCount <= 0 )
2478 return;
2480 --wm->ldr.LoadCount;
2481 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2483 if ( wm->ldr.LoadCount == 0 )
2485 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
2487 for ( i = 0; i < wm->nDeps; i++ )
2488 if ( wm->deps[i] )
2489 MODULE_DecRefCount( wm->deps[i] );
2491 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
2495 /******************************************************************
2496 * LdrUnloadDll (NTDLL.@)
2500 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
2502 NTSTATUS retv = STATUS_SUCCESS;
2504 TRACE("(%p)\n", hModule);
2506 RtlEnterCriticalSection( &loader_section );
2508 /* if we're stopping the whole process (and forcing the removal of all
2509 * DLLs) the library will be freed anyway
2511 if (!process_detaching)
2513 WINE_MODREF *wm;
2515 free_lib_count++;
2516 if ((wm = get_modref( hModule )) != NULL)
2518 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
2520 /* Recursively decrement reference counts */
2521 MODULE_DecRefCount( wm );
2523 /* Call process detach notifications */
2524 if ( free_lib_count <= 1 )
2526 process_detach( FALSE, NULL );
2527 MODULE_FlushModrefs();
2530 TRACE("END\n");
2532 else
2533 retv = STATUS_DLL_NOT_FOUND;
2535 free_lib_count--;
2538 RtlLeaveCriticalSection( &loader_section );
2540 return retv;
2543 /***********************************************************************
2544 * RtlImageNtHeader (NTDLL.@)
2546 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
2548 IMAGE_NT_HEADERS *ret;
2550 __TRY
2552 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
2554 ret = NULL;
2555 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
2557 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
2558 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
2561 __EXCEPT_PAGE_FAULT
2563 return NULL;
2565 __ENDTRY
2566 return ret;
2570 /***********************************************************************
2571 * attach_process_dlls
2573 * Initial attach to all the dlls loaded by the process.
2575 static NTSTATUS attach_process_dlls( void *wm )
2577 NTSTATUS status;
2579 pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
2581 RtlEnterCriticalSection( &loader_section );
2582 if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS)
2584 if (last_failed_modref)
2585 ERR( "%s failed to initialize, aborting\n",
2586 debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
2587 return status;
2589 attach_implicitly_loaded_dlls( (LPVOID)1 );
2590 RtlLeaveCriticalSection( &loader_section );
2591 return status;
2595 /***********************************************************************
2596 * load_global_options
2598 static void load_global_options(void)
2600 static const WCHAR sessionW[] = {'M','a','c','h','i','n','e','\\',
2601 'S','y','s','t','e','m','\\',
2602 'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
2603 'C','o','n','t','r','o','l','\\',
2604 'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
2605 static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
2606 static const WCHAR critsectW[] = {'C','r','i','t','i','c','a','l','S','e','c','t','i','o','n','T','i','m','e','o','u','t',0};
2607 static const WCHAR heapresW[] = {'H','e','a','p','S','e','g','m','e','n','t','R','e','s','e','r','v','e',0};
2608 static const WCHAR heapcommitW[] = {'H','e','a','p','S','e','g','m','e','n','t','C','o','m','m','i','t',0};
2609 static const WCHAR decommittotalW[] = {'H','e','a','p','D','e','C','o','m','m','i','t','T','o','t','a','l','F','r','e','e','T','h','r','e','s','h','o','l','d',0};
2610 static const WCHAR decommitfreeW[] = {'H','e','a','p','D','e','C','o','m','m','i','t','F','r','e','e','B','l','o','c','k','T','h','r','e','s','h','o','l','d',0};
2612 OBJECT_ATTRIBUTES attr;
2613 UNICODE_STRING name_str;
2614 HANDLE hkey;
2615 ULONG value;
2617 attr.Length = sizeof(attr);
2618 attr.RootDirectory = 0;
2619 attr.ObjectName = &name_str;
2620 attr.Attributes = OBJ_CASE_INSENSITIVE;
2621 attr.SecurityDescriptor = NULL;
2622 attr.SecurityQualityOfService = NULL;
2623 RtlInitUnicodeString( &name_str, sessionW );
2625 if (NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr )) return;
2627 query_dword_option( hkey, globalflagW, &NtCurrentTeb()->Peb->NtGlobalFlag );
2629 query_dword_option( hkey, critsectW, &value );
2630 NtCurrentTeb()->Peb->CriticalSectionTimeout.QuadPart = (ULONGLONG)value * -10000000;
2632 query_dword_option( hkey, heapresW, &value );
2633 NtCurrentTeb()->Peb->HeapSegmentReserve = value;
2635 query_dword_option( hkey, heapcommitW, &value );
2636 NtCurrentTeb()->Peb->HeapSegmentCommit = value;
2638 query_dword_option( hkey, decommittotalW, &value );
2639 NtCurrentTeb()->Peb->HeapDeCommitTotalFreeThreshold = value;
2641 query_dword_option( hkey, decommitfreeW, &value );
2642 NtCurrentTeb()->Peb->HeapDeCommitFreeBlockThreshold = value;
2644 NtClose( hkey );
2648 /***********************************************************************
2649 * start_process
2651 static void start_process( void *kernel_start )
2653 call_thread_entry_point( kernel_start, NtCurrentTeb()->Peb );
2656 /******************************************************************
2657 * LdrInitializeThunk (NTDLL.@)
2660 void WINAPI LdrInitializeThunk( void *kernel_start, ULONG_PTR unknown2,
2661 ULONG_PTR unknown3, ULONG_PTR unknown4 )
2663 static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
2664 NTSTATUS status;
2665 WINE_MODREF *wm;
2666 LPCWSTR load_path;
2667 PEB *peb = NtCurrentTeb()->Peb;
2668 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
2670 if (main_exe_file) NtClose( main_exe_file ); /* at this point the main module is created */
2672 /* allocate the modref for the main exe (if not already done) */
2673 wm = get_modref( peb->ImageBaseAddress );
2674 assert( wm );
2675 if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
2677 ERR("%s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
2678 exit(1);
2681 peb->LoaderLock = &loader_section;
2682 peb->ProcessParameters->ImagePathName = wm->ldr.FullDllName;
2683 if (!peb->ProcessParameters->WindowTitle.Buffer)
2684 peb->ProcessParameters->WindowTitle = wm->ldr.FullDllName;
2685 version_init( wm->ldr.FullDllName.Buffer );
2687 LdrQueryImageFileExecutionOptions( &peb->ProcessParameters->ImagePathName, globalflagW,
2688 REG_DWORD, &peb->NtGlobalFlag, sizeof(peb->NtGlobalFlag), NULL );
2690 /* the main exe needs to be the first in the load order list */
2691 RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
2692 InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
2694 if ((status = virtual_alloc_thread_stack( NtCurrentTeb(), 0, 0 )) != STATUS_SUCCESS) goto error;
2695 if ((status = server_init_process_done()) != STATUS_SUCCESS) goto error;
2697 actctx_init();
2698 load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2699 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
2700 if ((status = alloc_process_tls()) != STATUS_SUCCESS) goto error;
2701 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto error;
2702 heap_set_debug_flags( GetProcessHeap() );
2704 status = wine_call_on_stack( attach_process_dlls, wm, NtCurrentTeb()->Tib.StackBase );
2705 if (status != STATUS_SUCCESS) goto error;
2707 virtual_release_address_space( nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE );
2708 virtual_clear_thread_stack();
2709 wine_switch_to_stack( start_process, kernel_start, NtCurrentTeb()->Tib.StackBase );
2711 error:
2712 ERR( "Main exe initialization for %s failed, status %x\n",
2713 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), status );
2714 NtTerminateProcess( GetCurrentProcess(), status );
2718 /***********************************************************************
2719 * RtlImageDirectoryEntryToData (NTDLL.@)
2721 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
2723 const IMAGE_NT_HEADERS *nt;
2724 DWORD addr;
2726 if ((ULONG_PTR)module & 1) /* mapped as data file */
2728 module = (HMODULE)((ULONG_PTR)module & ~1);
2729 image = FALSE;
2731 if (!(nt = RtlImageNtHeader( module ))) return NULL;
2732 if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
2734 const IMAGE_NT_HEADERS64 *nt64 = (const IMAGE_NT_HEADERS64 *)nt;
2736 if (dir >= nt64->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2737 if (!(addr = nt64->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2738 *size = nt64->OptionalHeader.DataDirectory[dir].Size;
2739 if (image || addr < nt64->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2741 else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
2743 const IMAGE_NT_HEADERS32 *nt32 = (const IMAGE_NT_HEADERS32 *)nt;
2745 if (dir >= nt32->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2746 if (!(addr = nt32->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2747 *size = nt32->OptionalHeader.DataDirectory[dir].Size;
2748 if (image || addr < nt32->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2750 else return NULL;
2752 /* not mapped as image, need to find the section containing the virtual address */
2753 return RtlImageRvaToVa( nt, module, addr, NULL );
2757 /***********************************************************************
2758 * RtlImageRvaToSection (NTDLL.@)
2760 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
2761 HMODULE module, DWORD rva )
2763 int i;
2764 const IMAGE_SECTION_HEADER *sec;
2766 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
2767 nt->FileHeader.SizeOfOptionalHeader);
2768 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
2770 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2771 return (PIMAGE_SECTION_HEADER)sec;
2773 return NULL;
2777 /***********************************************************************
2778 * RtlImageRvaToVa (NTDLL.@)
2780 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
2781 DWORD rva, IMAGE_SECTION_HEADER **section )
2783 IMAGE_SECTION_HEADER *sec;
2785 if (section && *section) /* try this section first */
2787 sec = *section;
2788 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2789 goto found;
2791 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
2792 found:
2793 if (section) *section = sec;
2794 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
2798 /***********************************************************************
2799 * RtlPcToFileHeader (NTDLL.@)
2801 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
2803 LDR_MODULE *module;
2804 PVOID ret = NULL;
2806 RtlEnterCriticalSection( &loader_section );
2807 if (!LdrFindEntryForAddress( pc, &module )) ret = module->BaseAddress;
2808 RtlLeaveCriticalSection( &loader_section );
2809 *address = ret;
2810 return ret;
2814 /***********************************************************************
2815 * NtLoadDriver (NTDLL.@)
2816 * ZwLoadDriver (NTDLL.@)
2818 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
2820 FIXME("(%p), stub!\n",DriverServiceName);
2821 return STATUS_NOT_IMPLEMENTED;
2825 /***********************************************************************
2826 * NtUnloadDriver (NTDLL.@)
2827 * ZwUnloadDriver (NTDLL.@)
2829 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
2831 FIXME("(%p), stub!\n",DriverServiceName);
2832 return STATUS_NOT_IMPLEMENTED;
2836 /******************************************************************
2837 * DllMain (NTDLL.@)
2839 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
2841 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
2842 return TRUE;
2846 /******************************************************************
2847 * __wine_init_windows_dir (NTDLL.@)
2849 * Windows and system dir initialization once kernel32 has been loaded.
2851 void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
2853 PLIST_ENTRY mark, entry;
2854 LPWSTR buffer, p;
2856 strcpyW( user_shared_data->NtSystemRoot, windir );
2857 DIR_init_windows_dir( windir, sysdir );
2859 /* prepend the system dir to the name of the already created modules */
2860 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2861 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2863 LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
2865 assert( mod->Flags & LDR_WINE_INTERNAL );
2867 buffer = RtlAllocateHeap( GetProcessHeap(), 0,
2868 system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
2869 if (!buffer) continue;
2870 strcpyW( buffer, system_dir.Buffer );
2871 p = buffer + strlenW( buffer );
2872 if (p > buffer && p[-1] != '\\') *p++ = '\\';
2873 strcpyW( p, mod->FullDllName.Buffer );
2874 RtlInitUnicodeString( &mod->FullDllName, buffer );
2875 RtlInitUnicodeString( &mod->BaseDllName, p );
2880 /***********************************************************************
2881 * __wine_process_init
2883 void __wine_process_init(void)
2885 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
2887 WINE_MODREF *wm;
2888 NTSTATUS status;
2889 ANSI_STRING func_name;
2890 void (* DECLSPEC_NORETURN CDECL init_func)(void);
2892 main_exe_file = thread_init();
2894 /* retrieve current umask */
2895 FILE_umask = umask(0777);
2896 umask( FILE_umask );
2898 load_global_options();
2900 /* setup the load callback and create ntdll modref */
2901 wine_dll_set_callback( load_builtin_callback );
2903 if ((status = load_builtin_dll( NULL, kernel32W, 0, 0, &wm )) != STATUS_SUCCESS)
2905 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
2906 exit(1);
2908 RtlInitAnsiString( &func_name, "UnhandledExceptionFilter" );
2909 LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name, 0, (void **)&unhandled_exception_filter );
2911 RtlInitAnsiString( &func_name, "__wine_kernel_init" );
2912 if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
2913 0, (void **)&init_func )) != STATUS_SUCCESS)
2915 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status );
2916 exit(1);
2918 init_func();