1 /*
2 * Loader functions
3 *
4 * Copyright 1995, 2003 Alexandre Julliard
5 * Copyright 2002 Dmitry Timoshkov for CodeWeavers
6 *
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.
11 *
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.
16 *
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
20 */
21
22 #include "config.h"
23 #include "wine/port.h"
24
25 #include <assert.h>
26 #include <stdarg.h>
27 #ifdef HAVE_SYS_MMAN_H
28 # include <sys/mman.h>
29 #endif
30
31 #define NONAMELESSUNION
32 #define NONAMELESSSTRUCT
33
34 #include "ntstatus.h"
35 #define WIN32_NO_STATUS
36 #include "windef.h"
37 #include "winnt.h"
38 #include "winternl.h"
39
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"
47
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);
53
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)
57
58 typedef DWORD (CALLBACK *DLLENTRYPROC)(HMODULE,DWORD,LPVOID);
59
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 */
62
63 static const char * const reason_names[] =
64 {
65 "PROCESS_DETACH",
66 "PROCESS_ATTACH",
67 "THREAD_ATTACH",
68 "THREAD_DETACH",
69 NULL, NULL, NULL, NULL,
70 "WINE_PREATTACH"
71 };
72
73 static const WCHAR dllW[] = {'.','d','l','l',0};
74
75 /* internal representation of 32bit modules. per process. */
76 typedef struct _wine_modref
77 {
78 LDR_MODULE ldr;
79 int nDeps;
80 struct _wine_modref **deps;
81 } WINE_MODREF;
82
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
86 {
87 const WCHAR *load_path;
88 const WCHAR *filename;
89 NTSTATUS status;
90 WINE_MODREF *wm;
91 };
92
93 static struct builtin_load_info default_load_info;
94 static struct builtin_load_info *builtin_load_info = &default_load_info;
95
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
101 UNICODE_STRING windows_dir = { 0, 0, NULL }; /* windows directory */
102 UNICODE_STRING system_dir = { 0, 0, NULL }; /* system directory */
103
104 static RTL_CRITICAL_SECTION loader_section;
105 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
106 {
107 0, 0, &loader_section,
108 { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
109 0, 0, { (DWORD_PTR)(__FILE__ ": loader_section") }
110 };
111 static RTL_CRITICAL_SECTION loader_section = { &critsect_debug, -1, 0, 0, 0, 0 };
112
113 static WINE_MODREF *cached_modref;
114 static WINE_MODREF *current_modref;
115 static WINE_MODREF *last_failed_modref;
116
117 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm );
118 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved );
119 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
120 DWORD exp_size, const char *name, int hint, LPCWSTR load_path );
121
122 /* convert PE image VirtualAddress to Real Address */
123 static inline void *get_rva( HMODULE module, DWORD va )
124 {
125 return (void *)((char *)module + va);
126 }
127
128 /* check whether the file name contains a path */
129 static inline int contains_path( LPCWSTR name )
130 {
131 return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
132 }
133
134 /* convert from straight ASCII to Unicode without depending on the current codepage */
135 static inline void ascii_to_unicode( WCHAR *dst, const char *src, size_t len )
136 {
137 while (len--) *dst++ = (unsigned char)*src++;
138 }
139
140
141 /*************************************************************************
142 * call_dll_entry_point
143 *
144 * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
145 * their entry point, so we need a small asm wrapper.
146 */
147 #ifdef __i386__
148 extern BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module, UINT reason, void *reserved );
149 __ASM_GLOBAL_FUNC(call_dll_entry_point,
150 "pushl %ebp\n\t"
151 __ASM_CFI(".cfi_adjust_cfa_offset 4\n\t")
152 __ASM_CFI(".cfi_rel_offset %ebp,0\n\t")
153 "movl %esp,%ebp\n\t"
154 __ASM_CFI(".cfi_def_cfa_register %ebp\n\t")
155 "pushl %ebx\n\t"
156 __ASM_CFI(".cfi_rel_offset %ebx,-4\n\t")
157 "subl $8,%esp\n\t"
158 "pushl 20(%ebp)\n\t"
159 "pushl 16(%ebp)\n\t"
160 "pushl 12(%ebp)\n\t"
161 "movl 8(%ebp),%eax\n\t"
162 "call *%eax\n\t"
163 "leal -4(%ebp),%esp\n\t"
164 "popl %ebx\n\t"
165 __ASM_CFI(".cfi_same_value %ebx\n\t")
166 "popl %ebp\n\t"
167 __ASM_CFI(".cfi_def_cfa %esp,4\n\t")
168 __ASM_CFI(".cfi_same_value %ebp\n\t")
169 "ret" )
170 #else /* __i386__ */
171 static inline BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module,
172 UINT reason, void *reserved )
173 {
174 return proc( module, reason, reserved );
175 }
176 #endif /* __i386__ */
177
178
179 #if defined(__i386__) || defined(__x86_64__)
180 /*************************************************************************
181 * stub_entry_point
182 *
183 * Entry point for stub functions.
184 */
185 static void stub_entry_point( const char *dll, const char *name, void *ret_addr )
186 {
187 EXCEPTION_RECORD rec;
188
189 rec.ExceptionCode = EXCEPTION_WINE_STUB;
190 rec.ExceptionFlags = EH_NONCONTINUABLE;
191 rec.ExceptionRecord = NULL;
192 rec.ExceptionAddress = ret_addr;
193 rec.NumberParameters = 2;
194 rec.ExceptionInformation[0] = (ULONG_PTR)dll;
195 rec.ExceptionInformation[1] = (ULONG_PTR)name;
196 for (;;) RtlRaiseException( &rec );
197 }
198
199
200 #include "pshpack1.h"
201 #ifdef __i386__
202 struct stub
203 {
204 BYTE pushl1; /* pushl $name */
205 const char *name;
206 BYTE pushl2; /* pushl $dll */
207 const char *dll;
208 BYTE call; /* call stub_entry_point */
209 DWORD entry;
210 };
211 #else
212 struct stub
213 {
214 BYTE movq_rdi[2]; /* movq $dll,%rdi */
215 const char *dll;
216 BYTE movq_rsi[2]; /* movq $name,%rsi */
217 const char *name;
218 BYTE movq_rsp_rdx[4]; /* movq (%rsp),%rdx */
219 BYTE movq_rax[2]; /* movq $entry, %rax */
220 const void* entry;
221 BYTE jmpq_rax[2]; /* jmp %rax */
222 };
223 #endif
224 #include "poppack.h"
225
226 /*************************************************************************
227 * allocate_stub
228 *
229 * Allocate a stub entry point.
230 */
231 static ULONG_PTR allocate_stub( const char *dll, const char *name )
232 {
233 #define MAX_SIZE 65536
234 static struct stub *stubs;
235 static unsigned int nb_stubs;
236 struct stub *stub;
237
238 if (nb_stubs >= MAX_SIZE / sizeof(*stub)) return 0xdeadbeef;
239
240 if (!stubs)
241 {
242 SIZE_T size = MAX_SIZE;
243 if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs, 0, &size,
244 MEM_COMMIT, PAGE_EXECUTE_WRITECOPY ) != STATUS_SUCCESS)
245 return 0xdeadbeef;
246 }
247 stub = &stubs[nb_stubs++];
248 #ifdef __i386__
249 stub->pushl1 = 0x68; /* pushl $name */
250 stub->name = name;
251 stub->pushl2 = 0x68; /* pushl $dll */
252 stub->dll = dll;
253 stub->call = 0xe8; /* call stub_entry_point */
254 stub->entry = (BYTE *)stub_entry_point - (BYTE *)(&stub->entry + 1);
255 #else
256 stub->movq_rdi[0] = 0x48; /* movq $dll,%rdi */
257 stub->movq_rdi[1] = 0xbf;
258 stub->dll = dll;
259 stub->movq_rsi[0] = 0x48; /* movq $name,%rsi */
260 stub->movq_rsi[1] = 0xbe;
261 stub->name = name;
262 stub->movq_rsp_rdx[0] = 0x48; /* movq (%rsp),%rdx */
263 stub->movq_rsp_rdx[1] = 0x8b;
264 stub->movq_rsp_rdx[2] = 0x14;
265 stub->movq_rsp_rdx[3] = 0x24;
266 stub->movq_rax[0] = 0x48; /* movq $entry, %rax */
267 stub->movq_rax[1] = 0xb8;
268 stub->entry = stub_entry_point;
269 stub->jmpq_rax[0] = 0xff; /* jmp %rax */
270 stub->jmpq_rax[1] = 0xe0;
271 #endif
272 return (ULONG_PTR)stub;
273 }
274
275 #else /* __i386__ */
276 static inline ULONG_PTR allocate_stub( const char *dll, const char *name ) { return 0xdeadbeef; }
277 #endif /* __i386__ */
278
279
280 /*************************************************************************
281 * get_modref
282 *
283 * Looks for the referenced HMODULE in the current process
284 * The loader_section must be locked while calling this function.
285 */
286 static WINE_MODREF *get_modref( HMODULE hmod )
287 {
288 PLIST_ENTRY mark, entry;
289 PLDR_MODULE mod;
290
291 if (cached_modref && cached_modref->ldr.BaseAddress == hmod) return cached_modref;
292
293 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
294 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
295 {
296 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
297 if (mod->BaseAddress == hmod)
298 return cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
299 if (mod->BaseAddress > (void*)hmod) break;
300 }
301 return NULL;
302 }
303
304
305 /**********************************************************************
306 * find_basename_module
307 *
308 * Find a module from its base name.
309 * The loader_section must be locked while calling this function
310 */
311 static WINE_MODREF *find_basename_module( LPCWSTR name )
312 {
313 PLIST_ENTRY mark, entry;
314
315 if (cached_modref && !strcmpiW( name, cached_modref->ldr.BaseDllName.Buffer ))
316 return cached_modref;
317
318 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
319 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
320 {
321 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
322 if (!strcmpiW( name, mod->BaseDllName.Buffer ))
323 {
324 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
325 return cached_modref;
326 }
327 }
328 return NULL;
329 }
330
331
332 /**********************************************************************
333 * find_fullname_module
334 *
335 * Find a module from its full path name.
336 * The loader_section must be locked while calling this function
337 */
338 static WINE_MODREF *find_fullname_module( LPCWSTR name )
339 {
340 PLIST_ENTRY mark, entry;
341
342 if (cached_modref && !strcmpiW( name, cached_modref->ldr.FullDllName.Buffer ))
343 return cached_modref;
344
345 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
346 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
347 {
348 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
349 if (!strcmpiW( name, mod->FullDllName.Buffer ))
350 {
351 cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
352 return cached_modref;
353 }
354 }
355 return NULL;
356 }
357
358
359 /*************************************************************************
360 * find_forwarded_export
361 *
362 * Find the final function pointer for a forwarded function.
363 * The loader_section must be locked while calling this function.
364 */
365 static FARPROC find_forwarded_export( HMODULE module, const char *forward, LPCWSTR load_path )
366 {
367 const IMAGE_EXPORT_DIRECTORY *exports;
368 DWORD exp_size;
369 WINE_MODREF *wm;
370 WCHAR mod_name[32];
371 const char *end = strrchr(forward, '.');
372 FARPROC proc = NULL;
373
374 if (!end) return NULL;
375 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name)) return NULL;
376 ascii_to_unicode( mod_name, forward, end - forward );
377 mod_name[end - forward] = 0;
378 if (!strchrW( mod_name, '.' ))
379 {
380 if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name) - sizeof(dllW)) return NULL;
381 memcpy( mod_name + (end - forward), dllW, sizeof(dllW) );
382 }
383
384 if (!(wm = find_basename_module( mod_name )))
385 {
386 TRACE( "delay loading %s for '%s'\n", debugstr_w(mod_name), forward );
387 if (load_dll( load_path, mod_name, 0, &wm ) == STATUS_SUCCESS &&
388 !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
389 {
390 if (process_attach( wm, NULL ) != STATUS_SUCCESS)
391 {
392 LdrUnloadDll( wm->ldr.BaseAddress );
393 wm = NULL;
394 }
395 }
396
397 if (!wm)
398 {
399 ERR( "module not found for forward '%s' used by %s\n",
400 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer) );
401 return NULL;
402 }
403 }
404 if ((exports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
405 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
406 proc = find_named_export( wm->ldr.BaseAddress, exports, exp_size, end + 1, -1, load_path );
407
408 if (!proc)
409 {
410 ERR("function not found for forward '%s' used by %s."
411 " If you are using builtin %s, try using the native one instead.\n",
412 forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer),
413 debugstr_w(get_modref(module)->ldr.BaseDllName.Buffer) );
414 }
415 return proc;
416 }
417
418
419 /*************************************************************************
420 * find_ordinal_export
421 *
422 * Find an exported function by ordinal.
423 * The exports base must have been subtracted from the ordinal already.
424 * The loader_section must be locked while calling this function.
425 */
426 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
427 DWORD exp_size, DWORD ordinal, LPCWSTR load_path )
428 {
429 FARPROC proc;
430 const DWORD *functions = get_rva( module, exports->AddressOfFunctions );
431
432 if (ordinal >= exports->NumberOfFunctions)
433 {
434 TRACE(" ordinal %d out of range!\n", ordinal + exports->Base );
435 return NULL;
436 }
437 if (!functions[ordinal]) return NULL;
438
439 proc = get_rva( module, functions[ordinal] );
440
441 /* if the address falls into the export dir, it's a forward */
442 if (((const char *)proc >= (const char *)exports) &&
443 ((const char *)proc < (const char *)exports + exp_size))
444 return find_forwarded_export( module, (const char *)proc, load_path );
445
446 if (TRACE_ON(snoop))
447 {
448 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
449 proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
450 }
451 if (TRACE_ON(relay))
452 {
453 const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
454 proc = RELAY_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
455 }
456 return proc;
457 }
458
459
460 /*************************************************************************
461 * find_named_export
462 *
463 * Find an exported function by name.
464 * The loader_section must be locked while calling this function.
465 */
466 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
467 DWORD exp_size, const char *name, int hint, LPCWSTR load_path )
468 {
469 const WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
470 const DWORD *names = get_rva( module, exports->AddressOfNames );
471 int min = 0, max = exports->NumberOfNames - 1;
472
473 /* first check the hint */
474 if (hint >= 0 && hint <= max)
475 {
476 char *ename = get_rva( module, names[hint] );
477 if (!strcmp( ename, name ))
478 return find_ordinal_export( module, exports, exp_size, ordinals[hint], load_path );
479 }
480
481 /* then do a binary search */
482 while (min <= max)
483 {
484 int res, pos = (min + max) / 2;
485 char *ename = get_rva( module, names[pos] );
486 if (!(res = strcmp( ename, name )))
487 return find_ordinal_export( module, exports, exp_size, ordinals[pos], load_path );
488 if (res > 0) max = pos - 1;
489 else min = pos + 1;
490 }
491 return NULL;
492
493 }
494
495
496 /*************************************************************************
497 * import_dll
498 *
499 * Import the dll specified by the given import descriptor.
500 * The loader_section must be locked while calling this function.
501 */
502 static WINE_MODREF *import_dll( HMODULE module, const IMAGE_IMPORT_DESCRIPTOR *descr, LPCWSTR load_path )
503 {
504 NTSTATUS status;
505 WINE_MODREF *wmImp;
506 HMODULE imp_mod;
507 const IMAGE_EXPORT_DIRECTORY *exports;
508 DWORD exp_size;
509 const IMAGE_THUNK_DATA *import_list;
510 IMAGE_THUNK_DATA *thunk_list;
511 WCHAR buffer[32];
512 const char *name = get_rva( module, descr->Name );
513 DWORD len = strlen(name);
514 PVOID protect_base;
515 SIZE_T protect_size = 0;
516 DWORD protect_old;
517
518 thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
519 if (descr->u.OriginalFirstThunk)
520 import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
521 else
522 import_list = thunk_list;
523
524 while (len && name[len-1] == ' ') len--; /* remove trailing spaces */
525
526 if (len * sizeof(WCHAR) < sizeof(buffer))
527 {
528 ascii_to_unicode( buffer, name, len );
529 buffer[len] = 0;
530 status = load_dll( load_path, buffer, 0, &wmImp );
531 }
532 else /* need to allocate a larger buffer */
533 {
534 WCHAR *ptr = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) );
535 if (!ptr) return NULL;
536 ascii_to_unicode( ptr, name, len );
537 ptr[len] = 0;
538 status = load_dll( load_path, ptr, 0, &wmImp );
539 RtlFreeHeap( GetProcessHeap(), 0, ptr );
540 }
541
542 if (status)
543 {
544 if (status == STATUS_DLL_NOT_FOUND)
545 ERR("Library %s (which is needed by %s) not found\n",
546 name, debugstr_w(current_modref->ldr.FullDllName.Buffer));
547 else
548 ERR("Loading library %s (which is needed by %s) failed (error %x).\n",
549 name, debugstr_w(current_modref->ldr.FullDllName.Buffer), status);
550 return NULL;
551 }
552
553 /* unprotect the import address table since it can be located in
554 * readonly section */
555 while (import_list[protect_size].u1.Ordinal) protect_size++;
556 protect_base = thunk_list;
557 protect_size *= sizeof(*thunk_list);
558 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base,
559 &protect_size, PAGE_WRITECOPY, &protect_old );
560
561 imp_mod = wmImp->ldr.BaseAddress;
562 exports = RtlImageDirectoryEntryToData( imp_mod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
563
564 if (!exports)
565 {
566 /* set all imported function to deadbeef */
567 while (import_list->u1.Ordinal)
568 {
569 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
570 {
571 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
572 WARN("No implementation for %s.%d", name, ordinal );
573 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
574 }
575 else
576 {
577 IMAGE_IMPORT_BY_NAME *pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
578 WARN("No implementation for %s.%s", name, pe_name->Name );
579 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
580 }
581 WARN(" imported from %s, allocating stub %p\n",
582 debugstr_w(current_modref->ldr.FullDllName.Buffer),
583 (void *)thunk_list->u1.Function );
584 import_list++;
585 thunk_list++;
586 }
587 goto done;
588 }
589
590 while (import_list->u1.Ordinal)
591 {
592 if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
593 {
594 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
595
596 thunk_list->u1.Function = (ULONG_PTR)find_ordinal_export( imp_mod, exports, exp_size,
597 ordinal - exports->Base, load_path );
598 if (!thunk_list->u1.Function)
599 {
600 thunk_list->u1.Function = allocate_stub( name, IntToPtr(ordinal) );
601 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
602 name, ordinal, debugstr_w(current_modref->ldr.FullDllName.Buffer),
603 (void *)thunk_list->u1.Function );
604 }
605 TRACE_(imports)("--- Ordinal %s.%d = %p\n", name, ordinal, (void *)thunk_list->u1.Function );
606 }
607 else /* import by name */
608 {
609 IMAGE_IMPORT_BY_NAME *pe_name;
610 pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
611 thunk_list->u1.Function = (ULONG_PTR)find_named_export( imp_mod, exports, exp_size,
612 (const char*)pe_name->Name,
613 pe_name->Hint, load_path );
614 if (!thunk_list->u1.Function)
615 {
616 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
617 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
618 name, pe_name->Name, debugstr_w(current_modref->ldr.FullDllName.Buffer),
619 (void *)thunk_list->u1.Function );
620 }
621 TRACE_(imports)("--- %s %s.%d = %p\n",
622 pe_name->Name, name, pe_name->Hint, (void *)thunk_list->u1.Function);
623 }
624 import_list++;
625 thunk_list++;
626 }
627
628 done:
629 /* restore old protection of the import address table */
630 NtProtectVirtualMemory( NtCurrentProcess(), &protect_base, &protect_size, protect_old, NULL );
631 return wmImp;
632 }
633
634
635 /***********************************************************************
636 * create_module_activation_context
637 */
638 static NTSTATUS create_module_activation_context( LDR_MODULE *module )
639 {
640 NTSTATUS status;
641 LDR_RESOURCE_INFO info;
642 const IMAGE_RESOURCE_DATA_ENTRY *entry;
643
644 info.Type = RT_MANIFEST;
645 info.Name = ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
646 info.Language = 0;
647 if (!(status = LdrFindResource_U( module->BaseAddress, &info, 3, &entry )))
648 {
649 ACTCTXW ctx;
650 ctx.cbSize = sizeof(ctx);
651 ctx.lpSource = NULL;
652 ctx.dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID | ACTCTX_FLAG_HMODULE_VALID;
653 ctx.hModule = module->BaseAddress;
654 ctx.lpResourceName = (LPCWSTR)ISOLATIONAWARE_MANIFEST_RESOURCE_ID;
655 status = RtlCreateActivationContext( &module->ActivationContext, &ctx );
656 }
657 return status;
658 }
659
660
661 /****************************************************************
662 * fixup_imports
663 *
664 * Fixup all imports of a given module.
665 * The loader_section must be locked while calling this function.
666 */
667 static NTSTATUS fixup_imports( WINE_MODREF *wm, LPCWSTR load_path )
668 {
669 int i, nb_imports;
670 const IMAGE_IMPORT_DESCRIPTOR *imports;
671 WINE_MODREF *prev;
672 DWORD size;
673 NTSTATUS status;
674 ULONG_PTR cookie;
675
676 if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS; /* already done */
677 wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
678
679 if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
680 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
681 return STATUS_SUCCESS;
682
683 nb_imports = 0;
684 while (imports[nb_imports].Name && imports[nb_imports].FirstThunk) nb_imports++;
685
686 if (!nb_imports) return STATUS_SUCCESS; /* no imports */
687
688 if (!create_module_activation_context( &wm->ldr ))
689 RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
690
691 /* Allocate module dependency list */
692 wm->nDeps = nb_imports;
693 wm->deps = RtlAllocateHeap( GetProcessHeap(), 0, nb_imports*sizeof(WINE_MODREF *) );
694
695 /* load the imported modules. They are automatically
696 * added to the modref list of the process.
697 */
698 prev = current_modref;
699 current_modref = wm;
700 status = STATUS_SUCCESS;
701 for (i = 0; i < nb_imports; i++)
702 {
703 if (!(wm->deps[i] = import_dll( wm->ldr.BaseAddress, &imports[i], load_path )))
704 status = STATUS_DLL_NOT_FOUND;
705 }
706 current_modref = prev;
707 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
708 return status;
709 }
710
711
712 /*************************************************************************
713 * is_dll_native_subsystem
714 *
715 * Check if dll is a proper native driver.
716 * Some dlls (corpol.dll from IE6 for instance) are incorrectly marked as native
717 * while being perfectly normal DLLs. This heuristic should catch such breakages.
718 */
719 static BOOL is_dll_native_subsystem( HMODULE module, const IMAGE_NT_HEADERS *nt, LPCWSTR filename )
720 {
721 static const WCHAR ntdllW[] = {'n','t','d','l','l','.','d','l','l',0};
722 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
723 const IMAGE_IMPORT_DESCRIPTOR *imports;
724 DWORD i, size;
725 WCHAR buffer[16];
726
727 if (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_NATIVE) return FALSE;
728 if (nt->OptionalHeader.SectionAlignment < getpagesize()) return TRUE;
729
730 if ((imports = RtlImageDirectoryEntryToData( module, TRUE,
731 IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
732 {
733 for (i = 0; imports[i].Name; i++)
734 {
735 const char *name = get_rva( module, imports[i].Name );
736 DWORD len = strlen(name);
737 if (len * sizeof(WCHAR) >= sizeof(buffer)) continue;
738 ascii_to_unicode( buffer, name, len + 1 );
739 if (!strcmpiW( buffer, ntdllW ) || !strcmpiW( buffer, kernel32W ))
740 {
741 TRACE( "%s imports %s, assuming not native\n", debugstr_w(filename), debugstr_w(buffer) );
742 return FALSE;
743 }
744 }
745 }
746 return TRUE;
747 }
748
749
750 /*************************************************************************
751 * alloc_module
752 *
753 * Allocate a WINE_MODREF structure and add it to the process list
754 * The loader_section must be locked while calling this function.
755 */
756 static WINE_MODREF *alloc_module( HMODULE hModule, LPCWSTR filename )
757 {
758 WINE_MODREF *wm;
759 const WCHAR *p;
760 const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
761 PLIST_ENTRY entry, mark;
762
763 if (!(wm = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm) ))) return NULL;
764
765 wm->nDeps = 0;
766 wm->deps = NULL;
767
768 wm->ldr.BaseAddress = hModule;
769 wm->ldr.EntryPoint = NULL;
770 wm->ldr.SizeOfImage = nt->OptionalHeader.SizeOfImage;
771 wm->ldr.Flags = LDR_DONT_RESOLVE_REFS;
772 wm->ldr.LoadCount = 1;
773 wm->ldr.TlsIndex = -1;
774 wm->ldr.SectionHandle = NULL;
775 wm->ldr.CheckSum = 0;
776 wm->ldr.TimeDateStamp = 0;
777 wm->ldr.ActivationContext = 0;
778
779 RtlCreateUnicodeString( &wm->ldr.FullDllName, filename );
780 if ((p = strrchrW( wm->ldr.FullDllName.Buffer, '\\' ))) p++;
781 else p = wm->ldr.FullDllName.Buffer;
782 RtlInitUnicodeString( &wm->ldr.BaseDllName, p );
783
784 if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && !is_dll_native_subsystem( hModule, nt, p ))
785 {
786 wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
787 if (nt->OptionalHeader.AddressOfEntryPoint)
788 wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
789 }
790
791 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
792 &wm->ldr.InLoadOrderModuleList);
793
794 /* insert module in MemoryList, sorted in increasing base addresses */
795 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
796 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
797 {
798 if (CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList)->BaseAddress > wm->ldr.BaseAddress)
799 break;
800 }
801 entry->Blink->Flink = &wm->ldr.InMemoryOrderModuleList;
802 wm->ldr.InMemoryOrderModuleList.Blink = entry->Blink;
803 wm->ldr.InMemoryOrderModuleList.Flink = entry;
804 entry->Blink = &wm->ldr.InMemoryOrderModuleList;
805
806 /* wait until init is called for inserting into this list */
807 wm->ldr.InInitializationOrderModuleList.Flink = NULL;
808 wm->ldr.InInitializationOrderModuleList.Blink = NULL;
809
810 if (!(nt->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
811 {
812 WARN( "disabling no-exec because of %s\n", debugstr_w(wm->ldr.BaseDllName.Buffer) );
813 VIRTUAL_SetForceExec( TRUE );
814 }
815 return wm;
816 }
817
818
819 /*************************************************************************
820 * alloc_process_tls
821 *
822 * Allocate the process-wide structure for module TLS storage.
823 */
824 static NTSTATUS alloc_process_tls(void)
825 {
826 PLIST_ENTRY mark, entry;
827 PLDR_MODULE mod;
828 const IMAGE_TLS_DIRECTORY *dir;
829 ULONG size, i;
830
831 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
832 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
833 {
834 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
835 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
836 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
837 continue;
838 size = (dir->EndAddressOfRawData - dir->StartAddressOfRawData) + dir->SizeOfZeroFill;
839 if (!size) continue;
840 tls_total_size += size;
841 tls_module_count++;
842 }
843 if (!tls_module_count) return STATUS_SUCCESS;
844
845 TRACE( "count %u size %u\n", tls_module_count, tls_total_size );
846
847 tls_dirs = RtlAllocateHeap( GetProcessHeap(), 0, tls_module_count * sizeof(*tls_dirs) );
848 if (!tls_dirs) return STATUS_NO_MEMORY;
849
850 for (i = 0, entry = mark->Flink; entry != mark; entry = entry->Flink)
851 {
852 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
853 if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
854 IMAGE_DIRECTORY_ENTRY_TLS, &size )))
855 continue;
856 tls_dirs[i] = dir;
857 *(DWORD *)dir->AddressOfIndex = i;
858 mod->TlsIndex = i;
859 mod->LoadCount = -1; /* can't unload it */
860 i++;
861 }
862 return STATUS_SUCCESS;
863 }
864
865
866 /*************************************************************************
867 * alloc_thread_tls
868 *
869 * Allocate the per-thread structure for module TLS storage.
870 */
871 static NTSTATUS alloc_thread_tls(void)
872 {
873 void **pointers;
874 char *data;
875 UINT i;
876
877 if (!tls_module_count) return STATUS_SUCCESS;
878
879 if (!(pointers = RtlAllocateHeap( GetProcessHeap(), 0,
880 tls_module_count * sizeof(*pointers) )))
881 return STATUS_NO_MEMORY;
882
883 if (!(data = RtlAllocateHeap( GetProcessHeap(), 0, tls_total_size )))
884 {
885 RtlFreeHeap( GetProcessHeap(), 0, pointers );
886 return STATUS_NO_MEMORY;
887 }
888
889 for (i = 0; i < tls_module_count; i++)
890 {
891 const IMAGE_TLS_DIRECTORY *dir = tls_dirs[i];
892 ULONG size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
893
894 TRACE( "thread %04x idx %d: %d/%d bytes from %p to %p\n",
895 GetCurrentThreadId(), i, size, dir->SizeOfZeroFill,
896 (void *)dir->StartAddressOfRawData, data );
897
898 pointers[i] = data;
899 memcpy( data, (void *)dir->StartAddressOfRawData, size );
900 data += size;
901 memset( data, 0, dir->SizeOfZeroFill );
902 data += dir->SizeOfZeroFill;
903 }
904 NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
905 return STATUS_SUCCESS;
906 }
907
908
909 /*************************************************************************
910 * call_tls_callbacks
911 */
912 static void call_tls_callbacks( HMODULE module, UINT reason )
913 {
914 const IMAGE_TLS_DIRECTORY *dir;
915 const PIMAGE_TLS_CALLBACK *callback;
916 ULONG dirsize;
917
918 dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
919 if (!dir || !dir->AddressOfCallBacks) return;
920
921 for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
922 {
923 if (TRACE_ON(relay))
924 DPRINTF("%04x:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
925 GetCurrentThreadId(), *callback, module, reason_names[reason] );
926 __TRY
927 {
928 (*callback)( module, reason, NULL );
929 }
930 __EXCEPT_ALL
931 {
932 if (TRACE_ON(relay))
933 DPRINTF("%04x:exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
934 GetCurrentThreadId(), callback, module, reason_names[reason] );
935 return;
936 }
937 __ENDTRY
938 if (TRACE_ON(relay))
939 DPRINTF("%04x:Ret TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
940 GetCurrentThreadId(), *callback, module, reason_names[reason] );
941 }
942 }
943
944
945 /*************************************************************************
946 * MODULE_InitDLL
947 */
948 static NTSTATUS MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
949 {
950 WCHAR mod_name[32];
951 NTSTATUS status = STATUS_SUCCESS;
952 DLLENTRYPROC entry = wm->ldr.EntryPoint;
953 void *module = wm->ldr.BaseAddress;
954 BOOL retv = TRUE;
955
956 /* Skip calls for modules loaded with special load flags */
957
958 if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return STATUS_SUCCESS;
959 if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.BaseAddress, reason );
960 if (!entry) return STATUS_SUCCESS;
961
962 if (TRACE_ON(relay))
963 {
964 size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
965 memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
966 mod_name[len / sizeof(WCHAR)] = 0;
967 DPRINTF("%04x:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
968 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
969 reason_names[reason], lpReserved );
970 }
971 else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
972 reason_names[reason], lpReserved );
973
974 __TRY
975 {
976 retv = call_dll_entry_point( entry, module, reason, lpReserved );
977 if (!retv)
978 status = STATUS_DLL_INIT_FAILED;
979 }
980 __EXCEPT_ALL
981 {
982 if (TRACE_ON(relay))
983 DPRINTF("%04x:exception in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
984 GetCurrentThreadId(), entry, module, reason_names[reason], lpReserved );
985 status = GetExceptionCode();
986 }
987 __ENDTRY
988
989 /* The state of the module list may have changed due to the call
990 to the dll. We cannot assume that this module has not been
991 deleted. */
992 if (TRACE_ON(relay))
993 DPRINTF("%04x:Ret PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
994 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
995 reason_names[reason], lpReserved, retv );
996 else TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
997
998 return status;
999 }
1000
1001
1002 /*************************************************************************
1003 * process_attach
1004 *
1005 * Send the process attach notification to all DLLs the given module
1006 * depends on (recursively). This is somewhat complicated due to the fact that
1007 *
1008 * - we have to respect the module dependencies, i.e. modules implicitly
1009 * referenced by another module have to be initialized before the module
1010 * itself can be initialized
1011 *
1012 * - the initialization routine of a DLL can itself call LoadLibrary,
1013 * thereby introducing a whole new set of dependencies (even involving
1014 * the 'old' modules) at any time during the whole process
1015 *
1016 * (Note that this routine can be recursively entered not only directly
1017 * from itself, but also via LoadLibrary from one of the called initialization
1018 * routines.)
1019 *
1020 * Furthermore, we need to rearrange the main WINE_MODREF list to allow
1021 * the process *detach* notifications to be sent in the correct order.
1022 * This must not only take into account module dependencies, but also
1023 * 'hidden' dependencies created by modules calling LoadLibrary in their
1024 * attach notification routine.
1025 *
1026 * The strategy is rather simple: we move a WINE_MODREF to the head of the
1027 * list after the attach notification has returned. This implies that the
1028 * detach notifications are called in the reverse of the sequence the attach
1029 * notifications *returned*.
1030 *
1031 * The loader_section must be locked while calling this function.
1032 */
1033 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
1034 {
1035 NTSTATUS status = STATUS_SUCCESS;
1036 ULONG_PTR cookie;
1037 int i;
1038
1039 if (process_detaching) return status;
1040
1041 /* prevent infinite recursion in case of cyclical dependencies */
1042 if ( ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
1043 || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
1044 return status;
1045
1046 TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1047
1048 /* Tag current MODREF to prevent recursive loop */
1049 wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
1050 if (lpReserved) wm->ldr.LoadCount = -1; /* pin it if imported by the main exe */
1051 if (wm->ldr.ActivationContext) RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
1052
1053 /* Recursively attach all DLLs this one depends on */
1054 for ( i = 0; i < wm->nDeps; i++ )
1055 {
1056 if (!wm->deps[i]) continue;
1057 if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
1058 }
1059
1060 /* Call DLL entry point */
1061 if (status == STATUS_SUCCESS)
1062 {
1063 WINE_MODREF *prev = current_modref;
1064 current_modref = wm;
1065 status = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
1066 if (status == STATUS_SUCCESS)
1067 wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
1068 else
1069 {
1070 /* point to the name so LdrInitializeThunk can print it */
1071 last_failed_modref = wm;
1072 WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
1073 }
1074 current_modref = prev;
1075 }
1076
1077 if (!wm->ldr.InInitializationOrderModuleList.Flink)
1078 InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
1079 &wm->ldr.InInitializationOrderModuleList);
1080
1081 if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
1082 /* Remove recursion flag */
1083 wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
1084
1085 TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1086 return status;
1087 }
1088
1089
1090 /**********************************************************************
1091 * attach_implicitly_loaded_dlls
1092 *
1093 * Attach to the (builtin) dlls that have been implicitly loaded because
1094 * of a dependency at the Unix level, but not imported at the Win32 level.
1095 */
1096 static void attach_implicitly_loaded_dlls( LPVOID reserved )
1097 {
1098 for (;;)
1099 {
1100 PLIST_ENTRY mark, entry;
1101
1102 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1103 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1104 {
1105 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1106
1107 if (mod->Flags & (LDR_LOAD_IN_PROGRESS | LDR_PROCESS_ATTACHED)) continue;
1108 TRACE( "found implicitly loaded %s, attaching to it\n",
1109 debugstr_w(mod->BaseDllName.Buffer));
1110 process_attach( CONTAINING_RECORD(mod, WINE_MODREF, ldr), reserved );
1111 break; /* restart the search from the start */
1112 }
1113 if (entry == mark) break; /* nothing found */
1114 }
1115 }
1116
1117
1118 /*************************************************************************
1119 * process_detach
1120 *
1121 * Send DLL process detach notifications. See the comment about calling
1122 * sequence at process_attach. Unless the bForceDetach flag
1123 * is set, only DLLs with zero refcount are notified.
1124 */
1125 static void process_detach( BOOL bForceDetach, LPVOID lpReserved )
1126 {
1127 PLIST_ENTRY mark, entry;
1128 PLDR_MODULE mod;
1129
1130 RtlEnterCriticalSection( &loader_section );
1131 if (bForceDetach) process_detaching = 1;
1132 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1133 do
1134 {
1135 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1136 {
1137 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1138 InInitializationOrderModuleList);
1139 /* Check whether to detach this DLL */
1140 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1141 continue;
1142 if ( mod->LoadCount && !bForceDetach )
1143 continue;
1144
1145 /* Call detach notification */
1146 mod->Flags &= ~LDR_PROCESS_ATTACHED;
1147 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1148 DLL_PROCESS_DETACH, lpReserved );
1149
1150 /* Restart at head of WINE_MODREF list, as entries might have
1151 been added and/or removed while performing the call ... */
1152 break;
1153 }
1154 } while (entry != mark);
1155
1156 RtlLeaveCriticalSection( &loader_section );
1157 }
1158
1159 /*************************************************************************
1160 * MODULE_DllThreadAttach
1161 *
1162 * Send DLL thread attach notifications. These are sent in the
1163 * reverse sequence of process detach notification.
1164 *
1165 */
1166 NTSTATUS MODULE_DllThreadAttach( LPVOID lpReserved )
1167 {
1168 PLIST_ENTRY mark, entry;
1169 PLDR_MODULE mod;
1170 NTSTATUS status;
1171
1172 /* don't do any attach calls if process is exiting */
1173 if (process_detaching) return STATUS_SUCCESS;
1174 /* FIXME: there is still a race here */
1175
1176 RtlEnterCriticalSection( &loader_section );
1177
1178 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto done;
1179
1180 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1181 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1182 {
1183 mod = CONTAINING_RECORD(entry, LDR_MODULE,
1184 InInitializationOrderModuleList);
1185 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1186 continue;
1187 if ( mod->Flags & LDR_NO_DLL_CALLS )
1188 continue;
1189
1190 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1191 DLL_THREAD_ATTACH, lpReserved );
1192 }
1193
1194 done:
1195 RtlLeaveCriticalSection( &loader_section );
1196 return status;
1197 }
1198
1199 /******************************************************************
1200 * LdrDisableThreadCalloutsForDll (NTDLL.@)
1201 *
1202 */
1203 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1204 {
1205 WINE_MODREF *wm;
1206 NTSTATUS ret = STATUS_SUCCESS;
1207
1208 RtlEnterCriticalSection( &loader_section );
1209
1210 wm = get_modref( hModule );
1211 if (!wm || wm->ldr.TlsIndex != -1)
1212 ret = STATUS_DLL_NOT_FOUND;
1213 else
1214 wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1215
1216 RtlLeaveCriticalSection( &loader_section );
1217
1218 return ret;
1219 }
1220
1221 /******************************************************************
1222 * LdrFindEntryForAddress (NTDLL.@)
1223 *
1224 * The loader_section must be locked while calling this function
1225 */
1226 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
1227 {
1228 PLIST_ENTRY mark, entry;
1229 PLDR_MODULE mod;
1230
1231 mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1232 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1233 {
1234 mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
1235 if (mod->BaseAddress <= addr &&
1236 (const char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
1237 {
1238 *pmod = mod;
1239 return STATUS_SUCCESS;
1240 }
1241 if (mod->BaseAddress > addr) break;
1242 }
1243 return STATUS_NO_MORE_ENTRIES;
1244 }
1245
1246 /******************************************************************
1247 * LdrLockLoaderLock (NTDLL.@)
1248 *
1249 * Note: flags are not implemented.
1250 * Flag 0x01 is used to raise exceptions on errors.
1251 * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
1252 */
1253 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG *magic )
1254 {
1255 if (flags) FIXME( "flags %x not supported\n", flags );
1256
1257 if (result) *result = 1;
1258 if (!magic) return STATUS_INVALID_PARAMETER_3;
1259 RtlEnterCriticalSection( &loader_section );
1260 *magic = GetCurrentThreadId();
1261 return STATUS_SUCCESS;
1262 }
1263
1264
1265 /******************************************************************
1266 * LdrUnlockLoaderUnlock (NTDLL.@)
1267 */
1268 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG magic )
1269 {
1270 if (magic)
1271 {
1272 if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1273 RtlLeaveCriticalSection( &loader_section );
1274 }
1275 return STATUS_SUCCESS;
1276 }
1277
1278
1279 /******************************************************************
1280 * LdrGetProcedureAddress (NTDLL.@)
1281 */
1282 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1283 ULONG ord, PVOID *address)
1284 {
1285 IMAGE_EXPORT_DIRECTORY *exports;
1286 DWORD exp_size;
1287 NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1288
1289 RtlEnterCriticalSection( &loader_section );
1290
1291 /* check if the module itself is invalid to return the proper error */
1292 if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1293 else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1294 IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1295 {
1296 LPCWSTR load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1297 void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1, load_path )
1298 : find_ordinal_export( module, exports, exp_size, ord - exports->Base, load_path );
1299 if (proc)
1300 {
1301 *address = proc;
1302 ret = STATUS_SUCCESS;
1303 }
1304 }
1305
1306 RtlLeaveCriticalSection( &loader_section );
1307 return ret;
1308 }
1309
1310
1311 /***********************************************************************
1312 * is_fake_dll
1313 *
1314 * Check if a loaded native dll is a Wine fake dll.
1315 */
1316 static BOOL is_fake_dll( HANDLE handle )
1317 {
1318 static const char fakedll_signature[] = "Wine placeholder DLL";
1319 char buffer[sizeof(IMAGE_DOS_HEADER) + sizeof(fakedll_signature)];
1320 const IMAGE_DOS_HEADER *dos = (const IMAGE_DOS_HEADER *)buffer;
1321 IO_STATUS_BLOCK io;
1322 LARGE_INTEGER offset;
1323
1324 offset.QuadPart = 0;
1325 if (NtReadFile( handle, 0, NULL, 0, &io, buffer, sizeof(buffer), &offset, NULL )) return FALSE;
1326 if (io.Information < sizeof(buffer)) return FALSE;
1327 if (dos->e_magic != IMAGE_DOS_SIGNATURE) return FALSE;
1328 if (dos->e_lfanew >= sizeof(*dos) + sizeof(fakedll_signature) &&
1329 !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) return TRUE;
1330 return FALSE;
1331 }
1332
1333
1334 /***********************************************************************
1335 * get_builtin_fullname
1336 *
1337 * Build the full pathname for a builtin dll.
1338 */
1339 static WCHAR *get_builtin_fullname( const WCHAR *path, const char *filename )
1340 {
1341 static const WCHAR soW[] = {'.','s','o',0};
1342 WCHAR *p, *fullname;
1343 size_t i, len = strlen(filename);
1344
1345 /* check if path can correspond to the dll we have */
1346 if (path && (p = strrchrW( path, '\\' )))
1347 {
1348 p++;
1349 for (i = 0; i < len; i++)
1350 if (tolowerW(p[i]) != tolowerW( (WCHAR)filename[i]) ) break;
1351 if (i == len && (!p[len] || !strcmpiW( p + len, soW )))
1352 {
1353 /* the filename matches, use path as the full path */
1354 len += p - path;
1355 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
1356 {
1357 memcpy( fullname, path, len * sizeof(WCHAR) );
1358 fullname[len] = 0;
1359 }
1360 return fullname;
1361 }
1362 }
1363
1364 if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0,
1365 system_dir.MaximumLength + (len + 1) * sizeof(WCHAR) )))
1366 {
1367 memcpy( fullname, system_dir.Buffer, system_dir.Length );
1368 p = fullname + system_dir.Length / sizeof(WCHAR);
1369 if (p > fullname && p[-1] != '\\') *p++ = '\\';
1370 ascii_to_unicode( p, filename, len + 1 );
1371 }
1372 return fullname;
1373 }
1374
1375
1376 /***********************************************************************
1377 * load_builtin_callback
1378 *
1379 * Load a library in memory; callback function for wine_dll_register
1380 */
1381 static void load_builtin_callback( void *module, const char *filename )
1382 {
1383 static const WCHAR emptyW[1];
1384 IMAGE_NT_HEADERS *nt;
1385 WINE_MODREF *wm;
1386 WCHAR *fullname;
1387 const WCHAR *load_path;
1388
1389 if (!module)
1390 {
1391 ERR("could not map image for %s\n", filename ? filename : "main exe" );
1392 return;
1393 }
1394 if (!(nt = RtlImageNtHeader( module )))
1395 {
1396 ERR( "bad module for %s\n", filename ? filename : "main exe" );
1397 builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1398 return;
1399 }
1400 virtual_create_system_view( module, nt->OptionalHeader.SizeOfImage,
1401 VPROT_SYSTEM | VPROT_IMAGE | VPROT_COMMITTED |
1402 VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
1403
1404 /* create the MODREF */
1405
1406 if (!(fullname = get_builtin_fullname( builtin_load_info->filename, filename )))
1407 {
1408 ERR( "can't load %s\n", filename );
1409 builtin_load_info->status = STATUS_NO_MEMORY;
1410 return;
1411 }
1412
1413 wm = alloc_module( module, fullname );
1414 RtlFreeHeap( GetProcessHeap(), 0, fullname );
1415 if (!wm)
1416 {
1417 ERR( "can't load %s\n", filename );
1418 builtin_load_info->status = STATUS_NO_MEMORY;
1419 return;
1420 }
1421 wm->ldr.Flags |= LDR_WINE_INTERNAL;
1422
1423 if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
1424 !NtCurrentTeb()->Peb->ImageBaseAddress) /* if we already have an executable, ignore this one */
1425 {
1426 NtCurrentTeb()->Peb->ImageBaseAddress = module;
1427 }
1428 else
1429 {
1430 /* fixup imports */
1431
1432 load_path = builtin_load_info->load_path;
1433 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1434 if (!load_path) load_path = emptyW;
1435 if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1436 {
1437 /* the module has only be inserted in the load & memory order lists */
1438 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1439 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1440 /* FIXME: free the modref */
1441 builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1442 return;
1443 }
1444 }
1445
1446 builtin_load_info->wm = wm;
1447 TRACE( "loaded %s %p %p\n", filename, wm, module );
1448
1449 /* send the DLL load event */
1450
1451 SERVER_START_REQ( load_dll )
1452 {
1453 req->handle = 0;
1454 req->base = wine_server_client_ptr( module );
1455 req->size = nt->OptionalHeader.SizeOfImage;
1456 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1457 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1458 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1459 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1460 wine_server_call( req );
1461 }
1462 SERVER_END_REQ;
1463
1464 /* setup relay debugging entry points */
1465 if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1466 }
1467
1468
1469 /******************************************************************************
1470 * load_native_dll (internal)
1471 */
1472 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1473 DWORD flags, WINE_MODREF** pwm )
1474 {
1475 void *module;
1476 HANDLE mapping;
1477 LARGE_INTEGER size;
1478 IMAGE_NT_HEADERS *nt;
1479 SIZE_T len = 0;
1480 WINE_MODREF *wm;
1481 NTSTATUS status;
1482
1483 TRACE("Trying native dll %s\n", debugstr_w(name));
1484
1485 size.QuadPart = 0;
1486 status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1487 NULL, &size, PAGE_READONLY, SEC_IMAGE, file );
1488 if (status != STATUS_SUCCESS) return status;
1489
1490 module = NULL;
1491 status = NtMapViewOfSection( mapping, NtCurrentProcess(),
1492 &module, 0, 0, &size, &len, ViewShare, 0, PAGE_READONLY );
1493 NtClose( mapping );
1494 if (status != STATUS_SUCCESS) return status;
1495
1496 /* create the MODREF */
1497
1498 if (!(wm = alloc_module( module, name ))) return STATUS_NO_MEMORY;
1499
1500 /* fixup imports */
1501
1502 if (!(flags & DONT_RESOLVE_DLL_REFERENCES))
1503 {
1504 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1505 {
1506 /* the module has only be inserted in the load & memory order lists */
1507 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1508 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1509
1510 /* FIXME: there are several more dangling references
1511 * left. Including dlls loaded by this dll before the
1512 * failed one. Unrolling is rather difficult with the
1513 * current structure and we can leave them lying
1514 * around with no problems, so we don't care.
1515 * As these might reference our wm, we don't free it.
1516 */
1517 return status;
1518 }
1519 }
1520
1521 /* send DLL load event */
1522
1523 nt = RtlImageNtHeader( module );
1524
1525 SERVER_START_REQ( load_dll )
1526 {
1527 req->handle = wine_server_obj_handle( file );
1528 req->base = wine_server_client_ptr( module );
1529 req->size = nt->OptionalHeader.SizeOfImage;
1530 req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1531 req->dbg_size = nt->FileHeader.NumberOfSymbols;
1532 req->name = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1533 wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1534 wine_server_call( req );
1535 }
1536 SERVER_END_REQ;
1537
1538 if ((wm->ldr.Flags & LDR_IMAGE_IS_DLL) && TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1539
1540 TRACE_(loaddll)( "Loaded %s at %p: native\n", debugstr_w(wm->ldr.FullDllName.Buffer), module );
1541
1542 wm->ldr.LoadCount = 1;
1543 *pwm = wm;
1544 return STATUS_SUCCESS;
1545 }
1546
1547
1548 /***********************************************************************
1549 * load_builtin_dll
1550 */
1551 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, HANDLE file,
1552 DWORD flags, WINE_MODREF** pwm )
1553 {
1554 char error[256], dllname[MAX_PATH];
1555 const WCHAR *name, *p;
1556 DWORD len, i;
1557 void *handle = NULL;
1558 struct builtin_load_info info, *prev_info;
1559
1560 /* Fix the name in case we have a full path and extension */
1561 name = path;
1562 if ((p = strrchrW( name, '\\' ))) name = p + 1;
1563 if ((p = strrchrW( name, '/' ))) name = p + 1;
1564
1565 /* load_library will modify info.status. Note also that load_library can be
1566 * called several times, if the .so file we're loading has dependencies.
1567 * info.status will gather all the errors we may get while loading all these
1568 * libraries
1569 */
1570 info.load_path = load_path;
1571 info.filename = NULL;
1572 info.status = STATUS_SUCCESS;
1573 info.wm = NULL;
1574
1575 if (file) /* we have a real file, try to load it */
1576 {
1577 UNICODE_STRING nt_name;
1578 ANSI_STRING unix_name;
1579
1580 TRACE("Trying built-in %s\n", debugstr_w(path));
1581
1582 if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1583 return STATUS_DLL_NOT_FOUND;
1584
1585 if (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ))
1586 {
1587 RtlFreeUnicodeString( &nt_name );
1588 return STATUS_DLL_NOT_FOUND;
1589 }
1590 prev_info = builtin_load_info;
1591 info.filename = nt_name.Buffer + 4; /* skip \??\ */
1592 builtin_load_info = &info;
1593 handle = wine_dlopen( unix_name.Buffer, RTLD_NOW, error, sizeof(error) );
1594 builtin_load_info = prev_info;
1595 RtlFreeUnicodeString( &nt_name );
1596 RtlFreeHeap( GetProcessHeap(), 0, unix_name.Buffer );
1597 if (!handle)
1598 {
1599 WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path), error );
1600 return STATUS_INVALID_IMAGE_FORMAT;
1601 }
1602 }
1603 else
1604 {
1605 int file_exists;
1606
1607 TRACE("Trying built-in %s\n", debugstr_w(name));
1608
1609 /* we don't want to depend on the current codepage here */
1610 len = strlenW( name ) + 1;
1611 if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1612 for (i = 0; i < len; i++)
1613 {
1614 if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1615 dllname[i] = (char)name[i];
1616 if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1617 }
1618
1619 prev_info = builtin_load_info;
1620 builtin_load_info = &info;
1621 handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1622 builtin_load_info = prev_info;
1623 if (!handle)
1624 {
1625 if (!file_exists)
1626 {
1627 /* The file does not exist -> WARN() */
1628 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
1629 return STATUS_DLL_NOT_FOUND;
1630 }
1631 /* ERR() for all other errors (missing functions, ...) */
1632 ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
1633 return STATUS_PROCEDURE_NOT_FOUND;
1634 }
1635 }
1636
1637 if (info.status != STATUS_SUCCESS)
1638 {
1639 wine_dll_unload( handle );
1640 return info.status;
1641 }
1642
1643 if (!info.wm)
1644 {
1645 PLIST_ENTRY mark, entry;
1646
1647 /* The constructor wasn't called, this means the .so is already
1648 * loaded under a different name. Try to find the wm for it. */
1649
1650 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1651 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1652 {
1653 LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1654 if (mod->Flags & LDR_WINE_INTERNAL && mod->SectionHandle == handle)
1655 {
1656 info.wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1657 TRACE( "Found %s at %p for builtin %s\n",
1658 debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress, debugstr_w(path) );
1659 break;
1660 }
1661 }
1662 wine_dll_unload( handle ); /* release the libdl refcount */
1663 if (!info.wm) return STATUS_INVALID_IMAGE_FORMAT;
1664 if (info.wm->ldr.LoadCount != -1) info.wm->ldr.LoadCount++;
1665 }
1666 else
1667 {
1668 TRACE_(loaddll)( "Loaded %s at %p: builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress );
1669 info.wm->ldr.LoadCount = 1;
1670 info.wm->ldr.SectionHandle = handle;
1671 }
1672
1673 *pwm = info.wm;
1674 return STATUS_SUCCESS;
1675 }
1676
1677
1678 /***********************************************************************
1679 * find_actctx_dll
1680 *
1681 * Find the full path (if any) of the dll from the activation context.
1682 */
1683 static NTSTATUS find_actctx_dll( LPCWSTR libname, LPWSTR *fullname )
1684 {
1685 static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
1686 static const WCHAR dotManifestW[] = {'.','m','a','n','i','f','e','s','t',0};
1687
1688 ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
1689 ACTCTX_SECTION_KEYED_DATA data;
1690 UNICODE_STRING nameW;
1691 NTSTATUS status;
1692 SIZE_T needed, size = 1024;
1693 WCHAR *p;
1694
1695 RtlInitUnicodeString( &nameW, libname );
1696 data.cbSize = sizeof(data);
1697 status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
1698 ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
1699 &nameW, &data );
1700 if (status != STATUS_SUCCESS) return status;
1701
1702 for (;;)
1703 {
1704 if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1705 {
1706 status = STATUS_NO_MEMORY;
1707 goto done;
1708 }
1709 status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
1710 AssemblyDetailedInformationInActivationContext,
1711 info, size, &needed );
1712 if (status == STATUS_SUCCESS) break;
1713 if (status != STATUS_BUFFER_TOO_SMALL) goto done;
1714 RtlFreeHeap( GetProcessHeap(), 0, info );
1715 size = needed;
1716 /* restart with larger buffer */
1717 }
1718
1719 if (!info->lpAssemblyManifestPath || !info->lpAssemblyDirectoryName)
1720 {
1721 status = STATUS_SXS_KEY_NOT_FOUND;
1722 goto done;
1723 }
1724
1725 if ((p = strrchrW( info->lpAssemblyManifestPath, '\\' )))
1726 {
1727 DWORD dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1728
1729 p++;
1730 if (strncmpiW( p, info->lpAssemblyDirectoryName, dirlen ) || strcmpiW( p + dirlen, dotManifestW ))
1731 {
1732 /* manifest name does not match directory name, so it's not a global
1733 * windows/winsxs manifest; use the manifest directory name instead */
1734 dirlen = p - info->lpAssemblyManifestPath;
1735 needed = (dirlen + 1) * sizeof(WCHAR) + nameW.Length;
1736 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1737 {
1738 status = STATUS_NO_MEMORY;
1739 goto done;
1740 }
1741 memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
1742 p += dirlen;
1743 strcpyW( p, libname );
1744 goto done;
1745 }
1746 }
1747
1748 needed = (windows_dir.Length + sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength +
1749 nameW.Length + 2*sizeof(WCHAR));
1750
1751 if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1752 {
1753 status = STATUS_NO_MEMORY;
1754 goto done;
1755 }
1756 memcpy( p, windows_dir.Buffer, windows_dir.Length );
1757 p += windows_dir.Length / sizeof(WCHAR);
1758 memcpy( p, winsxsW, sizeof(winsxsW) );
1759 p += sizeof(winsxsW) / sizeof(WCHAR);
1760 memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
1761 p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1762 *p++ = '\\';
1763 strcpyW( p, libname );
1764 done:
1765 RtlFreeHeap( GetProcessHeap(), 0, info );
1766 RtlReleaseActivationContext( data.hActCtx );
1767 return status;
1768 }
1769
1770
1771 /***********************************************************************
1772 * find_dll_file
1773 *
1774 * Find the file (or already loaded module) for a given dll name.
1775 */
1776 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
1777 WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
1778 {
1779 OBJECT_ATTRIBUTES attr;
1780 IO_STATUS_BLOCK io;
1781 UNICODE_STRING nt_name;
1782 WCHAR *file_part, *ext, *dllname;
1783 ULONG len;
1784
1785 /* first append .dll if needed */
1786
1787 dllname = NULL;
1788 if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
1789 {
1790 if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
1791 (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
1792 return STATUS_NO_MEMORY;
1793 strcpyW( dllname, libname );
1794 strcatW( dllname, dllW );
1795 libname = dllname;
1796 }
1797
1798 nt_name.Buffer = NULL;
1799
1800 if (!contains_path( libname ))
1801 {
1802 NTSTATUS status;
1803 WCHAR *fullname = NULL;
1804
1805 if ((*pwm = find_basename_module( libname )) != NULL) goto found;
1806
1807 status = find_actctx_dll( libname, &fullname );
1808 if (status == STATUS_SUCCESS)
1809 {
1810 TRACE ("found %s for %s\n", debugstr_w(fullname), debugstr_w(libname) );
1811 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1812 libname = dllname = fullname;
1813 }
1814 else if (status != STATUS_SXS_KEY_NOT_FOUND)
1815 {
1816 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1817 return status;
1818 }
1819 }
1820
1821 if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
1822 {
1823 /* we need to search for it */
1824 len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
1825 if (len)
1826 {
1827 if (len >= *size) goto overflow;
1828 if ((*pwm = find_fullname_module( filename )) || !handle) goto found;
1829
1830 if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
1831 {
1832 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1833 return STATUS_NO_MEMORY;
1834 }
1835 attr.Length = sizeof(attr);
1836 attr.RootDirectory = 0;
1837 attr.Attributes = OBJ_CASE_INSENSITIVE;
1838 attr.ObjectName = &nt_name;
1839 attr.SecurityDescriptor = NULL;
1840 attr.SecurityQualityOfService = NULL;
1841 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1842 goto found;
1843 }
1844
1845 /* not found */
1846
1847 if (!contains_path( libname ))
1848 {
1849 /* if libname doesn't contain a path at all, we simply return the name as is,
1850 * to be loaded as builtin */
1851 len = strlenW(libname) * sizeof(WCHAR);
1852 if (len >= *size) goto overflow;
1853 strcpyW( filename, libname );
1854 goto found;
1855 }
1856 }
1857
1858 /* absolute path name, or relative path name but not found above */
1859
1860 if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
1861 {
1862 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1863 return STATUS_NO_MEMORY;
1864 }
1865 len = nt_name.Length - 4*sizeof(WCHAR); /* for \??\ prefix */
1866 if (len >= *size) goto overflow;
1867 memcpy( filename, nt_name.Buffer + 4, len + sizeof(WCHAR) );
1868 if (!(*pwm = find_fullname_module( filename )) && handle)
1869 {
1870 attr.Length = sizeof(attr);
1871 attr.RootDirectory = 0;
1872 attr.Attributes = OBJ_CASE_INSENSITIVE;
1873 attr.ObjectName = &nt_name;
1874 attr.SecurityDescriptor = NULL;
1875 attr.SecurityQualityOfService = NULL;
1876 if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1877 }
1878 found:
1879 RtlFreeUnicodeString( &nt_name );
1880 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1881 return STATUS_SUCCESS;
1882
1883 overflow:
1884 RtlFreeUnicodeString( &nt_name );
1885 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1886 *size = len + sizeof(WCHAR);
1887 return STATUS_BUFFER_TOO_SMALL;
1888 }
1889
1890
1891 /***********************************************************************
1892 * load_dll (internal)
1893 *
1894 * Load a PE style module according to the load order.
1895 * The loader_section must be locked while calling this function.
1896 */
1897 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
1898 {
1899 enum loadorder loadorder;
1900 WCHAR buffer[32];
1901 WCHAR *filename;
1902 ULONG size;
1903 WINE_MODREF *main_exe;
1904 HANDLE handle = 0;
1905 NTSTATUS nts;
1906
1907 TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
1908
1909 *pwm = NULL;
1910 filename = buffer;
1911 size = sizeof(buffer);
1912 for (;;)
1913 {
1914 nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
1915 if (nts == STATUS_SUCCESS) break;
1916 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1917 if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
1918 /* grow the buffer and retry */
1919 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
1920 }
1921
1922 if (*pwm) /* found already loaded module */
1923 {
1924 if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
1925
1926 if (!(flags & DONT_RESOLVE_DLL_REFERENCES)) fixup_imports( *pwm, load_path );
1927
1928 TRACE("Found %s for %s at %p, count=%d\n",
1929 debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
1930 (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
1931 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1932 return STATUS_SUCCESS;
1933 }
1934
1935 main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
1936 loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
1937
1938 if (handle && is_fake_dll( handle ))
1939 {
1940 TRACE( "%s is a fake Wine dll\n", debugstr_w(filename) );
1941 NtClose( handle );
1942 handle = 0;
1943 }
1944
1945 switch(loadorder)
1946 {
1947 case LO_INVALID:
1948 nts = STATUS_NO_MEMORY;
1949 break;
1950 case LO_DISABLED:
1951 nts = STATUS_DLL_NOT_FOUND;
1952 break;
1953 case LO_NATIVE:
1954 case LO_NATIVE_BUILTIN:
1955 if (!handle) nts = STATUS_DLL_NOT_FOUND;
1956 else
1957 {
1958 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1959 if (nts == STATUS_INVALID_FILE_FOR_SECTION)
1960 /* not in PE format, maybe it's a builtin */
1961 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1962 }
1963 if (nts == STATUS_DLL_NOT_FOUND && loadorder == LO_NATIVE_BUILTIN)
1964 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1965 break;
1966 case LO_BUILTIN:
1967 case LO_BUILTIN_NATIVE:
1968 case LO_DEFAULT: /* default is builtin,native */
1969 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1970 if (!handle) break; /* nothing else we can try */
1971 /* file is not a builtin library, try without using the specified file */
1972 if (nts != STATUS_SUCCESS)
1973 nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1974 if (nts == STATUS_SUCCESS && loadorder == LO_DEFAULT &&
1975 (MODULE_InitDLL( *pwm, DLL_WINE_PREATTACH, NULL ) != STATUS_SUCCESS))
1976 {
1977 /* stub-only dll, try native */
1978 TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename) );
1979 LdrUnloadDll( (*pwm)->ldr.BaseAddress );
1980 nts = STATUS_DLL_NOT_FOUND;
1981 }
1982 if (nts == STATUS_DLL_NOT_FOUND && loadorder != LO_BUILTIN)
1983 nts = load_native_dll( load_path, filename, handle, flags, pwm );
1984 break;
1985 }
1986
1987 if (nts == STATUS_SUCCESS)
1988 {
1989 /* Initialize DLL just loaded */
1990 TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename),
1991 ((*pwm)->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native",
1992 (*pwm)->ldr.BaseAddress);
1993 if (handle) NtClose( handle );
1994 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1995 return nts;
1996 }
1997
1998 WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
1999 if (handle) NtClose( handle );
2000 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2001 return nts;
2002 }
2003
2004 /******************************************************************
2005 * LdrLoadDll (NTDLL.@)
2006 */
2007 NTSTATUS WINAPI LdrLoadDll(LPCWSTR path_name, DWORD flags,
2008 const UNICODE_STRING *libname, HMODULE* hModule)
2009 {
2010 WINE_MODREF *wm;
2011 NTSTATUS nts;
2012
2013 RtlEnterCriticalSection( &loader_section );
2014
2015 if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2016 nts = load_dll( path_name, libname->Buffer, flags, &wm );
2017
2018 if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
2019 {
2020 nts = process_attach( wm, NULL );
2021 if (nts != STATUS_SUCCESS)
2022 {
2023 LdrUnloadDll(wm->ldr.BaseAddress);
2024 wm = NULL;
2025 }
2026 }
2027 *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
2028
2029 RtlLeaveCriticalSection( &loader_section );
2030 return nts;
2031 }
2032
2033
2034 /******************************************************************
2035 * LdrGetDllHandle (NTDLL.@)
2036 */
2037 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
2038 {
2039 NTSTATUS status;
2040 WCHAR buffer[128];
2041 WCHAR *filename;
2042 ULONG size;
2043 WINE_MODREF *wm;
2044
2045 RtlEnterCriticalSection( &loader_section );
2046
2047 if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2048
2049 filename = buffer;
2050 size = sizeof(buffer);
2051 for (;;)
2052 {
2053 status = find_dll_file( load_path, name->Buffer, filename, &size, &wm, NULL );
2054 if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2055 if (status != STATUS_BUFFER_TOO_SMALL) break;
2056 /* grow the buffer and retry */
2057 if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2058 {
2059 status = STATUS_NO_MEMORY;
2060 break;
2061 }
2062 }
2063
2064 if (status == STATUS_SUCCESS)
2065 {
2066 if (wm) *base = wm->ldr.BaseAddress;
2067 else status = STATUS_DLL_NOT_FOUND;
2068 }
2069
2070 RtlLeaveCriticalSection( &loader_section );
2071 TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
2072 return status;
2073 }
2074
2075
2076 /******************************************************************
2077 * LdrAddRefDll (NTDLL.@)
2078 */
2079 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
2080 {
2081 NTSTATUS ret = STATUS_SUCCESS;
2082 WINE_MODREF *wm;
2083
2084 if (flags) FIXME( "%p flags %x not implemented\n", module, flags );
2085
2086 RtlEnterCriticalSection( &loader_section );
2087
2088 if ((wm = get_modref( module )))
2089 {
2090 if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
2091 TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2092 }
2093 else ret = STATUS_INVALID_PARAMETER;
2094
2095 RtlLeaveCriticalSection( &loader_section );
2096 return ret;
2097 }
2098
2099
2100 /***********************************************************************
2101 * LdrProcessRelocationBlock (NTDLL.@)
2102 *
2103 * Apply relocations to a given page of a mapped PE image.
2104 */
2105 IMAGE_BASE_RELOCATION * WINAPI LdrProcessRelocationBlock( void *page, UINT count,
2106 USHORT *relocs, INT_PTR delta )
2107 {
2108 while (count--)
2109 {
2110 USHORT offset = *relocs & 0xfff;
2111 int type = *relocs >> 12;
2112 switch(type)
2113 {
2114 case IMAGE_REL_BASED_ABSOLUTE:
2115 break;
2116 #ifdef __i386__
2117 case IMAGE_REL_BASED_HIGH:
2118 *(short *)((char *)page + offset) += HIWORD(delta);
2119 break;
2120 case IMAGE_REL_BASED_LOW:
2121 *(short *)((char *)page + offset) += LOWORD(delta);
2122 break;
2123 case IMAGE_REL_BASED_HIGHLOW:
2124 *(int *)((char *)page + offset) += delta;
2125 break;
2126 #elif defined(__x86_64__)
2127 case IMAGE_REL_BASED_DIR64:
2128 *(INT_PTR *)((char *)page + offset) += delta;
2129 break;
2130 #endif
2131 default:
2132 FIXME("Unknown/unsupported fixup type %x.\n", type);
2133 return NULL;
2134 }
2135 relocs++;
2136 }
2137 return (IMAGE_BASE_RELOCATION *)relocs; /* return address of next block */
2138 }
2139
2140
2141 /******************************************************************
2142 * LdrQueryProcessModuleInformation
2143 *
2144 */
2145 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi,
2146 ULONG buf_size, ULONG* req_size)
2147 {
2148 SYSTEM_MODULE* sm = &smi->Modules[0];
2149 ULONG size = sizeof(ULONG);
2150 NTSTATUS nts = STATUS_SUCCESS;
2151 ANSI_STRING str;
2152 char* ptr;
2153 PLIST_ENTRY mark, entry;
2154 PLDR_MODULE mod;
2155 WORD id = 0;
2156
2157 smi->ModulesCount = 0;
2158
2159 RtlEnterCriticalSection( &loader_section );
2160 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2161 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2162 {
2163 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2164 size += sizeof(*sm);
2165 if (size <= buf_size)
2166 {
2167 sm->Reserved1 = 0; /* FIXME */
2168 sm->Reserved2 = 0; /* FIXME */
2169 sm->ImageBaseAddress = mod->BaseAddress;
2170 sm->ImageSize = mod->SizeOfImage;
2171 sm->Flags = mod->Flags;
2172 sm->Id = id++;
2173 sm->Rank = 0; /* FIXME */
2174 sm->Unknown = 0; /* FIXME */
2175 str.Length = 0;
2176 str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
2177 str.Buffer = (char*)sm->Name;
2178 RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
2179 ptr = strrchr(str.Buffer, '\\');
2180 sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
2181
2182 smi->ModulesCount++;
2183 sm++;
2184 }
2185 else nts = STATUS_INFO_LENGTH_MISMATCH;
2186 }
2187 RtlLeaveCriticalSection( &loader_section );
2188
2189 if (req_size) *req_size = size;
2190
2191 return nts;
2192 }
2193
2194
2195 /******************************************************************
2196 * RtlDllShutdownInProgress (NTDLL.@)
2197 */
2198 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
2199 {
2200 return process_detaching;
2201 }
2202
2203
2204 /******************************************************************
2205 * LdrShutdownProcess (NTDLL.@)
2206 *
2207 */
2208 void WINAPI LdrShutdownProcess(void)
2209 {
2210 TRACE("()\n");
2211 process_detach( TRUE, (LPVOID)1 );
2212 }
2213
2214 /******************************************************************
2215 * LdrShutdownThread (NTDLL.@)
2216 *
2217 */
2218 void WINAPI LdrShutdownThread(void)
2219 {
2220 PLIST_ENTRY mark, entry;
2221 PLDR_MODULE mod;
2222
2223 TRACE("()\n");
2224
2225 /* don't do any detach calls if process is exiting */
2226 if (process_detaching) return;
2227 /* FIXME: there is still a race here */
2228
2229 RtlEnterCriticalSection( &loader_section );
2230
2231 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2232 for (entry = mark->Blink; entry != mark; entry = entry->Blink)
2233 {
2234 mod = CONTAINING_RECORD(entry, LDR_MODULE,
2235 InInitializationOrderModuleList);
2236 if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
2237 continue;
2238 if ( mod->Flags & LDR_NO_DLL_CALLS )
2239 continue;
2240
2241 MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
2242 DLL_THREAD_DETACH, NULL );
2243 }
2244
2245 RtlLeaveCriticalSection( &loader_section );
2246 RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->ThreadLocalStoragePointer );
2247 }
2248
2249
2250 /***********************************************************************
2251 * free_modref
2252 *
2253 */
2254 static void free_modref( WINE_MODREF *wm )
2255 {
2256 RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
2257 RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
2258 if (wm->ldr.InInitializationOrderModuleList.Flink)
2259 RemoveEntryList(&wm->ldr.InInitializationOrderModuleList);
2260
2261 TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
2262 if (!TRACE_ON(module))
2263 TRACE_(loaddll)("Unloaded module %s : %s\n",
2264 debugstr_w(wm->ldr.FullDllName.Buffer),
2265 (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
2266
2267 SERVER_START_REQ( unload_dll )
2268 {
2269 req->base = wine_server_client_ptr( wm->ldr.BaseAddress );
2270 wine_server_call( req );
2271 }
2272 SERVER_END_REQ;
2273
2274 RtlReleaseActivationContext( wm->ldr.ActivationContext );
2275 NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.BaseAddress );
2276 if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
2277 if (cached_modref == wm) cached_modref = NULL;
2278 RtlFreeUnicodeString( &wm->ldr.FullDllName );
2279 RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
2280 RtlFreeHeap( GetProcessHeap(), 0, wm );
2281 }
2282
2283 /***********************************************************************
2284 * MODULE_FlushModrefs
2285 *
2286 * Remove all unused modrefs and call the internal unloading routines
2287 * for the library type.
2288 *
2289 * The loader_section must be locked while calling this function.
2290 */
2291 static void MODULE_FlushModrefs(void)
2292 {
2293 PLIST_ENTRY mark, entry, prev;
2294 PLDR_MODULE mod;
2295 WINE_MODREF*wm;
2296
2297 mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2298 for (entry = mark->Blink; entry != mark; entry = prev)
2299 {
2300 mod = CONTAINING_RECORD(entry, LDR_MODULE, InInitializationOrderModuleList);
2301 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2302 prev = entry->Blink;
2303 if (!mod->LoadCount) free_modref( wm );
2304 }
2305
2306 /* check load order list too for modules that haven't been initialized yet */
2307 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2308 for (entry = mark->Blink; entry != mark; entry = prev)
2309 {
2310 mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2311 wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2312 prev = entry->Blink;
2313 if (!mod->LoadCount) free_modref( wm );
2314 }
2315 }
2316
2317 /***********************************************************************
2318 * MODULE_DecRefCount
2319 *
2320 * The loader_section must be locked while calling this function.
2321 */
2322 static void MODULE_DecRefCount( WINE_MODREF *wm )
2323 {
2324 int i;
2325
2326 if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
2327 return;
2328
2329 if ( wm->ldr.LoadCount <= 0 )
2330 return;
2331
2332 --wm->ldr.LoadCount;
2333 TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2334
2335 if ( wm->ldr.LoadCount == 0 )
2336 {
2337 wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
2338
2339 for ( i = 0; i < wm->nDeps; i++ )
2340 if ( wm->deps[i] )
2341 MODULE_DecRefCount( wm->deps[i] );
2342
2343 wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
2344 }
2345 }
2346
2347 /******************************************************************
2348 * LdrUnloadDll (NTDLL.@)
2349 *
2350 *
2351 */
2352 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
2353 {
2354 NTSTATUS retv = STATUS_SUCCESS;
2355
2356 TRACE("(%p)\n", hModule);
2357
2358 RtlEnterCriticalSection( &loader_section );
2359
2360 /* if we're stopping the whole process (and forcing the removal of all
2361 * DLLs) the library will be freed anyway
2362 */
2363 if (!process_detaching)
2364 {
2365 WINE_MODREF *wm;
2366
2367 free_lib_count++;
2368 if ((wm = get_modref( hModule )) != NULL)
2369 {
2370 TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
2371
2372 /* Recursively decrement reference counts */
2373 MODULE_DecRefCount( wm );
2374
2375 /* Call process detach notifications */
2376 if ( free_lib_count <= 1 )
2377 {
2378 process_detach( FALSE, NULL );
2379 MODULE_FlushModrefs();
2380 }
2381
2382 TRACE("END\n");
2383 }
2384 else
2385 retv = STATUS_DLL_NOT_FOUND;
2386
2387 free_lib_count--;
2388 }
2389
2390 RtlLeaveCriticalSection( &loader_section );
2391
2392 return retv;
2393 }
2394
2395 /***********************************************************************
2396 * RtlImageNtHeader (NTDLL.@)
2397 */
2398 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
2399 {
2400 IMAGE_NT_HEADERS *ret;
2401
2402 __TRY
2403 {
2404 IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
2405
2406 ret = NULL;
2407 if (dos->e_magic == IMAGE_DOS_SIGNATURE)
2408 {
2409 ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
2410 if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
2411 }
2412 }
2413 __EXCEPT_PAGE_FAULT
2414 {
2415 return NULL;
2416 }
2417 __ENDTRY
2418 return ret;
2419 }
2420
2421
2422 /***********************************************************************
2423 * attach_process_dlls
2424 *
2425 * Initial attach to all the dlls loaded by the process.
2426 */
2427 static NTSTATUS attach_process_dlls( void *wm )
2428 {
2429 NTSTATUS status;
2430
2431 pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
2432
2433 RtlEnterCriticalSection( &loader_section );
2434 if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS)
2435 {
2436 if (last_failed_modref)
2437 ERR( "%s failed to initialize, aborting\n",
2438 debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
2439 return status;
2440 }
2441 attach_implicitly_loaded_dlls( (LPVOID)1 );
2442 RtlLeaveCriticalSection( &loader_section );
2443 return status;
2444 }
2445
2446
2447 /******************************************************************
2448 * LdrInitializeThunk (NTDLL.@)
2449 *
2450 */
2451 void WINAPI LdrInitializeThunk( ULONG unknown1, ULONG unknown2, ULONG unknown3, ULONG unknown4 )
2452 {
2453 NTSTATUS status;
2454 WINE_MODREF *wm;
2455 LPCWSTR load_path;
2456 PEB *peb = NtCurrentTeb()->Peb;
2457 IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
2458
2459 if (main_exe_file) NtClose( main_exe_file ); /* at this point the main module is created */
2460
2461 /* allocate the modref for the main exe (if not already done) */
2462 wm = get_modref( peb->ImageBaseAddress );
2463 assert( wm );
2464 if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
2465 {
2466 ERR("%s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
2467 exit(1);
2468 }
2469
2470 peb->LoaderLock = &loader_section;
2471 peb->ProcessParameters->ImagePathName = wm->ldr.FullDllName;
2472 version_init( wm->ldr.FullDllName.Buffer );
2473
2474 /* the main exe needs to be the first in the load order list */
2475 RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
2476 InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
2477
2478 if ((status = virtual_alloc_thread_stack( NtCurrentTeb(), 0, 0 )) != STATUS_SUCCESS) goto error;
2479 if ((status = server_init_process_done()) != STATUS_SUCCESS) goto error;
2480
2481 actctx_init();
2482 load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2483 if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
2484 if ((status = alloc_process_tls()) != STATUS_SUCCESS) goto error;
2485 if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto error;
2486
2487 status = wine_call_on_stack( attach_process_dlls, wm, NtCurrentTeb()->Tib.StackBase );
2488 if (status != STATUS_SUCCESS) goto error;
2489
2490 virtual_release_address_space( nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE );
2491 virtual_clear_thread_stack();
2492 return;
2493
2494 error:
2495 ERR( "Main exe initialization for %s failed, status %x\n",
2496 debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), status );
2497 NtTerminateProcess( GetCurrentProcess(), status );
2498 }
2499
2500
2501 /***********************************************************************
2502 * RtlImageDirectoryEntryToData (NTDLL.@)
2503 */
2504 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
2505 {
2506 const IMAGE_NT_HEADERS *nt;
2507 DWORD addr;
2508
2509 if ((ULONG_PTR)module & 1) /* mapped as data file */
2510 {
2511 module = (HMODULE)((ULONG_PTR)module & ~1);
2512 image = FALSE;
2513 }
2514 if (!(nt = RtlImageNtHeader( module ))) return NULL;
2515 if (dir >= nt->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2516 if (!(addr = nt->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2517 *size = nt->OptionalHeader.DataDirectory[dir].Size;
2518 if (image || addr < nt->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2519
2520 /* not mapped as image, need to find the section containing the virtual address */
2521 return RtlImageRvaToVa( nt, module, addr, NULL );
2522 }
2523
2524
2525 /***********************************************************************
2526 * RtlImageRvaToSection (NTDLL.@)
2527 */
2528 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
2529 HMODULE module, DWORD rva )
2530 {
2531 int i;
2532 const IMAGE_SECTION_HEADER *sec;
2533
2534 sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
2535 nt->FileHeader.SizeOfOptionalHeader);
2536 for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
2537 {
2538 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2539 return (PIMAGE_SECTION_HEADER)sec;
2540 }
2541 return NULL;
2542 }
2543
2544
2545 /***********************************************************************
2546 * RtlImageRvaToVa (NTDLL.@)
2547 */
2548 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
2549 DWORD rva, IMAGE_SECTION_HEADER **section )
2550 {
2551 IMAGE_SECTION_HEADER *sec;
2552
2553 if (section && *section) /* try this section first */
2554 {
2555 sec = *section;
2556 if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2557 goto found;
2558 }
2559 if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
2560 found:
2561 if (section) *section = sec;
2562 return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
2563 }
2564
2565
2566 /***********************************************************************
2567 * RtlPcToFileHeader (NTDLL.@)
2568 */
2569 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
2570 {
2571 LDR_MODULE *module;
2572 PVOID ret = NULL;
2573
2574 RtlEnterCriticalSection( &loader_section );
2575 if (!LdrFindEntryForAddress( pc, &module )) ret = module->BaseAddress;
2576 RtlLeaveCriticalSection( &loader_section );
2577 *address = ret;
2578 return ret;
2579 }
2580
2581
2582 /***********************************************************************
2583 * NtLoadDriver (NTDLL.@)
2584 * ZwLoadDriver (NTDLL.@)
2585 */
2586 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
2587 {
2588 FIXME("(%p), stub!\n",DriverServiceName);
2589 return STATUS_NOT_IMPLEMENTED;
2590 }
2591
2592
2593 /***********************************************************************
2594 * NtUnloadDriver (NTDLL.@)
2595 * ZwUnloadDriver (NTDLL.@)
2596 */
2597 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
2598 {
2599 FIXME("(%p), stub!\n",DriverServiceName);
2600 return STATUS_NOT_IMPLEMENTED;
2601 }
2602
2603
2604 /******************************************************************
2605 * DllMain (NTDLL.@)
2606 */
2607 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
2608 {
2609 if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
2610 return TRUE;
2611 }
2612
2613
2614 /******************************************************************
2615 * __wine_init_windows_dir (NTDLL.@)
2616 *
2617 * Windows and system dir initialization once kernel32 has been loaded.
2618 */
2619 void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
2620 {
2621 PLIST_ENTRY mark, entry;
2622 LPWSTR buffer, p;
2623
2624 RtlCreateUnicodeString( &windows_dir, windir );
2625 RtlCreateUnicodeString( &system_dir, sysdir );
2626 strcpyW( user_shared_data->NtSystemRoot, windir );
2627
2628 /* prepend the system dir to the name of the already created modules */
2629 mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2630 for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2631 {
2632 LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
2633
2634 assert( mod->Flags & LDR_WINE_INTERNAL );
2635
2636 buffer = RtlAllocateHeap( GetProcessHeap(), 0,
2637 system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
2638 if (!buffer) continue;
2639 strcpyW( buffer, system_dir.Buffer );
2640 p = buffer + strlenW( buffer );
2641 if (p > buffer && p[-1] != '\\') *p++ = '\\';
2642 strcpyW( p, mod->FullDllName.Buffer );
2643 RtlInitUnicodeString( &mod->FullDllName, buffer );
2644 RtlInitUnicodeString( &mod->BaseDllName, p );
2645 }
2646 }
2647
2648
2649 /***********************************************************************
2650 * __wine_process_init
2651 */
2652 void __wine_process_init(void)
2653 {
2654 static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
2655
2656 WINE_MODREF *wm;
2657 NTSTATUS status;
2658 ANSI_STRING func_name;
2659 void (* DECLSPEC_NORETURN CDECL init_func)(void);
2660 extern mode_t FILE_umask;
2661
2662 main_exe_file = thread_init();
2663
2664 /* retrieve current umask */
2665 FILE_umask = umask(0777);
2666 umask( FILE_umask );
2667
2668 /* setup the load callback and create ntdll modref */
2669 wine_dll_set_callback( load_builtin_callback );
2670
2671 if ((status = load_builtin_dll( NULL, kernel32W, 0, 0, &wm )) != STATUS_SUCCESS)
2672 {
2673 MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
2674 exit(1);
2675 }
2676 RtlInitAnsiString( &func_name, "UnhandledExceptionFilter" );
2677 LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name, 0, (void **)&unhandled_exception_filter );
2678
2679 RtlInitAnsiString( &func_name, "__wine_kernel_init" );
2680 if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
2681 0, (void **)&init_func )) != STATUS_SUCCESS)
2682 {
2683 MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status );
2684 exit(1);
2685 }
2686 init_func();
2687 }
2688
This page was automatically generated by the
LXR engine.
Visit the LXR main site for more
information.