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