Release 1.5.29.
[wine] / dlls / ntdll / loader.c
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 #define TLS_ALIGNMENT (2 * sizeof(void *))
101 #define TLS_ALIGN(size) (((size) + TLS_ALIGNMENT - 1) & ~(TLS_ALIGNMENT - 1))
102
103 static RTL_CRITICAL_SECTION loader_section;
104 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
105 {
106     0, 0, &loader_section,
107     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
108       0, 0, { (DWORD_PTR)(__FILE__ ": loader_section") }
109 };
110 static RTL_CRITICAL_SECTION loader_section = { &critsect_debug, -1, 0, 0, 0, 0 };
111
112 static WINE_MODREF *cached_modref;
113 static WINE_MODREF *current_modref;
114 static WINE_MODREF *last_failed_modref;
115
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 );
122
123 /* convert PE image VirtualAddress to Real Address */
124 static inline void *get_rva( HMODULE module, DWORD va )
125 {
126     return (void *)((char *)module + va);
127 }
128
129 /* check whether the file name contains a path */
130 static inline int contains_path( LPCWSTR name )
131 {
132     return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
133 }
134
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 )
137 {
138     while (len--) *dst++ = (unsigned char)*src++;
139 }
140
141
142 /*************************************************************************
143  *              call_dll_entry_point
144  *
145  * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
146  * their entry point, so we need a small asm wrapper.
147  */
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 )
174 {
175     return proc( module, reason, reserved );
176 }
177 #endif /* __i386__ */
178
179
180 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__)
181 /*************************************************************************
182  *              stub_entry_point
183  *
184  * Entry point for stub functions.
185  */
186 static void stub_entry_point( const char *dll, const char *name, void *ret_addr )
187 {
188     EXCEPTION_RECORD rec;
189
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 );
198 }
199
200
201 #include "pshpack1.h"
202 #ifdef __i386__
203 struct stub
204 {
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;
211 };
212 #elif defined(__arm__)
213 struct stub
214 {
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;
224 };
225 #else
226 struct stub
227 {
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 */
236 };
237 #endif
238 #include "poppack.h"
239
240 /*************************************************************************
241  *              allocate_stub
242  *
243  * Allocate a stub entry point.
244  */
245 static ULONG_PTR allocate_stub( const char *dll, const char *name )
246 {
247 #define MAX_SIZE 65536
248     static struct stub *stubs;
249     static unsigned int nb_stubs;
250     struct stub *stub;
251
252     if (nb_stubs >= MAX_SIZE / sizeof(*stub)) return 0xdeadbeef;
253
254     if (!stubs)
255     {
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;
260     }
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;
315 }
316
317 #else  /* __i386__ */
318 static inline ULONG_PTR allocate_stub( const char *dll, const char *name ) { return 0xdeadbeef; }
319 #endif  /* __i386__ */
320
321
322 /*************************************************************************
323  *              get_modref
324  *
325  * Looks for the referenced HMODULE in the current process
326  * The loader_section must be locked while calling this function.
327  */
328 static WINE_MODREF *get_modref( HMODULE hmod )
329 {
330     PLIST_ENTRY mark, entry;
331     PLDR_MODULE mod;
332
333     if (cached_modref && cached_modref->ldr.BaseAddress == hmod) return cached_modref;
334
335     mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
336     for (entry = mark->Flink; entry != mark; entry = entry->Flink)
337     {
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;
342     }
343     return NULL;
344 }
345
346
347 /**********************************************************************
348  *          find_basename_module
349  *
350  * Find a module from its base name.
351  * The loader_section must be locked while calling this function
352  */
353 static WINE_MODREF *find_basename_module( LPCWSTR name )
354 {
355     PLIST_ENTRY mark, entry;
356
357     if (cached_modref && !strcmpiW( name, cached_modref->ldr.BaseDllName.Buffer ))
358         return cached_modref;
359
360     mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
361     for (entry = mark->Flink; entry != mark; entry = entry->Flink)
362     {
363         LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
364         if (!strcmpiW( name, mod->BaseDllName.Buffer ))
365         {
366             cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
367             return cached_modref;
368         }
369     }
370     return NULL;
371 }
372
373
374 /**********************************************************************
375  *          find_fullname_module
376  *
377  * Find a module from its full path name.
378  * The loader_section must be locked while calling this function
379  */
380 static WINE_MODREF *find_fullname_module( LPCWSTR name )
381 {
382     PLIST_ENTRY mark, entry;
383
384     if (cached_modref && !strcmpiW( name, cached_modref->ldr.FullDllName.Buffer ))
385         return cached_modref;
386
387     mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
388     for (entry = mark->Flink; entry != mark; entry = entry->Flink)
389     {
390         LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
391         if (!strcmpiW( name, mod->FullDllName.Buffer ))
392         {
393             cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
394             return cached_modref;
395         }
396     }
397     return NULL;
398 }
399
400
401 /*************************************************************************
402  *              find_forwarded_export
403  *
404  * Find the final function pointer for a forwarded function.
405  * The loader_section must be locked while calling this function.
406  */
407 static FARPROC find_forwarded_export( HMODULE module, const char *forward, LPCWSTR load_path )
408 {
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;
415
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, '.' ))
421     {
422         if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name) - sizeof(dllW)) return NULL;
423         memcpy( mod_name + (end - forward), dllW, sizeof(dllW) );
424     }
425
426     if (!(wm = find_basename_module( mod_name )))
427     {
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))
431         {
432             if (process_attach( wm, NULL ) != STATUS_SUCCESS)
433             {
434                 LdrUnloadDll( wm->ldr.BaseAddress );
435                 wm = NULL;
436             }
437         }
438
439         if (!wm)
440         {
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;
444         }
445     }
446     if ((exports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
447                                                  IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
448     {
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 );
454     }
455
456     if (!proc)
457     {
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) );
462     }
463     return proc;
464 }
465
466
467 /*************************************************************************
468  *              find_ordinal_export
469  *
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.
473  */
474 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
475                                     DWORD exp_size, DWORD ordinal, LPCWSTR load_path )
476 {
477     FARPROC proc;
478     const DWORD *functions = get_rva( module, exports->AddressOfFunctions );
479
480     if (ordinal >= exports->NumberOfFunctions)
481     {
482         TRACE(" ordinal %d out of range!\n", ordinal + exports->Base );
483         return NULL;
484     }
485     if (!functions[ordinal]) return NULL;
486
487     proc = get_rva( module, functions[ordinal] );
488
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 );
493
494     if (TRACE_ON(snoop))
495     {
496         const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
497         proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
498     }
499     if (TRACE_ON(relay))
500     {
501         const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
502         proc = RELAY_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
503     }
504     return proc;
505 }
506
507
508 /*************************************************************************
509  *              find_named_export
510  *
511  * Find an exported function by name.
512  * The loader_section must be locked while calling this function.
513  */
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 )
516 {
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;
520
521     /* first check the hint */
522     if (hint >= 0 && hint <= max)
523     {
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 );
527     }
528
529     /* then do a binary search */
530     while (min <= max)
531     {
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;
538     }
539     return NULL;
540
541 }
542
543
544 /*************************************************************************
545  *              import_dll
546  *
547  * Import the dll specified by the given import descriptor.
548  * The loader_section must be locked while calling this function.
549  */
550 static WINE_MODREF *import_dll( HMODULE module, const IMAGE_IMPORT_DESCRIPTOR *descr, LPCWSTR load_path )
551 {
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;
565
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;
571
572     while (len && name[len-1] == ' ') len--;  /* remove trailing spaces */
573
574     if (len * sizeof(WCHAR) < sizeof(buffer))
575     {
576         ascii_to_unicode( buffer, name, len );
577         buffer[len] = 0;
578         status = load_dll( load_path, buffer, 0, &wmImp );
579     }
580     else  /* need to allocate a larger buffer */
581     {
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 );
588     }
589
590     if (status)
591     {
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;
599     }
600
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 );
608
609     imp_mod = wmImp->ldr.BaseAddress;
610     exports = RtlImageDirectoryEntryToData( imp_mod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
611
612     if (!exports)
613     {
614         /* set all imported function to deadbeef */
615         while (import_list->u1.Ordinal)
616         {
617             if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
618             {
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) );
622             }
623             else
624             {
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 );
628             }
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++;
634         }
635         goto done;
636     }
637
638     while (import_list->u1.Ordinal)
639     {
640         if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
641         {
642             int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
643
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)
647             {
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 );
652             }
653             TRACE_(imports)("--- Ordinal %s.%d = %p\n", name, ordinal, (void *)thunk_list->u1.Function );
654         }
655         else  /* import by name */
656         {
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)
663             {
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 );
668             }
669             TRACE_(imports)("--- %s %s.%d = %p\n",
670                             pe_name->Name, name, pe_name->Hint, (void *)thunk_list->u1.Function);
671         }
672         import_list++;
673         thunk_list++;
674     }
675
676 done:
677     /* restore old protection of the import address table */
678     NtProtectVirtualMemory( NtCurrentProcess(), &protect_base, &protect_size, protect_old, NULL );
679     return wmImp;
680 }
681
682
683 /***********************************************************************
684  *           create_module_activation_context
685  */
686 static NTSTATUS create_module_activation_context( LDR_MODULE *module )
687 {
688     NTSTATUS status;
689     LDR_RESOURCE_INFO info;
690     const IMAGE_RESOURCE_DATA_ENTRY *entry;
691
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 )))
696     {
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 );
704     }
705     return status;
706 }
707
708
709 /****************************************************************
710  *       fixup_imports
711  *
712  * Fixup all imports of a given module.
713  * The loader_section must be locked while calling this function.
714  */
715 static NTSTATUS fixup_imports( WINE_MODREF *wm, LPCWSTR load_path )
716 {
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;
723
724     if (!(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS)) return STATUS_SUCCESS;  /* already done */
725     wm->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
726
727     if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
728                                                   IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
729         return STATUS_SUCCESS;
730
731     nb_imports = 0;
732     while (imports[nb_imports].Name && imports[nb_imports].FirstThunk) nb_imports++;
733
734     if (!nb_imports) return STATUS_SUCCESS;  /* no imports */
735
736     if (!create_module_activation_context( &wm->ldr ))
737         RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
738
739     /* Allocate module dependency list */
740     wm->nDeps = nb_imports;
741     wm->deps  = RtlAllocateHeap( GetProcessHeap(), 0, nb_imports*sizeof(WINE_MODREF *) );
742
743     /* load the imported modules. They are automatically
744      * added to the modref list of the process.
745      */
746     prev = current_modref;
747     current_modref = wm;
748     status = STATUS_SUCCESS;
749     for (i = 0; i < nb_imports; i++)
750     {
751         if (!(wm->deps[i] = import_dll( wm->ldr.BaseAddress, &imports[i], load_path )))
752             status = STATUS_DLL_NOT_FOUND;
753     }
754     current_modref = prev;
755     if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
756     return status;
757 }
758
759
760 /*************************************************************************
761  *              is_dll_native_subsystem
762  *
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.
766  */
767 static BOOL is_dll_native_subsystem( HMODULE module, const IMAGE_NT_HEADERS *nt, LPCWSTR filename )
768 {
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];
774
775     if (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_NATIVE) return FALSE;
776     if (nt->OptionalHeader.SectionAlignment < page_size) return TRUE;
777
778     if ((imports = RtlImageDirectoryEntryToData( module, TRUE,
779                                                  IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
780     {
781         for (i = 0; imports[i].Name; i++)
782         {
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 ))
788             {
789                 TRACE( "%s imports %s, assuming not native\n", debugstr_w(filename), debugstr_w(buffer) );
790                 return FALSE;
791             }
792         }
793     }
794     return TRUE;
795 }
796
797
798 /*************************************************************************
799  *              alloc_module
800  *
801  * Allocate a WINE_MODREF structure and add it to the process list
802  * The loader_section must be locked while calling this function.
803  */
804 static WINE_MODREF *alloc_module( HMODULE hModule, LPCWSTR filename )
805 {
806     WINE_MODREF *wm;
807     const WCHAR *p;
808     const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
809     PLIST_ENTRY entry, mark;
810
811     if (!(wm = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm) ))) return NULL;
812
813     wm->nDeps    = 0;
814     wm->deps     = NULL;
815
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;
826
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 );
831
832     if ((nt->FileHeader.Characteristics & IMAGE_FILE_DLL) && !is_dll_native_subsystem( hModule, nt, p ))
833     {
834         wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
835         if (nt->OptionalHeader.AddressOfEntryPoint)
836             wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
837     }
838
839     InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
840                    &wm->ldr.InLoadOrderModuleList);
841
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)
845     {
846         if (CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList)->BaseAddress > wm->ldr.BaseAddress)
847             break;
848     }
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;
853
854     /* wait until init is called for inserting into this list */
855     wm->ldr.InInitializationOrderModuleList.Flink = NULL;
856     wm->ldr.InInitializationOrderModuleList.Blink = NULL;
857
858     if (!(nt->OptionalHeader.DllCharacteristics & IMAGE_DLLCHARACTERISTICS_NX_COMPAT))
859     {
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) );
863     }
864     return wm;
865 }
866
867
868 /*************************************************************************
869  *              alloc_process_tls
870  *
871  * Allocate the process-wide structure for module TLS storage.
872  */
873 static NTSTATUS alloc_process_tls(void)
874 {
875     PLIST_ENTRY mark, entry;
876     PLDR_MODULE mod;
877     const IMAGE_TLS_DIRECTORY *dir;
878     ULONG size, i;
879
880     mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
881     for (entry = mark->Flink; entry != mark; entry = entry->Flink)
882     {
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++;
891     }
892     if (!tls_module_count) return STATUS_SUCCESS;
893
894     TRACE( "count %u size %u\n", tls_module_count, tls_total_size );
895
896     tls_dirs = RtlAllocateHeap( GetProcessHeap(), 0, tls_module_count * sizeof(*tls_dirs) );
897     if (!tls_dirs) return STATUS_NO_MEMORY;
898
899     for (i = 0, entry = mark->Flink; entry != mark; entry = entry->Flink)
900     {
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++;
910     }
911     return STATUS_SUCCESS;
912 }
913
914
915 /*************************************************************************
916  *              alloc_thread_tls
917  *
918  * Allocate the per-thread structure for module TLS storage.
919  */
920 static NTSTATUS alloc_thread_tls(void)
921 {
922     void **pointers;
923     char *data;
924     UINT i, size;
925
926     if (!tls_module_count) return STATUS_SUCCESS;
927
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;
932
933     for (i = 0; i < tls_module_count; i++)
934     {
935         const IMAGE_TLS_DIRECTORY *dir = tls_dirs[i];
936         size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
937
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 );
941
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 );
946     }
947     NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
948     return STATUS_SUCCESS;
949 }
950
951
952 /*************************************************************************
953  *              call_tls_callbacks
954  */
955 static void call_tls_callbacks( HMODULE module, UINT reason )
956 {
957     const IMAGE_TLS_DIRECTORY *dir;
958     const PIMAGE_TLS_CALLBACK *callback;
959     ULONG dirsize;
960
961     dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
962     if (!dir || !dir->AddressOfCallBacks) return;
963
964     for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
965     {
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
970         {
971             (*callback)( module, reason, NULL );
972         }
973         __EXCEPT_ALL
974         {
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;
979         }
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] );
984     }
985 }
986
987
988 /*************************************************************************
989  *              MODULE_InitDLL
990  */
991 static NTSTATUS MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
992 {
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 = FALSE;
998
999     /* Skip calls for modules loaded with special load flags */
1000
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;
1004
1005     if (TRACE_ON(relay))
1006     {
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 );
1013     }
1014     else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
1015                reason_names[reason], lpReserved );
1016
1017     __TRY
1018     {
1019         retv = call_dll_entry_point( entry, module, reason, lpReserved );
1020         if (!retv)
1021             status = STATUS_DLL_INIT_FAILED;
1022     }
1023     __EXCEPT_ALL
1024     {
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();
1029     }
1030     __ENDTRY
1031
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 );
1040
1041     return status;
1042 }
1043
1044
1045 /*************************************************************************
1046  *              process_attach
1047  *
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
1050  *
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
1054  *
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
1058  *
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.)
1062  *
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.
1068  *
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*.
1073  *
1074  * The loader_section must be locked while calling this function.
1075  */
1076 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
1077 {
1078     NTSTATUS status = STATUS_SUCCESS;
1079     ULONG_PTR cookie;
1080     int i;
1081
1082     if (process_detaching) return status;
1083
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;
1088
1089     TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1090
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 );
1095
1096     /* Recursively attach all DLLs this one depends on */
1097     for ( i = 0; i < wm->nDeps; i++ )
1098     {
1099         if (!wm->deps[i]) continue;
1100         if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
1101     }
1102
1103     /* Call DLL entry point */
1104     if (status == STATUS_SUCCESS)
1105     {
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
1112         {
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));
1117         }
1118         current_modref = prev;
1119     }
1120
1121     if (!wm->ldr.InInitializationOrderModuleList.Flink)
1122         InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
1123                        &wm->ldr.InInitializationOrderModuleList);
1124
1125     if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
1126     /* Remove recursion flag */
1127     wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
1128
1129     TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1130     return status;
1131 }
1132
1133
1134 /**********************************************************************
1135  *          attach_implicitly_loaded_dlls
1136  *
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.
1139  */
1140 static void attach_implicitly_loaded_dlls( LPVOID reserved )
1141 {
1142     for (;;)
1143     {
1144         PLIST_ENTRY mark, entry;
1145
1146         mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1147         for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1148         {
1149             LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1150
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 */
1156         }
1157         if (entry == mark) break;  /* nothing found */
1158     }
1159 }
1160
1161
1162 /*************************************************************************
1163  *              process_detach
1164  *
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.
1168  */
1169 static void process_detach( BOOL bForceDetach, LPVOID lpReserved )
1170 {
1171     PLIST_ENTRY mark, entry;
1172     PLDR_MODULE mod;
1173
1174     RtlEnterCriticalSection( &loader_section );
1175     if (bForceDetach) process_detaching = 1;
1176     mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1177     do
1178     {
1179         for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1180         {
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;
1188
1189             /* Call detach notification */
1190             mod->Flags &= ~LDR_PROCESS_ATTACHED;
1191             MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr), 
1192                             DLL_PROCESS_DETACH, lpReserved );
1193
1194             /* Restart at head of WINE_MODREF list, as entries might have
1195                been added and/or removed while performing the call ... */
1196             break;
1197         }
1198     } while (entry != mark);
1199
1200     RtlLeaveCriticalSection( &loader_section );
1201 }
1202
1203 /*************************************************************************
1204  *              MODULE_DllThreadAttach
1205  *
1206  * Send DLL thread attach notifications. These are sent in the
1207  * reverse sequence of process detach notification.
1208  *
1209  */
1210 NTSTATUS MODULE_DllThreadAttach( LPVOID lpReserved )
1211 {
1212     PLIST_ENTRY mark, entry;
1213     PLDR_MODULE mod;
1214     NTSTATUS    status;
1215
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 */
1219
1220     RtlEnterCriticalSection( &loader_section );
1221
1222     if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto done;
1223
1224     mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1225     for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1226     {
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;
1233
1234         MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1235                         DLL_THREAD_ATTACH, lpReserved );
1236     }
1237
1238 done:
1239     RtlLeaveCriticalSection( &loader_section );
1240     return status;
1241 }
1242
1243 /******************************************************************
1244  *              LdrDisableThreadCalloutsForDll (NTDLL.@)
1245  *
1246  */
1247 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1248 {
1249     WINE_MODREF *wm;
1250     NTSTATUS    ret = STATUS_SUCCESS;
1251
1252     RtlEnterCriticalSection( &loader_section );
1253
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;
1259
1260     RtlLeaveCriticalSection( &loader_section );
1261
1262     return ret;
1263 }
1264
1265 /******************************************************************
1266  *              LdrFindEntryForAddress (NTDLL.@)
1267  *
1268  * The loader_section must be locked while calling this function
1269  */
1270 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
1271 {
1272     PLIST_ENTRY mark, entry;
1273     PLDR_MODULE mod;
1274
1275     mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1276     for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1277     {
1278         mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
1279         if (mod->BaseAddress <= addr &&
1280             (const char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
1281         {
1282             *pmod = mod;
1283             return STATUS_SUCCESS;
1284         }
1285         if (mod->BaseAddress > addr) break;
1286     }
1287     return STATUS_NO_MORE_ENTRIES;
1288 }
1289
1290 /******************************************************************
1291  *              LdrLockLoaderLock  (NTDLL.@)
1292  *
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).
1296  */
1297 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG *magic )
1298 {
1299     if (flags) FIXME( "flags %x not supported\n", flags );
1300
1301     if (result) *result = 1;
1302     if (!magic) return STATUS_INVALID_PARAMETER_3;
1303     RtlEnterCriticalSection( &loader_section );
1304     *magic = GetCurrentThreadId();
1305     return STATUS_SUCCESS;
1306 }
1307
1308
1309 /******************************************************************
1310  *              LdrUnlockLoaderUnlock  (NTDLL.@)
1311  */
1312 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG magic )
1313 {
1314     if (magic)
1315     {
1316         if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1317         RtlLeaveCriticalSection( &loader_section );
1318     }
1319     return STATUS_SUCCESS;
1320 }
1321
1322
1323 /******************************************************************
1324  *              LdrGetProcedureAddress  (NTDLL.@)
1325  */
1326 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1327                                        ULONG ord, PVOID *address)
1328 {
1329     IMAGE_EXPORT_DIRECTORY *exports;
1330     DWORD exp_size;
1331     NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1332
1333     RtlEnterCriticalSection( &loader_section );
1334
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 )))
1339     {
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)
1344         {
1345             *address = proc;
1346             ret = STATUS_SUCCESS;
1347         }
1348     }
1349
1350     RtlLeaveCriticalSection( &loader_section );
1351     return ret;
1352 }
1353
1354
1355 /***********************************************************************
1356  *           is_fake_dll
1357  *
1358  * Check if a loaded native dll is a Wine fake dll.
1359  */
1360 static BOOL is_fake_dll( HANDLE handle )
1361 {
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;
1367
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;
1375 }
1376
1377
1378 /***********************************************************************
1379  *           get_builtin_fullname
1380  *
1381  * Build the full pathname for a builtin dll.
1382  */
1383 static WCHAR *get_builtin_fullname( const WCHAR *path, const char *filename )
1384 {
1385     static const WCHAR soW[] = {'.','s','o',0};
1386     WCHAR *p, *fullname;
1387     size_t i, len = strlen(filename);
1388
1389     /* check if path can correspond to the dll we have */
1390     if (path && (p = strrchrW( path, '\\' )))
1391     {
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 )))
1396         {
1397             /* the filename matches, use path as the full path */
1398             len += p - path;
1399             if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
1400             {
1401                 memcpy( fullname, path, len * sizeof(WCHAR) );
1402                 fullname[len] = 0;
1403             }
1404             return fullname;
1405         }
1406     }
1407
1408     if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0,
1409                                      system_dir.MaximumLength + (len + 1) * sizeof(WCHAR) )))
1410     {
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 );
1415     }
1416     return fullname;
1417 }
1418
1419
1420 /***********************************************************************
1421  *           load_builtin_callback
1422  *
1423  * Load a library in memory; callback function for wine_dll_register
1424  */
1425 static void load_builtin_callback( void *module, const char *filename )
1426 {
1427     static const WCHAR emptyW[1];
1428     IMAGE_NT_HEADERS *nt;
1429     WINE_MODREF *wm;
1430     WCHAR *fullname;
1431     const WCHAR *load_path;
1432
1433     if (!module)
1434     {
1435         ERR("could not map image for %s\n", filename ? filename : "main exe" );
1436         return;
1437     }
1438     if (!(nt = RtlImageNtHeader( module )))
1439     {
1440         ERR( "bad module for %s\n", filename ? filename : "main exe" );
1441         builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1442         return;
1443     }
1444
1445     virtual_create_builtin_view( module );
1446
1447     /* create the MODREF */
1448
1449     if (!(fullname = get_builtin_fullname( builtin_load_info->filename, filename )))
1450     {
1451         ERR( "can't load %s\n", filename );
1452         builtin_load_info->status = STATUS_NO_MEMORY;
1453         return;
1454     }
1455
1456     wm = alloc_module( module, fullname );
1457     RtlFreeHeap( GetProcessHeap(), 0, fullname );
1458     if (!wm)
1459     {
1460         ERR( "can't load %s\n", filename );
1461         builtin_load_info->status = STATUS_NO_MEMORY;
1462         return;
1463     }
1464     wm->ldr.Flags |= LDR_WINE_INTERNAL;
1465
1466     if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
1467         !NtCurrentTeb()->Peb->ImageBaseAddress)  /* if we already have an executable, ignore this one */
1468     {
1469         NtCurrentTeb()->Peb->ImageBaseAddress = module;
1470     }
1471     else
1472     {
1473         /* fixup imports */
1474
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)
1479         {
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;
1486         }
1487     }
1488
1489     builtin_load_info->wm = wm;
1490     TRACE( "loaded %s %p %p\n", filename, wm, module );
1491
1492     /* send the DLL load event */
1493
1494     SERVER_START_REQ( load_dll )
1495     {
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 );
1504     }
1505     SERVER_END_REQ;
1506
1507     /* setup relay debugging entry points */
1508     if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1509 }
1510
1511
1512 /******************************************************************************
1513  *      load_native_dll  (internal)
1514  */
1515 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1516                                  DWORD flags, WINE_MODREF** pwm )
1517 {
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;
1525
1526     TRACE("Trying native dll %s\n", debugstr_w(name));
1527
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;
1532
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;
1537
1538     /* create the MODREF */
1539
1540     if (!(wm = alloc_module( module, name )))
1541     {
1542         status = STATUS_NO_MEMORY;
1543         goto done;
1544     }
1545
1546     /* fixup imports */
1547
1548     if (!(flags & DONT_RESOLVE_DLL_REFERENCES))
1549     {
1550         if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1551         {
1552             /* the module has only be inserted in the load & memory order lists */
1553             RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1554             RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1555
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.
1562              */
1563             goto done;
1564         }
1565     }
1566
1567     /* send DLL load event */
1568
1569     nt = RtlImageNtHeader( module );
1570
1571     SERVER_START_REQ( load_dll )
1572     {
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 );
1581     }
1582     SERVER_END_REQ;
1583
1584     if ((wm->ldr.Flags & LDR_IMAGE_IS_DLL) && TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1585
1586     TRACE_(loaddll)( "Loaded %s at %p: native\n", debugstr_w(wm->ldr.FullDllName.Buffer), module );
1587
1588     wm->ldr.LoadCount = 1;
1589     *pwm = wm;
1590     status = STATUS_SUCCESS;
1591 done:
1592     NtClose( mapping );
1593     return status;
1594 }
1595
1596
1597 /***********************************************************************
1598  *           load_builtin_dll
1599  */
1600 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, HANDLE file,
1601                                   DWORD flags, WINE_MODREF** pwm )
1602 {
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;
1608
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;
1613
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
1618      */
1619     info.load_path = load_path;
1620     info.filename  = NULL;
1621     info.status    = STATUS_SUCCESS;
1622     info.wm        = NULL;
1623
1624     if (file)  /* we have a real file, try to load it */
1625     {
1626         UNICODE_STRING nt_name;
1627         ANSI_STRING unix_name;
1628
1629         TRACE("Trying built-in %s\n", debugstr_w(path));
1630
1631         if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1632             return STATUS_DLL_NOT_FOUND;
1633
1634         if (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ))
1635         {
1636             RtlFreeUnicodeString( &nt_name );
1637             return STATUS_DLL_NOT_FOUND;
1638         }
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)
1647         {
1648             WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path), error );
1649             return STATUS_INVALID_IMAGE_FORMAT;
1650         }
1651     }
1652     else
1653     {
1654         int file_exists;
1655
1656         TRACE("Trying built-in %s\n", debugstr_w(name));
1657
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++)
1662         {
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';
1666         }
1667
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)
1673         {
1674             if (!file_exists)
1675             {
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;
1679             }
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;
1683         }
1684     }
1685
1686     if (info.status != STATUS_SUCCESS)
1687     {
1688         wine_dll_unload( handle );
1689         return info.status;
1690     }
1691
1692     if (!info.wm)
1693     {
1694         PLIST_ENTRY mark, entry;
1695
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. */
1698
1699         mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1700         for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1701         {
1702             LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1703             if (mod->Flags & LDR_WINE_INTERNAL && mod->SectionHandle == handle)
1704             {
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;
1709             }
1710         }
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++;
1714     }
1715     else
1716     {
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;
1720     }
1721
1722     *pwm = info.wm;
1723     return STATUS_SUCCESS;
1724 }
1725
1726
1727 /***********************************************************************
1728  *      find_actctx_dll
1729  *
1730  * Find the full path (if any) of the dll from the activation context.
1731  */
1732 static NTSTATUS find_actctx_dll( LPCWSTR libname, LPWSTR *fullname )
1733 {
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};
1736
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;
1743
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;
1750
1751     for (;;)
1752     {
1753         if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1754         {
1755             status = STATUS_NO_MEMORY;
1756             goto done;
1757         }
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 */
1766     }
1767
1768     if (!info->lpAssemblyManifestPath || !info->lpAssemblyDirectoryName)
1769     {
1770         status = STATUS_SXS_KEY_NOT_FOUND;
1771         goto done;
1772     }
1773
1774     if ((p = strrchrW( info->lpAssemblyManifestPath, '\\' )))
1775     {
1776         DWORD dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1777
1778         p++;
1779         if (strncmpiW( p, info->lpAssemblyDirectoryName, dirlen ) || strcmpiW( p + dirlen, dotManifestW ))
1780         {
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 )))
1786             {
1787                 status = STATUS_NO_MEMORY;
1788                 goto done;
1789             }
1790             memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
1791             p += dirlen;
1792             strcpyW( p, libname );
1793             goto done;
1794         }
1795     }
1796
1797     needed = (strlenW(user_shared_data->NtSystemRoot) * sizeof(WCHAR) +
1798               sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength + nameW.Length + 2*sizeof(WCHAR));
1799
1800     if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1801     {
1802         status = STATUS_NO_MEMORY;
1803         goto done;
1804     }
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;
1817 }
1818
1819
1820 /***********************************************************************
1821  *      find_dll_file
1822  *
1823  * Find the file (or already loaded module) for a given dll name.
1824  */
1825 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
1826                                WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
1827 {
1828     OBJECT_ATTRIBUTES attr;
1829     IO_STATUS_BLOCK io;
1830     UNICODE_STRING nt_name;
1831     WCHAR *file_part, *ext, *dllname;
1832     ULONG len;
1833
1834     /* first append .dll if needed */
1835
1836     dllname = NULL;
1837     if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
1838     {
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;
1845     }
1846
1847     nt_name.Buffer = NULL;
1848
1849     if (!contains_path( libname ))
1850     {
1851         NTSTATUS status;
1852         WCHAR *fullname = NULL;
1853
1854         if ((*pwm = find_basename_module( libname )) != NULL) goto found;
1855
1856         status = find_actctx_dll( libname, &fullname );
1857         if (status == STATUS_SUCCESS)
1858         {
1859             TRACE ("found %s for %s\n", debugstr_w(fullname), debugstr_w(libname) );
1860             RtlFreeHeap( GetProcessHeap(), 0, dllname );
1861             libname = dllname = fullname;
1862         }
1863         else if (status != STATUS_SXS_KEY_NOT_FOUND)
1864         {
1865             RtlFreeHeap( GetProcessHeap(), 0, dllname );
1866             return status;
1867         }
1868     }
1869
1870     if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
1871     {
1872         /* we need to search for it */
1873         len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
1874         if (len)
1875         {
1876             if (len >= *size) goto overflow;
1877             if ((*pwm = find_fullname_module( filename )) || !handle) goto found;
1878
1879             if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
1880             {
1881                 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1882                 return STATUS_NO_MEMORY;
1883             }
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;
1892         }
1893
1894         /* not found */
1895
1896         if (!contains_path( libname ))
1897         {
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;
1904         }
1905     }
1906
1907     /* absolute path name, or relative path name but not found above */
1908
1909     if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
1910     {
1911         RtlFreeHeap( GetProcessHeap(), 0, dllname );
1912         return STATUS_NO_MEMORY;
1913     }
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)
1918     {
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;
1926     }
1927 found:
1928     RtlFreeUnicodeString( &nt_name );
1929     RtlFreeHeap( GetProcessHeap(), 0, dllname );
1930     return STATUS_SUCCESS;
1931
1932 overflow:
1933     RtlFreeUnicodeString( &nt_name );
1934     RtlFreeHeap( GetProcessHeap(), 0, dllname );
1935     *size = len + sizeof(WCHAR);
1936     return STATUS_BUFFER_TOO_SMALL;
1937 }
1938
1939
1940 /***********************************************************************
1941  *      load_dll  (internal)
1942  *
1943  * Load a PE style module according to the load order.
1944  * The loader_section must be locked while calling this function.
1945  */
1946 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
1947 {
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;
1955
1956     TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
1957
1958     *pwm = NULL;
1959     filename = buffer;
1960     size = sizeof(buffer);
1961     for (;;)
1962     {
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;
1969     }
1970
1971     if (*pwm)  /* found already loaded module */
1972     {
1973         if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
1974
1975         if (!(flags & DONT_RESOLVE_DLL_REFERENCES)) fixup_imports( *pwm, load_path );
1976
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;
1982     }
1983
1984     main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
1985     loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
1986
1987     if (handle && is_fake_dll( handle ))
1988     {
1989         TRACE( "%s is a fake Wine dll\n", debugstr_w(filename) );
1990         NtClose( handle );
1991         handle = 0;
1992     }
1993
1994     switch(loadorder)
1995     {
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
2006         {
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 );
2011         }
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))
2025         {
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;
2030         }
2031         if (nts == STATUS_DLL_NOT_FOUND && loadorder != LO_BUILTIN)
2032             nts = load_native_dll( load_path, filename, handle, flags, pwm );
2033         break;
2034     }
2035
2036     if (nts == STATUS_SUCCESS)
2037     {
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;
2045     }
2046
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;
2051 }
2052
2053 /******************************************************************
2054  *              LdrLoadDll (NTDLL.@)
2055  */
2056 NTSTATUS WINAPI DECLSPEC_HOTPATCH LdrLoadDll(LPCWSTR path_name, DWORD flags,
2057                                              const UNICODE_STRING *libname, HMODULE* hModule)
2058 {
2059     WINE_MODREF *wm;
2060     NTSTATUS nts;
2061
2062     RtlEnterCriticalSection( &loader_section );
2063
2064     if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2065     nts = load_dll( path_name, libname->Buffer, flags, &wm );
2066
2067     if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
2068     {
2069         nts = process_attach( wm, NULL );
2070         if (nts != STATUS_SUCCESS)
2071         {
2072             LdrUnloadDll(wm->ldr.BaseAddress);
2073             wm = NULL;
2074         }
2075     }
2076     *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
2077
2078     RtlLeaveCriticalSection( &loader_section );
2079     return nts;
2080 }
2081
2082
2083 /******************************************************************
2084  *              LdrGetDllHandle (NTDLL.@)
2085  */
2086 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
2087 {
2088     NTSTATUS status;
2089     WCHAR buffer[128];
2090     WCHAR *filename;
2091     ULONG size;
2092     WINE_MODREF *wm;
2093
2094     RtlEnterCriticalSection( &loader_section );
2095
2096     if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2097
2098     filename = buffer;
2099     size = sizeof(buffer);
2100     for (;;)
2101     {
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 )))
2107         {
2108             status = STATUS_NO_MEMORY;
2109             break;
2110         }
2111     }
2112
2113     if (status == STATUS_SUCCESS)
2114     {
2115         if (wm) *base = wm->ldr.BaseAddress;
2116         else status = STATUS_DLL_NOT_FOUND;
2117     }
2118
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;
2122 }
2123
2124
2125 /******************************************************************
2126  *              LdrAddRefDll (NTDLL.@)
2127  */
2128 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
2129 {
2130     NTSTATUS ret = STATUS_SUCCESS;
2131     WINE_MODREF *wm;
2132
2133     if (flags) FIXME( "%p flags %x not implemented\n", module, flags );
2134
2135     RtlEnterCriticalSection( &loader_section );
2136
2137     if ((wm = get_modref( module )))
2138     {
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 );
2141     }
2142     else ret = STATUS_INVALID_PARAMETER;
2143
2144     RtlLeaveCriticalSection( &loader_section );
2145     return ret;
2146 }
2147
2148
2149 /***********************************************************************
2150  *           LdrProcessRelocationBlock  (NTDLL.@)
2151  *
2152  * Apply relocations to a given page of a mapped PE image.
2153  */
2154 IMAGE_BASE_RELOCATION * WINAPI LdrProcessRelocationBlock( void *page, UINT count,
2155                                                           USHORT *relocs, INT_PTR delta )
2156 {
2157     while (count--)
2158     {
2159         USHORT offset = *relocs & 0xfff;
2160         int type = *relocs >> 12;
2161         switch(type)
2162         {
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 #elif defined(__arm__)
2179         case IMAGE_REL_BASED_THUMB_MOV32:
2180         {
2181             DWORD inst = *(INT_PTR *)((char *)page + offset);
2182             DWORD imm16 = ((inst << 1) & 0x0800) + ((inst << 12) & 0xf000) +
2183                           ((inst >> 20) & 0x0700) + ((inst >> 16) & 0x00ff);
2184
2185             if ((inst & 0x8000fbf0) != 0x0000f240)
2186                 ERR("wrong Thumb2 instruction %08x, expected MOVW\n", inst);
2187
2188             imm16 += LOWORD(delta);
2189             if (imm16 > 0xffff)
2190                 ERR("resulting immediate value won't fit: %08x\n", imm16);
2191             *(INT_PTR *)((char *)page + offset) = (inst & 0x8f00fbf0) + ((imm16 >> 1) & 0x0400) +
2192                                                   ((imm16 >> 12) & 0x000f) +
2193                                                   ((imm16 << 20) & 0x70000000) +
2194                                                   ((imm16 << 16) & 0xff0000);
2195
2196             if (delta > 0xffff)
2197             {
2198                 inst = *(INT_PTR *)((char *)page + offset + 4);
2199                 imm16 = ((inst << 1) & 0x0800) + ((inst << 12) & 0xf000) +
2200                         ((inst >> 20) & 0x0700) + ((inst >> 16) & 0x00ff);
2201
2202                 if ((inst & 0x8000fbf0) != 0x0000f2c0)
2203                     ERR("wrong Thumb2 instruction %08x, expected MOVT\n", inst);
2204
2205                 imm16 += HIWORD(delta);
2206                 if (imm16 > 0xffff)
2207                     ERR("resulting immediate value won't fit: %08x\n", imm16);
2208                 *(INT_PTR *)((char *)page + offset + 4) = (inst & 0x8f00fbf0) +
2209                                                           ((imm16 >> 1) & 0x0400) +
2210                                                           ((imm16 >> 12) & 0x000f) +
2211                                                           ((imm16 << 20) & 0x70000000) +
2212                                                           ((imm16 << 16) & 0xff0000);
2213             }
2214         }
2215             break;
2216 #endif
2217         default:
2218             FIXME("Unknown/unsupported fixup type %x.\n", type);
2219             return NULL;
2220         }
2221         relocs++;
2222     }
2223     return (IMAGE_BASE_RELOCATION *)relocs;  /* return address of next block */
2224 }
2225
2226
2227 /******************************************************************
2228  *              LdrQueryProcessModuleInformation
2229  *
2230  */
2231 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi, 
2232                                                  ULONG buf_size, ULONG* req_size)
2233 {
2234     SYSTEM_MODULE*      sm = &smi->Modules[0];
2235     ULONG               size = sizeof(ULONG);
2236     NTSTATUS            nts = STATUS_SUCCESS;
2237     ANSI_STRING         str;
2238     char*               ptr;
2239     PLIST_ENTRY         mark, entry;
2240     PLDR_MODULE         mod;
2241     WORD id = 0;
2242
2243     smi->ModulesCount = 0;
2244
2245     RtlEnterCriticalSection( &loader_section );
2246     mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2247     for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2248     {
2249         mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2250         size += sizeof(*sm);
2251         if (size <= buf_size)
2252         {
2253             sm->Reserved1 = 0; /* FIXME */
2254             sm->Reserved2 = 0; /* FIXME */
2255             sm->ImageBaseAddress = mod->BaseAddress;
2256             sm->ImageSize = mod->SizeOfImage;
2257             sm->Flags = mod->Flags;
2258             sm->Id = id++;
2259             sm->Rank = 0; /* FIXME */
2260             sm->Unknown = 0; /* FIXME */
2261             str.Length = 0;
2262             str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
2263             str.Buffer = (char*)sm->Name;
2264             RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
2265             ptr = strrchr(str.Buffer, '\\');
2266             sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
2267
2268             smi->ModulesCount++;
2269             sm++;
2270         }
2271         else nts = STATUS_INFO_LENGTH_MISMATCH;
2272     }
2273     RtlLeaveCriticalSection( &loader_section );
2274
2275     if (req_size) *req_size = size;
2276
2277     return nts;
2278 }
2279
2280
2281 static NTSTATUS query_dword_option( HANDLE hkey, LPCWSTR name, ULONG *value )
2282 {
2283     NTSTATUS status;
2284     UNICODE_STRING str;
2285     ULONG size;
2286     WCHAR buffer[64];
2287     KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
2288
2289     RtlInitUnicodeString( &str, name );
2290
2291     size = sizeof(buffer) - sizeof(WCHAR);
2292     if ((status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size )))
2293         return status;
2294
2295     if (info->Type != REG_DWORD)
2296     {
2297         buffer[size / sizeof(WCHAR)] = 0;
2298         *value = strtoulW( (WCHAR *)info->Data, 0, 16 );
2299     }
2300     else memcpy( value, info->Data, sizeof(*value) );
2301     return status;
2302 }
2303
2304 static NTSTATUS query_string_option( HANDLE hkey, LPCWSTR name, ULONG type,
2305                                      void *data, ULONG in_size, ULONG *out_size )
2306 {
2307     NTSTATUS status;
2308     UNICODE_STRING str;
2309     ULONG size;
2310     char *buffer;
2311     KEY_VALUE_PARTIAL_INFORMATION *info;
2312     static const int info_size = FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data );
2313
2314     RtlInitUnicodeString( &str, name );
2315
2316     size = info_size + in_size;
2317     if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
2318     info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
2319     status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size );
2320     if (!status || status == STATUS_BUFFER_OVERFLOW)
2321     {
2322         if (out_size) *out_size = info->DataLength;
2323         if (data && !status) memcpy( data, info->Data, info->DataLength );
2324     }
2325     RtlFreeHeap( GetProcessHeap(), 0, buffer );
2326     return status;
2327 }
2328
2329
2330 /******************************************************************
2331  *              LdrQueryImageFileExecutionOptions  (NTDLL.@)
2332  */
2333 NTSTATUS WINAPI LdrQueryImageFileExecutionOptions( const UNICODE_STRING *key, LPCWSTR value, ULONG type,
2334                                                    void *data, ULONG in_size, ULONG *out_size )
2335 {
2336     static const WCHAR optionsW[] = {'M','a','c','h','i','n','e','\\',
2337                                      'S','o','f','t','w','a','r','e','\\',
2338                                      'M','i','c','r','o','s','o','f','t','\\',
2339                                      'W','i','n','d','o','w','s',' ','N','T','\\',
2340                                      'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
2341                                      'I','m','a','g','e',' ','F','i','l','e',' ',
2342                                      'E','x','e','c','u','t','i','o','n',' ','O','p','t','i','o','n','s','\\'};
2343     WCHAR path[MAX_PATH + sizeof(optionsW)/sizeof(WCHAR)];
2344     OBJECT_ATTRIBUTES attr;
2345     UNICODE_STRING name_str;
2346     HANDLE hkey;
2347     NTSTATUS status;
2348     ULONG len;
2349     WCHAR *p;
2350
2351     attr.Length = sizeof(attr);
2352     attr.RootDirectory = 0;
2353     attr.ObjectName = &name_str;
2354     attr.Attributes = OBJ_CASE_INSENSITIVE;
2355     attr.SecurityDescriptor = NULL;
2356     attr.SecurityQualityOfService = NULL;
2357
2358     if ((p = memrchrW( key->Buffer, '\\', key->Length / sizeof(WCHAR) ))) p++;
2359     else p = key->Buffer;
2360     len = key->Length - (p - key->Buffer) * sizeof(WCHAR);
2361     name_str.Buffer = path;
2362     name_str.Length = sizeof(optionsW) + len;
2363     name_str.MaximumLength = name_str.Length;
2364     memcpy( path, optionsW, sizeof(optionsW) );
2365     memcpy( path + sizeof(optionsW)/sizeof(WCHAR), p, len );
2366     if ((status = NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr ))) return status;
2367
2368     if (type == REG_DWORD)
2369     {
2370         if (out_size) *out_size = sizeof(ULONG);
2371         if (in_size >= sizeof(ULONG)) status = query_dword_option( hkey, value, data );
2372         else status = STATUS_BUFFER_OVERFLOW;
2373     }
2374     else status = query_string_option( hkey, value, type, data, in_size, out_size );
2375
2376     NtClose( hkey );
2377     return status;
2378 }
2379
2380
2381 /******************************************************************
2382  *              RtlDllShutdownInProgress  (NTDLL.@)
2383  */
2384 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
2385 {
2386     return process_detaching;
2387 }
2388
2389
2390 /******************************************************************
2391  *              LdrShutdownProcess (NTDLL.@)
2392  *
2393  */
2394 void WINAPI LdrShutdownProcess(void)
2395 {
2396     TRACE("()\n");
2397     process_detach( TRUE, (LPVOID)1 );
2398 }
2399
2400 /******************************************************************
2401  *              LdrShutdownThread (NTDLL.@)
2402  *
2403  */
2404 void WINAPI LdrShutdownThread(void)
2405 {
2406     PLIST_ENTRY mark, entry;
2407     PLDR_MODULE mod;
2408
2409     TRACE("()\n");
2410
2411     /* don't do any detach calls if process is exiting */
2412     if (process_detaching) return;
2413     /* FIXME: there is still a race here */
2414
2415     RtlEnterCriticalSection( &loader_section );
2416
2417     mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2418     for (entry = mark->Blink; entry != mark; entry = entry->Blink)
2419     {
2420         mod = CONTAINING_RECORD(entry, LDR_MODULE, 
2421                                 InInitializationOrderModuleList);
2422         if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
2423             continue;
2424         if ( mod->Flags & LDR_NO_DLL_CALLS )
2425             continue;
2426
2427         MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr), 
2428                         DLL_THREAD_DETACH, NULL );
2429     }
2430
2431     RtlLeaveCriticalSection( &loader_section );
2432     RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->ThreadLocalStoragePointer );
2433 }
2434
2435
2436 /***********************************************************************
2437  *           free_modref
2438  *
2439  */
2440 static void free_modref( WINE_MODREF *wm )
2441 {
2442     RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
2443     RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
2444     if (wm->ldr.InInitializationOrderModuleList.Flink)
2445         RemoveEntryList(&wm->ldr.InInitializationOrderModuleList);
2446
2447     TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
2448     if (!TRACE_ON(module))
2449         TRACE_(loaddll)("Unloaded module %s : %s\n",
2450                         debugstr_w(wm->ldr.FullDllName.Buffer),
2451                         (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
2452
2453     SERVER_START_REQ( unload_dll )
2454     {
2455         req->base = wine_server_client_ptr( wm->ldr.BaseAddress );
2456         wine_server_call( req );
2457     }
2458     SERVER_END_REQ;
2459
2460     RtlReleaseActivationContext( wm->ldr.ActivationContext );
2461     NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.BaseAddress );
2462     if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
2463     if (cached_modref == wm) cached_modref = NULL;
2464     RtlFreeUnicodeString( &wm->ldr.FullDllName );
2465     RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
2466     RtlFreeHeap( GetProcessHeap(), 0, wm );
2467 }
2468
2469 /***********************************************************************
2470  *           MODULE_FlushModrefs
2471  *
2472  * Remove all unused modrefs and call the internal unloading routines
2473  * for the library type.
2474  *
2475  * The loader_section must be locked while calling this function.
2476  */
2477 static void MODULE_FlushModrefs(void)
2478 {
2479     PLIST_ENTRY mark, entry, prev;
2480     PLDR_MODULE mod;
2481     WINE_MODREF*wm;
2482
2483     mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2484     for (entry = mark->Blink; entry != mark; entry = prev)
2485     {
2486         mod = CONTAINING_RECORD(entry, LDR_MODULE, InInitializationOrderModuleList);
2487         wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2488         prev = entry->Blink;
2489         if (!mod->LoadCount) free_modref( wm );
2490     }
2491
2492     /* check load order list too for modules that haven't been initialized yet */
2493     mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2494     for (entry = mark->Blink; entry != mark; entry = prev)
2495     {
2496         mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2497         wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2498         prev = entry->Blink;
2499         if (!mod->LoadCount) free_modref( wm );
2500     }
2501 }
2502
2503 /***********************************************************************
2504  *           MODULE_DecRefCount
2505  *
2506  * The loader_section must be locked while calling this function.
2507  */
2508 static void MODULE_DecRefCount( WINE_MODREF *wm )
2509 {
2510     int i;
2511
2512     if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
2513         return;
2514
2515     if ( wm->ldr.LoadCount <= 0 )
2516         return;
2517
2518     --wm->ldr.LoadCount;
2519     TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2520
2521     if ( wm->ldr.LoadCount == 0 )
2522     {
2523         wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
2524
2525         for ( i = 0; i < wm->nDeps; i++ )
2526             if ( wm->deps[i] )
2527                 MODULE_DecRefCount( wm->deps[i] );
2528
2529         wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
2530     }
2531 }
2532
2533 /******************************************************************
2534  *              LdrUnloadDll (NTDLL.@)
2535  *
2536  *
2537  */
2538 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
2539 {
2540     NTSTATUS retv = STATUS_SUCCESS;
2541
2542     TRACE("(%p)\n", hModule);
2543
2544     RtlEnterCriticalSection( &loader_section );
2545
2546     /* if we're stopping the whole process (and forcing the removal of all
2547      * DLLs) the library will be freed anyway
2548      */
2549     if (!process_detaching)
2550     {
2551         WINE_MODREF *wm;
2552
2553         free_lib_count++;
2554         if ((wm = get_modref( hModule )) != NULL)
2555         {
2556             TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
2557
2558             /* Recursively decrement reference counts */
2559             MODULE_DecRefCount( wm );
2560
2561             /* Call process detach notifications */
2562             if ( free_lib_count <= 1 )
2563             {
2564                 process_detach( FALSE, NULL );
2565                 MODULE_FlushModrefs();
2566             }
2567
2568             TRACE("END\n");
2569         }
2570         else
2571             retv = STATUS_DLL_NOT_FOUND;
2572
2573         free_lib_count--;
2574     }
2575
2576     RtlLeaveCriticalSection( &loader_section );
2577
2578     return retv;
2579 }
2580
2581 /***********************************************************************
2582  *           RtlImageNtHeader   (NTDLL.@)
2583  */
2584 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
2585 {
2586     IMAGE_NT_HEADERS *ret;
2587
2588     __TRY
2589     {
2590         IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
2591
2592         ret = NULL;
2593         if (dos->e_magic == IMAGE_DOS_SIGNATURE)
2594         {
2595             ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
2596             if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
2597         }
2598     }
2599     __EXCEPT_PAGE_FAULT
2600     {
2601         return NULL;
2602     }
2603     __ENDTRY
2604     return ret;
2605 }
2606
2607
2608 /***********************************************************************
2609  *           attach_process_dlls
2610  *
2611  * Initial attach to all the dlls loaded by the process.
2612  */
2613 static NTSTATUS attach_process_dlls( void *wm )
2614 {
2615     NTSTATUS status;
2616
2617     pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
2618
2619     RtlEnterCriticalSection( &loader_section );
2620     if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS)
2621     {
2622         if (last_failed_modref)
2623             ERR( "%s failed to initialize, aborting\n",
2624                  debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
2625         return status;
2626     }
2627     attach_implicitly_loaded_dlls( (LPVOID)1 );
2628     RtlLeaveCriticalSection( &loader_section );
2629     return status;
2630 }
2631
2632
2633 /***********************************************************************
2634  *           load_global_options
2635  */
2636 static void load_global_options(void)
2637 {
2638     static const WCHAR sessionW[] = {'M','a','c','h','i','n','e','\\',
2639                                      'S','y','s','t','e','m','\\',
2640                                      'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
2641                                      'C','o','n','t','r','o','l','\\',
2642                                      'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
2643     static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
2644     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};
2645     static const WCHAR heapresW[] = {'H','e','a','p','S','e','g','m','e','n','t','R','e','s','e','r','v','e',0};
2646     static const WCHAR heapcommitW[] = {'H','e','a','p','S','e','g','m','e','n','t','C','o','m','m','i','t',0};
2647     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};
2648     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};
2649
2650     OBJECT_ATTRIBUTES attr;
2651     UNICODE_STRING name_str;
2652     HANDLE hkey;
2653     ULONG value;
2654
2655     attr.Length = sizeof(attr);
2656     attr.RootDirectory = 0;
2657     attr.ObjectName = &name_str;
2658     attr.Attributes = OBJ_CASE_INSENSITIVE;
2659     attr.SecurityDescriptor = NULL;
2660     attr.SecurityQualityOfService = NULL;
2661     RtlInitUnicodeString( &name_str, sessionW );
2662
2663     if (NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr )) return;
2664
2665     query_dword_option( hkey, globalflagW, &NtCurrentTeb()->Peb->NtGlobalFlag );
2666
2667     query_dword_option( hkey, critsectW, &value );
2668     NtCurrentTeb()->Peb->CriticalSectionTimeout.QuadPart = (ULONGLONG)value * -10000000;
2669
2670     query_dword_option( hkey, heapresW, &value );
2671     NtCurrentTeb()->Peb->HeapSegmentReserve = value;
2672
2673     query_dword_option( hkey, heapcommitW, &value );
2674     NtCurrentTeb()->Peb->HeapSegmentCommit = value;
2675
2676     query_dword_option( hkey, decommittotalW, &value );
2677     NtCurrentTeb()->Peb->HeapDeCommitTotalFreeThreshold = value;
2678
2679     query_dword_option( hkey, decommitfreeW, &value );
2680     NtCurrentTeb()->Peb->HeapDeCommitFreeBlockThreshold = value;
2681
2682     NtClose( hkey );
2683 }
2684
2685
2686 /***********************************************************************
2687  *           start_process
2688  */
2689 static void start_process( void *kernel_start )
2690 {
2691     call_thread_entry_point( kernel_start, NtCurrentTeb()->Peb );
2692 }
2693
2694 /******************************************************************
2695  *              LdrInitializeThunk (NTDLL.@)
2696  *
2697  */
2698 void WINAPI LdrInitializeThunk( void *kernel_start, ULONG_PTR unknown2,
2699                                 ULONG_PTR unknown3, ULONG_PTR unknown4 )
2700 {
2701     static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
2702     NTSTATUS status;
2703     WINE_MODREF *wm;
2704     LPCWSTR load_path;
2705     PEB *peb = NtCurrentTeb()->Peb;
2706
2707     if (main_exe_file) NtClose( main_exe_file );  /* at this point the main module is created */
2708
2709     /* allocate the modref for the main exe (if not already done) */
2710     wm = get_modref( peb->ImageBaseAddress );
2711     assert( wm );
2712     if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
2713     {
2714         ERR("%s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
2715         exit(1);
2716     }
2717
2718     peb->LoaderLock = &loader_section;
2719     peb->ProcessParameters->ImagePathName = wm->ldr.FullDllName;
2720     if (!peb->ProcessParameters->WindowTitle.Buffer)
2721         peb->ProcessParameters->WindowTitle = wm->ldr.FullDllName;
2722     version_init( wm->ldr.FullDllName.Buffer );
2723     virtual_set_large_address_space();
2724
2725     LdrQueryImageFileExecutionOptions( &peb->ProcessParameters->ImagePathName, globalflagW,
2726                                        REG_DWORD, &peb->NtGlobalFlag, sizeof(peb->NtGlobalFlag), NULL );
2727
2728     /* the main exe needs to be the first in the load order list */
2729     RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
2730     InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
2731
2732     if ((status = virtual_alloc_thread_stack( NtCurrentTeb(), 0, 0 )) != STATUS_SUCCESS) goto error;
2733     if ((status = server_init_process_done()) != STATUS_SUCCESS) goto error;
2734
2735     actctx_init();
2736     load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2737     if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
2738     if ((status = alloc_process_tls()) != STATUS_SUCCESS) goto error;
2739     if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto error;
2740     heap_set_debug_flags( GetProcessHeap() );
2741
2742     status = wine_call_on_stack( attach_process_dlls, wm, NtCurrentTeb()->Tib.StackBase );
2743     if (status != STATUS_SUCCESS) goto error;
2744
2745     virtual_release_address_space();
2746     virtual_clear_thread_stack();
2747     wine_switch_to_stack( start_process, kernel_start, NtCurrentTeb()->Tib.StackBase );
2748
2749 error:
2750     ERR( "Main exe initialization for %s failed, status %x\n",
2751          debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), status );
2752     NtTerminateProcess( GetCurrentProcess(), status );
2753 }
2754
2755
2756 /***********************************************************************
2757  *           RtlImageDirectoryEntryToData   (NTDLL.@)
2758  */
2759 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
2760 {
2761     const IMAGE_NT_HEADERS *nt;
2762     DWORD addr;
2763
2764     if ((ULONG_PTR)module & 1)  /* mapped as data file */
2765     {
2766         module = (HMODULE)((ULONG_PTR)module & ~1);
2767         image = FALSE;
2768     }
2769     if (!(nt = RtlImageNtHeader( module ))) return NULL;
2770     if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
2771     {
2772         const IMAGE_NT_HEADERS64 *nt64 = (const IMAGE_NT_HEADERS64 *)nt;
2773
2774         if (dir >= nt64->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2775         if (!(addr = nt64->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2776         *size = nt64->OptionalHeader.DataDirectory[dir].Size;
2777         if (image || addr < nt64->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2778     }
2779     else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
2780     {
2781         const IMAGE_NT_HEADERS32 *nt32 = (const IMAGE_NT_HEADERS32 *)nt;
2782
2783         if (dir >= nt32->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2784         if (!(addr = nt32->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2785         *size = nt32->OptionalHeader.DataDirectory[dir].Size;
2786         if (image || addr < nt32->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2787     }
2788     else return NULL;
2789
2790     /* not mapped as image, need to find the section containing the virtual address */
2791     return RtlImageRvaToVa( nt, module, addr, NULL );
2792 }
2793
2794
2795 /***********************************************************************
2796  *           RtlImageRvaToSection   (NTDLL.@)
2797  */
2798 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
2799                                                    HMODULE module, DWORD rva )
2800 {
2801     int i;
2802     const IMAGE_SECTION_HEADER *sec;
2803
2804     sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
2805                                         nt->FileHeader.SizeOfOptionalHeader);
2806     for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
2807     {
2808         if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2809             return (PIMAGE_SECTION_HEADER)sec;
2810     }
2811     return NULL;
2812 }
2813
2814
2815 /***********************************************************************
2816  *           RtlImageRvaToVa   (NTDLL.@)
2817  */
2818 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
2819                               DWORD rva, IMAGE_SECTION_HEADER **section )
2820 {
2821     IMAGE_SECTION_HEADER *sec;
2822
2823     if (section && *section)  /* try this section first */
2824     {
2825         sec = *section;
2826         if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2827             goto found;
2828     }
2829     if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
2830  found:
2831     if (section) *section = sec;
2832     return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
2833 }
2834
2835
2836 /***********************************************************************
2837  *           RtlPcToFileHeader   (NTDLL.@)
2838  */
2839 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
2840 {
2841     LDR_MODULE *module;
2842     PVOID ret = NULL;
2843
2844     RtlEnterCriticalSection( &loader_section );
2845     if (!LdrFindEntryForAddress( pc, &module )) ret = module->BaseAddress;
2846     RtlLeaveCriticalSection( &loader_section );
2847     *address = ret;
2848     return ret;
2849 }
2850
2851
2852 /***********************************************************************
2853  *           NtLoadDriver   (NTDLL.@)
2854  *           ZwLoadDriver   (NTDLL.@)
2855  */
2856 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
2857 {
2858     FIXME("(%p), stub!\n",DriverServiceName);
2859     return STATUS_NOT_IMPLEMENTED;
2860 }
2861
2862
2863 /***********************************************************************
2864  *           NtUnloadDriver   (NTDLL.@)
2865  *           ZwUnloadDriver   (NTDLL.@)
2866  */
2867 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
2868 {
2869     FIXME("(%p), stub!\n",DriverServiceName);
2870     return STATUS_NOT_IMPLEMENTED;
2871 }
2872
2873
2874 /******************************************************************
2875  *              DllMain   (NTDLL.@)
2876  */
2877 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
2878 {
2879     if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
2880     return TRUE;
2881 }
2882
2883
2884 /******************************************************************
2885  *              __wine_init_windows_dir   (NTDLL.@)
2886  *
2887  * Windows and system dir initialization once kernel32 has been loaded.
2888  */
2889 void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
2890 {
2891     PLIST_ENTRY mark, entry;
2892     LPWSTR buffer, p;
2893
2894     strcpyW( user_shared_data->NtSystemRoot, windir );
2895     DIR_init_windows_dir( windir, sysdir );
2896
2897     /* prepend the system dir to the name of the already created modules */
2898     mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2899     for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2900     {
2901         LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
2902
2903         assert( mod->Flags & LDR_WINE_INTERNAL );
2904
2905         buffer = RtlAllocateHeap( GetProcessHeap(), 0,
2906                                   system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
2907         if (!buffer) continue;
2908         strcpyW( buffer, system_dir.Buffer );
2909         p = buffer + strlenW( buffer );
2910         if (p > buffer && p[-1] != '\\') *p++ = '\\';
2911         strcpyW( p, mod->FullDllName.Buffer );
2912         RtlInitUnicodeString( &mod->FullDllName, buffer );
2913         RtlInitUnicodeString( &mod->BaseDllName, p );
2914     }
2915 }
2916
2917
2918 /***********************************************************************
2919  *           __wine_process_init
2920  */
2921 void __wine_process_init(void)
2922 {
2923     static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
2924
2925     WINE_MODREF *wm;
2926     NTSTATUS status;
2927     ANSI_STRING func_name;
2928     void (* DECLSPEC_NORETURN CDECL init_func)(void);
2929
2930     main_exe_file = thread_init();
2931
2932     /* retrieve current umask */
2933     FILE_umask = umask(0777);
2934     umask( FILE_umask );
2935
2936     load_global_options();
2937
2938     /* setup the load callback and create ntdll modref */
2939     wine_dll_set_callback( load_builtin_callback );
2940
2941     if ((status = load_builtin_dll( NULL, kernel32W, 0, 0, &wm )) != STATUS_SUCCESS)
2942     {
2943         MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
2944         exit(1);
2945     }
2946     RtlInitAnsiString( &func_name, "UnhandledExceptionFilter" );
2947     LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name, 0, (void **)&unhandled_exception_filter );
2948
2949     RtlInitAnsiString( &func_name, "__wine_kernel_init" );
2950     if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
2951                                           0, (void **)&init_func )) != STATUS_SUCCESS)
2952     {
2953         MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status );
2954         exit(1);
2955     }
2956     init_func();
2957 }