user32: Rename GetKeyboardLayout param; it's a thread ID, not a layout.
[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_WRITECOPY ) != 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_WRITECOPY, &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->handle     = 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     NtClose( mapping );
1496     if (status < 0) return status;
1497
1498     /* create the MODREF */
1499
1500     if (!(wm = alloc_module( module, name ))) return STATUS_NO_MEMORY;
1501
1502     /* fixup imports */
1503
1504     if (!(flags & DONT_RESOLVE_DLL_REFERENCES))
1505     {
1506         if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1507         {
1508             /* the module has only be inserted in the load & memory order lists */
1509             RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1510             RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1511
1512             /* FIXME: there are several more dangling references
1513              * left. Including dlls loaded by this dll before the
1514              * failed one. Unrolling is rather difficult with the
1515              * current structure and we can leave them lying
1516              * around with no problems, so we don't care.
1517              * As these might reference our wm, we don't free it.
1518              */
1519             return status;
1520         }
1521     }
1522
1523     /* send DLL load event */
1524
1525     nt = RtlImageNtHeader( module );
1526
1527     SERVER_START_REQ( load_dll )
1528     {
1529         req->handle     = wine_server_obj_handle( file );
1530         req->base       = wine_server_client_ptr( module );
1531         req->size       = nt->OptionalHeader.SizeOfImage;
1532         req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1533         req->dbg_size   = nt->FileHeader.NumberOfSymbols;
1534         req->name       = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1535         wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1536         wine_server_call( req );
1537     }
1538     SERVER_END_REQ;
1539
1540     if ((wm->ldr.Flags & LDR_IMAGE_IS_DLL) && TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1541
1542     TRACE_(loaddll)( "Loaded %s at %p: native\n", debugstr_w(wm->ldr.FullDllName.Buffer), module );
1543
1544     wm->ldr.LoadCount = 1;
1545     *pwm = wm;
1546     return STATUS_SUCCESS;
1547 }
1548
1549
1550 /***********************************************************************
1551  *           load_builtin_dll
1552  */
1553 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, HANDLE file,
1554                                   DWORD flags, WINE_MODREF** pwm )
1555 {
1556     char error[256], dllname[MAX_PATH];
1557     const WCHAR *name, *p;
1558     DWORD len, i;
1559     void *handle = NULL;
1560     struct builtin_load_info info, *prev_info;
1561
1562     /* Fix the name in case we have a full path and extension */
1563     name = path;
1564     if ((p = strrchrW( name, '\\' ))) name = p + 1;
1565     if ((p = strrchrW( name, '/' ))) name = p + 1;
1566
1567     /* load_library will modify info.status. Note also that load_library can be
1568      * called several times, if the .so file we're loading has dependencies.
1569      * info.status will gather all the errors we may get while loading all these
1570      * libraries
1571      */
1572     info.load_path = load_path;
1573     info.filename  = NULL;
1574     info.status    = STATUS_SUCCESS;
1575     info.wm        = NULL;
1576
1577     if (file)  /* we have a real file, try to load it */
1578     {
1579         UNICODE_STRING nt_name;
1580         ANSI_STRING unix_name;
1581
1582         TRACE("Trying built-in %s\n", debugstr_w(path));
1583
1584         if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1585             return STATUS_DLL_NOT_FOUND;
1586
1587         if (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ))
1588         {
1589             RtlFreeUnicodeString( &nt_name );
1590             return STATUS_DLL_NOT_FOUND;
1591         }
1592         prev_info = builtin_load_info;
1593         info.filename = nt_name.Buffer + 4;  /* skip \??\ */
1594         builtin_load_info = &info;
1595         handle = wine_dlopen( unix_name.Buffer, RTLD_NOW, error, sizeof(error) );
1596         builtin_load_info = prev_info;
1597         RtlFreeUnicodeString( &nt_name );
1598         RtlFreeHeap( GetProcessHeap(), 0, unix_name.Buffer );
1599         if (!handle)
1600         {
1601             WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path), error );
1602             return STATUS_INVALID_IMAGE_FORMAT;
1603         }
1604     }
1605     else
1606     {
1607         int file_exists;
1608
1609         TRACE("Trying built-in %s\n", debugstr_w(name));
1610
1611         /* we don't want to depend on the current codepage here */
1612         len = strlenW( name ) + 1;
1613         if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1614         for (i = 0; i < len; i++)
1615         {
1616             if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1617             dllname[i] = (char)name[i];
1618             if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1619         }
1620
1621         prev_info = builtin_load_info;
1622         builtin_load_info = &info;
1623         handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1624         builtin_load_info = prev_info;
1625         if (!handle)
1626         {
1627             if (!file_exists)
1628             {
1629                 /* The file does not exist -> WARN() */
1630                 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
1631                 return STATUS_DLL_NOT_FOUND;
1632             }
1633             /* ERR() for all other errors (missing functions, ...) */
1634             ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
1635             return STATUS_PROCEDURE_NOT_FOUND;
1636         }
1637     }
1638
1639     if (info.status != STATUS_SUCCESS)
1640     {
1641         wine_dll_unload( handle );
1642         return info.status;
1643     }
1644
1645     if (!info.wm)
1646     {
1647         PLIST_ENTRY mark, entry;
1648
1649         /* The constructor wasn't called, this means the .so is already
1650          * loaded under a different name. Try to find the wm for it. */
1651
1652         mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1653         for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1654         {
1655             LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1656             if (mod->Flags & LDR_WINE_INTERNAL && mod->SectionHandle == handle)
1657             {
1658                 info.wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1659                 TRACE( "Found %s at %p for builtin %s\n",
1660                        debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress, debugstr_w(path) );
1661                 break;
1662             }
1663         }
1664         wine_dll_unload( handle );  /* release the libdl refcount */
1665         if (!info.wm) return STATUS_INVALID_IMAGE_FORMAT;
1666         if (info.wm->ldr.LoadCount != -1) info.wm->ldr.LoadCount++;
1667     }
1668     else
1669     {
1670         TRACE_(loaddll)( "Loaded %s at %p: builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress );
1671         info.wm->ldr.LoadCount = 1;
1672         info.wm->ldr.SectionHandle = handle;
1673     }
1674
1675     *pwm = info.wm;
1676     return STATUS_SUCCESS;
1677 }
1678
1679
1680 /***********************************************************************
1681  *      find_actctx_dll
1682  *
1683  * Find the full path (if any) of the dll from the activation context.
1684  */
1685 static NTSTATUS find_actctx_dll( LPCWSTR libname, LPWSTR *fullname )
1686 {
1687     static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
1688     static const WCHAR dotManifestW[] = {'.','m','a','n','i','f','e','s','t',0};
1689
1690     ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
1691     ACTCTX_SECTION_KEYED_DATA data;
1692     UNICODE_STRING nameW;
1693     NTSTATUS status;
1694     SIZE_T needed, size = 1024;
1695     WCHAR *p;
1696
1697     RtlInitUnicodeString( &nameW, libname );
1698     data.cbSize = sizeof(data);
1699     status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
1700                                                     ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
1701                                                     &nameW, &data );
1702     if (status != STATUS_SUCCESS) return status;
1703
1704     for (;;)
1705     {
1706         if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1707         {
1708             status = STATUS_NO_MEMORY;
1709             goto done;
1710         }
1711         status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
1712                                                        AssemblyDetailedInformationInActivationContext,
1713                                                        info, size, &needed );
1714         if (status == STATUS_SUCCESS) break;
1715         if (status != STATUS_BUFFER_TOO_SMALL) goto done;
1716         RtlFreeHeap( GetProcessHeap(), 0, info );
1717         size = needed;
1718         /* restart with larger buffer */
1719     }
1720
1721     if (!info->lpAssemblyManifestPath || !info->lpAssemblyDirectoryName)
1722     {
1723         status = STATUS_SXS_KEY_NOT_FOUND;
1724         goto done;
1725     }
1726
1727     if ((p = strrchrW( info->lpAssemblyManifestPath, '\\' )))
1728     {
1729         DWORD dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1730
1731         p++;
1732         if (strncmpiW( p, info->lpAssemblyDirectoryName, dirlen ) || strcmpiW( p + dirlen, dotManifestW ))
1733         {
1734             /* manifest name does not match directory name, so it's not a global
1735              * windows/winsxs manifest; use the manifest directory name instead */
1736             dirlen = p - info->lpAssemblyManifestPath;
1737             needed = (dirlen + 1) * sizeof(WCHAR) + nameW.Length;
1738             if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1739             {
1740                 status = STATUS_NO_MEMORY;
1741                 goto done;
1742             }
1743             memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
1744             p += dirlen;
1745             strcpyW( p, libname );
1746             goto done;
1747         }
1748     }
1749
1750     needed = (windows_dir.Length + sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength +
1751               nameW.Length + 2*sizeof(WCHAR));
1752
1753     if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1754     {
1755         status = STATUS_NO_MEMORY;
1756         goto done;
1757     }
1758     memcpy( p, windows_dir.Buffer, windows_dir.Length );
1759     p += windows_dir.Length / sizeof(WCHAR);
1760     memcpy( p, winsxsW, sizeof(winsxsW) );
1761     p += sizeof(winsxsW) / sizeof(WCHAR);
1762     memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
1763     p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1764     *p++ = '\\';
1765     strcpyW( p, libname );
1766 done:
1767     RtlFreeHeap( GetProcessHeap(), 0, info );
1768     RtlReleaseActivationContext( data.hActCtx );
1769     return status;
1770 }
1771
1772
1773 /***********************************************************************
1774  *      find_dll_file
1775  *
1776  * Find the file (or already loaded module) for a given dll name.
1777  */
1778 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
1779                                WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
1780 {
1781     OBJECT_ATTRIBUTES attr;
1782     IO_STATUS_BLOCK io;
1783     UNICODE_STRING nt_name;
1784     WCHAR *file_part, *ext, *dllname;
1785     ULONG len;
1786
1787     /* first append .dll if needed */
1788
1789     dllname = NULL;
1790     if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
1791     {
1792         if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
1793                                          (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
1794             return STATUS_NO_MEMORY;
1795         strcpyW( dllname, libname );
1796         strcatW( dllname, dllW );
1797         libname = dllname;
1798     }
1799
1800     nt_name.Buffer = NULL;
1801
1802     if (!contains_path( libname ))
1803     {
1804         NTSTATUS status;
1805         WCHAR *fullname = NULL;
1806
1807         if ((*pwm = find_basename_module( libname )) != NULL) goto found;
1808
1809         status = find_actctx_dll( libname, &fullname );
1810         if (status == STATUS_SUCCESS)
1811         {
1812             TRACE ("found %s for %s\n", debugstr_w(fullname), debugstr_w(libname) );
1813             RtlFreeHeap( GetProcessHeap(), 0, dllname );
1814             libname = dllname = fullname;
1815         }
1816         else if (status != STATUS_SXS_KEY_NOT_FOUND)
1817         {
1818             RtlFreeHeap( GetProcessHeap(), 0, dllname );
1819             return status;
1820         }
1821     }
1822
1823     if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
1824     {
1825         /* we need to search for it */
1826         len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
1827         if (len)
1828         {
1829             if (len >= *size) goto overflow;
1830             if ((*pwm = find_fullname_module( filename )) || !handle) goto found;
1831
1832             if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
1833             {
1834                 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1835                 return STATUS_NO_MEMORY;
1836             }
1837             attr.Length = sizeof(attr);
1838             attr.RootDirectory = 0;
1839             attr.Attributes = OBJ_CASE_INSENSITIVE;
1840             attr.ObjectName = &nt_name;
1841             attr.SecurityDescriptor = NULL;
1842             attr.SecurityQualityOfService = NULL;
1843             if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1844             goto found;
1845         }
1846
1847         /* not found */
1848
1849         if (!contains_path( libname ))
1850         {
1851             /* if libname doesn't contain a path at all, we simply return the name as is,
1852              * to be loaded as builtin */
1853             len = strlenW(libname) * sizeof(WCHAR);
1854             if (len >= *size) goto overflow;
1855             strcpyW( filename, libname );
1856             goto found;
1857         }
1858     }
1859
1860     /* absolute path name, or relative path name but not found above */
1861
1862     if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
1863     {
1864         RtlFreeHeap( GetProcessHeap(), 0, dllname );
1865         return STATUS_NO_MEMORY;
1866     }
1867     len = nt_name.Length - 4*sizeof(WCHAR);  /* for \??\ prefix */
1868     if (len >= *size) goto overflow;
1869     memcpy( filename, nt_name.Buffer + 4, len + sizeof(WCHAR) );
1870     if (!(*pwm = find_fullname_module( filename )) && handle)
1871     {
1872         attr.Length = sizeof(attr);
1873         attr.RootDirectory = 0;
1874         attr.Attributes = OBJ_CASE_INSENSITIVE;
1875         attr.ObjectName = &nt_name;
1876         attr.SecurityDescriptor = NULL;
1877         attr.SecurityQualityOfService = NULL;
1878         if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1879     }
1880 found:
1881     RtlFreeUnicodeString( &nt_name );
1882     RtlFreeHeap( GetProcessHeap(), 0, dllname );
1883     return STATUS_SUCCESS;
1884
1885 overflow:
1886     RtlFreeUnicodeString( &nt_name );
1887     RtlFreeHeap( GetProcessHeap(), 0, dllname );
1888     *size = len + sizeof(WCHAR);
1889     return STATUS_BUFFER_TOO_SMALL;
1890 }
1891
1892
1893 /***********************************************************************
1894  *      load_dll  (internal)
1895  *
1896  * Load a PE style module according to the load order.
1897  * The loader_section must be locked while calling this function.
1898  */
1899 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
1900 {
1901     enum loadorder loadorder;
1902     WCHAR buffer[32];
1903     WCHAR *filename;
1904     ULONG size;
1905     WINE_MODREF *main_exe;
1906     HANDLE handle = 0;
1907     NTSTATUS nts;
1908
1909     TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
1910
1911     *pwm = NULL;
1912     filename = buffer;
1913     size = sizeof(buffer);
1914     for (;;)
1915     {
1916         nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
1917         if (nts == STATUS_SUCCESS) break;
1918         if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1919         if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
1920         /* grow the buffer and retry */
1921         if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
1922     }
1923
1924     if (*pwm)  /* found already loaded module */
1925     {
1926         if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
1927
1928         if (!(flags & DONT_RESOLVE_DLL_REFERENCES)) fixup_imports( *pwm, load_path );
1929
1930         TRACE("Found %s for %s at %p, count=%d\n",
1931               debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
1932               (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
1933         if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1934         return STATUS_SUCCESS;
1935     }
1936
1937     main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
1938     loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
1939
1940     if (handle && is_fake_dll( handle ))
1941     {
1942         TRACE( "%s is a fake Wine dll\n", debugstr_w(filename) );
1943         NtClose( handle );
1944         handle = 0;
1945     }
1946
1947     switch(loadorder)
1948     {
1949     case LO_INVALID:
1950         nts = STATUS_NO_MEMORY;
1951         break;
1952     case LO_DISABLED:
1953         nts = STATUS_DLL_NOT_FOUND;
1954         break;
1955     case LO_NATIVE:
1956     case LO_NATIVE_BUILTIN:
1957         if (!handle) nts = STATUS_DLL_NOT_FOUND;
1958         else
1959         {
1960             nts = load_native_dll( load_path, filename, handle, flags, pwm );
1961             if (nts == STATUS_INVALID_FILE_FOR_SECTION)
1962                 /* not in PE format, maybe it's a builtin */
1963                 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1964         }
1965         if (nts == STATUS_DLL_NOT_FOUND && loadorder == LO_NATIVE_BUILTIN)
1966             nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1967         break;
1968     case LO_BUILTIN:
1969     case LO_BUILTIN_NATIVE:
1970     case LO_DEFAULT:  /* default is builtin,native */
1971         nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1972         if (!handle) break;  /* nothing else we can try */
1973         /* file is not a builtin library, try without using the specified file */
1974         if (nts != STATUS_SUCCESS)
1975             nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1976         if (nts == STATUS_SUCCESS && loadorder == LO_DEFAULT &&
1977             (MODULE_InitDLL( *pwm, DLL_WINE_PREATTACH, NULL ) != STATUS_SUCCESS))
1978         {
1979             /* stub-only dll, try native */
1980             TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename) );
1981             LdrUnloadDll( (*pwm)->ldr.BaseAddress );
1982             nts = STATUS_DLL_NOT_FOUND;
1983         }
1984         if (nts == STATUS_DLL_NOT_FOUND && loadorder != LO_BUILTIN)
1985             nts = load_native_dll( load_path, filename, handle, flags, pwm );
1986         break;
1987     }
1988
1989     if (nts == STATUS_SUCCESS)
1990     {
1991         /* Initialize DLL just loaded */
1992         TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename),
1993               ((*pwm)->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native",
1994               (*pwm)->ldr.BaseAddress);
1995         if (handle) NtClose( handle );
1996         if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1997         return nts;
1998     }
1999
2000     WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
2001     if (handle) NtClose( handle );
2002     if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2003     return nts;
2004 }
2005
2006 /******************************************************************
2007  *              LdrLoadDll (NTDLL.@)
2008  */
2009 NTSTATUS WINAPI LdrLoadDll(LPCWSTR path_name, DWORD flags,
2010                            const UNICODE_STRING *libname, HMODULE* hModule)
2011 {
2012     WINE_MODREF *wm;
2013     NTSTATUS nts;
2014
2015     RtlEnterCriticalSection( &loader_section );
2016
2017     if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2018     nts = load_dll( path_name, libname->Buffer, flags, &wm );
2019
2020     if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
2021     {
2022         nts = process_attach( wm, NULL );
2023         if (nts != STATUS_SUCCESS)
2024         {
2025             LdrUnloadDll(wm->ldr.BaseAddress);
2026             wm = NULL;
2027         }
2028     }
2029     *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
2030
2031     RtlLeaveCriticalSection( &loader_section );
2032     return nts;
2033 }
2034
2035
2036 /******************************************************************
2037  *              LdrGetDllHandle (NTDLL.@)
2038  */
2039 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
2040 {
2041     NTSTATUS status;
2042     WCHAR buffer[128];
2043     WCHAR *filename;
2044     ULONG size;
2045     WINE_MODREF *wm;
2046
2047     RtlEnterCriticalSection( &loader_section );
2048
2049     if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2050
2051     filename = buffer;
2052     size = sizeof(buffer);
2053     for (;;)
2054     {
2055         status = find_dll_file( load_path, name->Buffer, filename, &size, &wm, NULL );
2056         if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2057         if (status != STATUS_BUFFER_TOO_SMALL) break;
2058         /* grow the buffer and retry */
2059         if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2060         {
2061             status = STATUS_NO_MEMORY;
2062             break;
2063         }
2064     }
2065
2066     if (status == STATUS_SUCCESS)
2067     {
2068         if (wm) *base = wm->ldr.BaseAddress;
2069         else status = STATUS_DLL_NOT_FOUND;
2070     }
2071
2072     RtlLeaveCriticalSection( &loader_section );
2073     TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
2074     return status;
2075 }
2076
2077
2078 /******************************************************************
2079  *              LdrAddRefDll (NTDLL.@)
2080  */
2081 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
2082 {
2083     NTSTATUS ret = STATUS_SUCCESS;
2084     WINE_MODREF *wm;
2085
2086     if (flags) FIXME( "%p flags %x not implemented\n", module, flags );
2087
2088     RtlEnterCriticalSection( &loader_section );
2089
2090     if ((wm = get_modref( module )))
2091     {
2092         if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
2093         TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2094     }
2095     else ret = STATUS_INVALID_PARAMETER;
2096
2097     RtlLeaveCriticalSection( &loader_section );
2098     return ret;
2099 }
2100
2101
2102 /***********************************************************************
2103  *           LdrProcessRelocationBlock  (NTDLL.@)
2104  *
2105  * Apply relocations to a given page of a mapped PE image.
2106  */
2107 IMAGE_BASE_RELOCATION * WINAPI LdrProcessRelocationBlock( void *page, UINT count,
2108                                                           USHORT *relocs, INT_PTR delta )
2109 {
2110     while (count--)
2111     {
2112         USHORT offset = *relocs & 0xfff;
2113         int type = *relocs >> 12;
2114         switch(type)
2115         {
2116         case IMAGE_REL_BASED_ABSOLUTE:
2117             break;
2118         case IMAGE_REL_BASED_HIGH:
2119             *(short *)((char *)page + offset) += HIWORD(delta);
2120             break;
2121         case IMAGE_REL_BASED_LOW:
2122             *(short *)((char *)page + offset) += LOWORD(delta);
2123             break;
2124         case IMAGE_REL_BASED_HIGHLOW:
2125             *(int *)((char *)page + offset) += delta;
2126             break;
2127 #ifdef __x86_64__
2128         case IMAGE_REL_BASED_DIR64:
2129             *(INT_PTR *)((char *)page + offset) += delta;
2130             break;
2131 #endif
2132         default:
2133             FIXME("Unknown/unsupported fixup type %x.\n", type);
2134             return NULL;
2135         }
2136         relocs++;
2137     }
2138     return (IMAGE_BASE_RELOCATION *)relocs;  /* return address of next block */
2139 }
2140
2141
2142 /******************************************************************
2143  *              LdrQueryProcessModuleInformation
2144  *
2145  */
2146 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi, 
2147                                                  ULONG buf_size, ULONG* req_size)
2148 {
2149     SYSTEM_MODULE*      sm = &smi->Modules[0];
2150     ULONG               size = sizeof(ULONG);
2151     NTSTATUS            nts = STATUS_SUCCESS;
2152     ANSI_STRING         str;
2153     char*               ptr;
2154     PLIST_ENTRY         mark, entry;
2155     PLDR_MODULE         mod;
2156     WORD id = 0;
2157
2158     smi->ModulesCount = 0;
2159
2160     RtlEnterCriticalSection( &loader_section );
2161     mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2162     for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2163     {
2164         mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2165         size += sizeof(*sm);
2166         if (size <= buf_size)
2167         {
2168             sm->Reserved1 = 0; /* FIXME */
2169             sm->Reserved2 = 0; /* FIXME */
2170             sm->ImageBaseAddress = mod->BaseAddress;
2171             sm->ImageSize = mod->SizeOfImage;
2172             sm->Flags = mod->Flags;
2173             sm->Id = id++;
2174             sm->Rank = 0; /* FIXME */
2175             sm->Unknown = 0; /* FIXME */
2176             str.Length = 0;
2177             str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
2178             str.Buffer = (char*)sm->Name;
2179             RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
2180             ptr = strrchr(str.Buffer, '\\');
2181             sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
2182
2183             smi->ModulesCount++;
2184             sm++;
2185         }
2186         else nts = STATUS_INFO_LENGTH_MISMATCH;
2187     }
2188     RtlLeaveCriticalSection( &loader_section );
2189
2190     if (req_size) *req_size = size;
2191
2192     return nts;
2193 }
2194
2195
2196 static NTSTATUS query_dword_option( HANDLE hkey, LPCWSTR name, ULONG *value )
2197 {
2198     NTSTATUS status;
2199     UNICODE_STRING str;
2200     ULONG size;
2201     WCHAR buffer[64];
2202     KEY_VALUE_PARTIAL_INFORMATION *info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
2203
2204     RtlInitUnicodeString( &str, name );
2205
2206     size = sizeof(buffer) - sizeof(WCHAR);
2207     if ((status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size )))
2208         return status;
2209
2210     if (info->Type != REG_DWORD)
2211     {
2212         buffer[size / sizeof(WCHAR)] = 0;
2213         *value = strtoulW( (WCHAR *)info->Data, 0, 16 );
2214     }
2215     else memcpy( value, info->Data, sizeof(*value) );
2216     return status;
2217 }
2218
2219 static NTSTATUS query_string_option( HANDLE hkey, LPCWSTR name, ULONG type,
2220                                      void *data, ULONG in_size, ULONG *out_size )
2221 {
2222     NTSTATUS status;
2223     UNICODE_STRING str;
2224     ULONG size;
2225     char *buffer;
2226     KEY_VALUE_PARTIAL_INFORMATION *info;
2227     static const int info_size = FIELD_OFFSET( KEY_VALUE_PARTIAL_INFORMATION, Data );
2228
2229     RtlInitUnicodeString( &str, name );
2230
2231     size = info_size + in_size;
2232     if (!(buffer = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
2233     info = (KEY_VALUE_PARTIAL_INFORMATION *)buffer;
2234     status = NtQueryValueKey( hkey, &str, KeyValuePartialInformation, buffer, size, &size );
2235     if (!status || status == STATUS_BUFFER_OVERFLOW)
2236     {
2237         if (out_size) *out_size = info->DataLength;
2238         if (data && !status) memcpy( data, info->Data, info->DataLength );
2239     }
2240     RtlFreeHeap( GetProcessHeap(), 0, buffer );
2241     return status;
2242 }
2243
2244
2245 /******************************************************************
2246  *              LdrQueryImageFileExecutionOptions  (NTDLL.@)
2247  */
2248 NTSTATUS WINAPI LdrQueryImageFileExecutionOptions( const UNICODE_STRING *key, LPCWSTR value, ULONG type,
2249                                                    void *data, ULONG in_size, ULONG *out_size )
2250 {
2251     static const WCHAR optionsW[] = {'M','a','c','h','i','n','e','\\',
2252                                      'S','o','f','t','w','a','r','e','\\',
2253                                      'M','i','c','r','o','s','o','f','t','\\',
2254                                      'W','i','n','d','o','w','s',' ','N','T','\\',
2255                                      'C','u','r','r','e','n','t','V','e','r','s','i','o','n','\\',
2256                                      'I','m','a','g','e',' ','F','i','l','e',' ',
2257                                      'E','x','e','c','u','t','i','o','n',' ','O','p','t','i','o','n','s','\\'};
2258     WCHAR path[MAX_PATH + sizeof(optionsW)/sizeof(WCHAR)];
2259     OBJECT_ATTRIBUTES attr;
2260     UNICODE_STRING name_str;
2261     HANDLE hkey;
2262     NTSTATUS status;
2263     ULONG len;
2264     WCHAR *p;
2265
2266     attr.Length = sizeof(attr);
2267     attr.RootDirectory = 0;
2268     attr.ObjectName = &name_str;
2269     attr.Attributes = OBJ_CASE_INSENSITIVE;
2270     attr.SecurityDescriptor = NULL;
2271     attr.SecurityQualityOfService = NULL;
2272
2273     if ((p = memrchrW( key->Buffer, '\\', key->Length / sizeof(WCHAR) ))) p++;
2274     else p = key->Buffer;
2275     len = key->Length - (p - key->Buffer) * sizeof(WCHAR);
2276     name_str.Buffer = path;
2277     name_str.Length = sizeof(optionsW) + len;
2278     name_str.MaximumLength = name_str.Length;
2279     memcpy( path, optionsW, sizeof(optionsW) );
2280     memcpy( path + sizeof(optionsW)/sizeof(WCHAR), p, len );
2281     if ((status = NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr ))) return status;
2282
2283     if (type == REG_DWORD)
2284     {
2285         if (out_size) *out_size = sizeof(ULONG);
2286         if (in_size >= sizeof(ULONG)) status = query_dword_option( hkey, value, data );
2287         else status = STATUS_BUFFER_OVERFLOW;
2288     }
2289     else status = query_string_option( hkey, value, type, data, in_size, out_size );
2290
2291     NtClose( hkey );
2292     return status;
2293 }
2294
2295
2296 /******************************************************************
2297  *              RtlDllShutdownInProgress  (NTDLL.@)
2298  */
2299 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
2300 {
2301     return process_detaching;
2302 }
2303
2304
2305 /******************************************************************
2306  *              LdrShutdownProcess (NTDLL.@)
2307  *
2308  */
2309 void WINAPI LdrShutdownProcess(void)
2310 {
2311     TRACE("()\n");
2312     process_detach( TRUE, (LPVOID)1 );
2313 }
2314
2315 /******************************************************************
2316  *              LdrShutdownThread (NTDLL.@)
2317  *
2318  */
2319 void WINAPI LdrShutdownThread(void)
2320 {
2321     PLIST_ENTRY mark, entry;
2322     PLDR_MODULE mod;
2323
2324     TRACE("()\n");
2325
2326     /* don't do any detach calls if process is exiting */
2327     if (process_detaching) return;
2328     /* FIXME: there is still a race here */
2329
2330     RtlEnterCriticalSection( &loader_section );
2331
2332     mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2333     for (entry = mark->Blink; entry != mark; entry = entry->Blink)
2334     {
2335         mod = CONTAINING_RECORD(entry, LDR_MODULE, 
2336                                 InInitializationOrderModuleList);
2337         if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
2338             continue;
2339         if ( mod->Flags & LDR_NO_DLL_CALLS )
2340             continue;
2341
2342         MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr), 
2343                         DLL_THREAD_DETACH, NULL );
2344     }
2345
2346     RtlLeaveCriticalSection( &loader_section );
2347     RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->ThreadLocalStoragePointer );
2348 }
2349
2350
2351 /***********************************************************************
2352  *           free_modref
2353  *
2354  */
2355 static void free_modref( WINE_MODREF *wm )
2356 {
2357     RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
2358     RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
2359     if (wm->ldr.InInitializationOrderModuleList.Flink)
2360         RemoveEntryList(&wm->ldr.InInitializationOrderModuleList);
2361
2362     TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
2363     if (!TRACE_ON(module))
2364         TRACE_(loaddll)("Unloaded module %s : %s\n",
2365                         debugstr_w(wm->ldr.FullDllName.Buffer),
2366                         (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
2367
2368     SERVER_START_REQ( unload_dll )
2369     {
2370         req->base = wine_server_client_ptr( wm->ldr.BaseAddress );
2371         wine_server_call( req );
2372     }
2373     SERVER_END_REQ;
2374
2375     RtlReleaseActivationContext( wm->ldr.ActivationContext );
2376     NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.BaseAddress );
2377     if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
2378     if (cached_modref == wm) cached_modref = NULL;
2379     RtlFreeUnicodeString( &wm->ldr.FullDllName );
2380     RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
2381     RtlFreeHeap( GetProcessHeap(), 0, wm );
2382 }
2383
2384 /***********************************************************************
2385  *           MODULE_FlushModrefs
2386  *
2387  * Remove all unused modrefs and call the internal unloading routines
2388  * for the library type.
2389  *
2390  * The loader_section must be locked while calling this function.
2391  */
2392 static void MODULE_FlushModrefs(void)
2393 {
2394     PLIST_ENTRY mark, entry, prev;
2395     PLDR_MODULE mod;
2396     WINE_MODREF*wm;
2397
2398     mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2399     for (entry = mark->Blink; entry != mark; entry = prev)
2400     {
2401         mod = CONTAINING_RECORD(entry, LDR_MODULE, InInitializationOrderModuleList);
2402         wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2403         prev = entry->Blink;
2404         if (!mod->LoadCount) free_modref( wm );
2405     }
2406
2407     /* check load order list too for modules that haven't been initialized yet */
2408     mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2409     for (entry = mark->Blink; entry != mark; entry = prev)
2410     {
2411         mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2412         wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2413         prev = entry->Blink;
2414         if (!mod->LoadCount) free_modref( wm );
2415     }
2416 }
2417
2418 /***********************************************************************
2419  *           MODULE_DecRefCount
2420  *
2421  * The loader_section must be locked while calling this function.
2422  */
2423 static void MODULE_DecRefCount( WINE_MODREF *wm )
2424 {
2425     int i;
2426
2427     if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
2428         return;
2429
2430     if ( wm->ldr.LoadCount <= 0 )
2431         return;
2432
2433     --wm->ldr.LoadCount;
2434     TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2435
2436     if ( wm->ldr.LoadCount == 0 )
2437     {
2438         wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
2439
2440         for ( i = 0; i < wm->nDeps; i++ )
2441             if ( wm->deps[i] )
2442                 MODULE_DecRefCount( wm->deps[i] );
2443
2444         wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
2445     }
2446 }
2447
2448 /******************************************************************
2449  *              LdrUnloadDll (NTDLL.@)
2450  *
2451  *
2452  */
2453 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
2454 {
2455     NTSTATUS retv = STATUS_SUCCESS;
2456
2457     TRACE("(%p)\n", hModule);
2458
2459     RtlEnterCriticalSection( &loader_section );
2460
2461     /* if we're stopping the whole process (and forcing the removal of all
2462      * DLLs) the library will be freed anyway
2463      */
2464     if (!process_detaching)
2465     {
2466         WINE_MODREF *wm;
2467
2468         free_lib_count++;
2469         if ((wm = get_modref( hModule )) != NULL)
2470         {
2471             TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
2472
2473             /* Recursively decrement reference counts */
2474             MODULE_DecRefCount( wm );
2475
2476             /* Call process detach notifications */
2477             if ( free_lib_count <= 1 )
2478             {
2479                 process_detach( FALSE, NULL );
2480                 MODULE_FlushModrefs();
2481             }
2482
2483             TRACE("END\n");
2484         }
2485         else
2486             retv = STATUS_DLL_NOT_FOUND;
2487
2488         free_lib_count--;
2489     }
2490
2491     RtlLeaveCriticalSection( &loader_section );
2492
2493     return retv;
2494 }
2495
2496 /***********************************************************************
2497  *           RtlImageNtHeader   (NTDLL.@)
2498  */
2499 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
2500 {
2501     IMAGE_NT_HEADERS *ret;
2502
2503     __TRY
2504     {
2505         IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
2506
2507         ret = NULL;
2508         if (dos->e_magic == IMAGE_DOS_SIGNATURE)
2509         {
2510             ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
2511             if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
2512         }
2513     }
2514     __EXCEPT_PAGE_FAULT
2515     {
2516         return NULL;
2517     }
2518     __ENDTRY
2519     return ret;
2520 }
2521
2522
2523 /***********************************************************************
2524  *           attach_process_dlls
2525  *
2526  * Initial attach to all the dlls loaded by the process.
2527  */
2528 static NTSTATUS attach_process_dlls( void *wm )
2529 {
2530     NTSTATUS status;
2531
2532     pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
2533
2534     RtlEnterCriticalSection( &loader_section );
2535     if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS)
2536     {
2537         if (last_failed_modref)
2538             ERR( "%s failed to initialize, aborting\n",
2539                  debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
2540         return status;
2541     }
2542     attach_implicitly_loaded_dlls( (LPVOID)1 );
2543     RtlLeaveCriticalSection( &loader_section );
2544     return status;
2545 }
2546
2547
2548 /***********************************************************************
2549  *           load_global_options
2550  */
2551 static void load_global_options(void)
2552 {
2553     static const WCHAR sessionW[] = {'M','a','c','h','i','n','e','\\',
2554                                      'S','y','s','t','e','m','\\',
2555                                      'C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\',
2556                                      'C','o','n','t','r','o','l','\\',
2557                                      'S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r',0};
2558     static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
2559     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};
2560     static const WCHAR heapresW[] = {'H','e','a','p','S','e','g','m','e','n','t','R','e','s','e','r','v','e',0};
2561     static const WCHAR heapcommitW[] = {'H','e','a','p','S','e','g','m','e','n','t','C','o','m','m','i','t',0};
2562     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};
2563     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};
2564
2565     OBJECT_ATTRIBUTES attr;
2566     UNICODE_STRING name_str;
2567     HANDLE hkey;
2568     ULONG value;
2569
2570     attr.Length = sizeof(attr);
2571     attr.RootDirectory = 0;
2572     attr.ObjectName = &name_str;
2573     attr.Attributes = OBJ_CASE_INSENSITIVE;
2574     attr.SecurityDescriptor = NULL;
2575     attr.SecurityQualityOfService = NULL;
2576     RtlInitUnicodeString( &name_str, sessionW );
2577
2578     if (NtOpenKey( &hkey, KEY_QUERY_VALUE, &attr )) return;
2579
2580     query_dword_option( hkey, globalflagW, &NtCurrentTeb()->Peb->NtGlobalFlag );
2581
2582     query_dword_option( hkey, critsectW, &value );
2583     NtCurrentTeb()->Peb->CriticalSectionTimeout.QuadPart = (ULONGLONG)value * -10000000;
2584
2585     query_dword_option( hkey, heapresW, &value );
2586     NtCurrentTeb()->Peb->HeapSegmentReserve = value;
2587
2588     query_dword_option( hkey, heapcommitW, &value );
2589     NtCurrentTeb()->Peb->HeapSegmentCommit = value;
2590
2591     query_dword_option( hkey, decommittotalW, &value );
2592     NtCurrentTeb()->Peb->HeapDeCommitTotalFreeThreshold = value;
2593
2594     query_dword_option( hkey, decommitfreeW, &value );
2595     NtCurrentTeb()->Peb->HeapDeCommitFreeBlockThreshold = value;
2596
2597     NtClose( hkey );
2598 }
2599
2600
2601 /***********************************************************************
2602  *           start_process
2603  */
2604 static void start_process( void *kernel_start )
2605 {
2606     call_thread_entry_point( kernel_start, NtCurrentTeb()->Peb );
2607 }
2608
2609 /******************************************************************
2610  *              LdrInitializeThunk (NTDLL.@)
2611  *
2612  */
2613 void WINAPI LdrInitializeThunk( void *kernel_start, ULONG_PTR unknown2,
2614                                 ULONG_PTR unknown3, ULONG_PTR unknown4 )
2615 {
2616     static const WCHAR globalflagW[] = {'G','l','o','b','a','l','F','l','a','g',0};
2617     NTSTATUS status;
2618     WINE_MODREF *wm;
2619     LPCWSTR load_path;
2620     PEB *peb = NtCurrentTeb()->Peb;
2621     IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
2622
2623     if (main_exe_file) NtClose( main_exe_file );  /* at this point the main module is created */
2624
2625     /* allocate the modref for the main exe (if not already done) */
2626     wm = get_modref( peb->ImageBaseAddress );
2627     assert( wm );
2628     if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
2629     {
2630         ERR("%s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
2631         exit(1);
2632     }
2633
2634     peb->LoaderLock = &loader_section;
2635     peb->ProcessParameters->ImagePathName = wm->ldr.FullDllName;
2636     if (!peb->ProcessParameters->WindowTitle.Buffer)
2637         peb->ProcessParameters->WindowTitle = wm->ldr.FullDllName;
2638     version_init( wm->ldr.FullDllName.Buffer );
2639
2640     LdrQueryImageFileExecutionOptions( &peb->ProcessParameters->ImagePathName, globalflagW,
2641                                        REG_DWORD, &peb->NtGlobalFlag, sizeof(peb->NtGlobalFlag), NULL );
2642
2643     /* the main exe needs to be the first in the load order list */
2644     RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
2645     InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
2646
2647     if ((status = virtual_alloc_thread_stack( NtCurrentTeb(), 0, 0 )) != STATUS_SUCCESS) goto error;
2648     if ((status = server_init_process_done()) != STATUS_SUCCESS) goto error;
2649
2650     actctx_init();
2651     load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2652     if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
2653     if ((status = alloc_process_tls()) != STATUS_SUCCESS) goto error;
2654     if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto error;
2655     heap_set_debug_flags( GetProcessHeap() );
2656
2657     status = wine_call_on_stack( attach_process_dlls, wm, NtCurrentTeb()->Tib.StackBase );
2658     if (status != STATUS_SUCCESS) goto error;
2659
2660     virtual_release_address_space( nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE );
2661     virtual_clear_thread_stack();
2662     wine_switch_to_stack( start_process, kernel_start, NtCurrentTeb()->Tib.StackBase );
2663
2664 error:
2665     ERR( "Main exe initialization for %s failed, status %x\n",
2666          debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), status );
2667     NtTerminateProcess( GetCurrentProcess(), status );
2668 }
2669
2670
2671 /***********************************************************************
2672  *           RtlImageDirectoryEntryToData   (NTDLL.@)
2673  */
2674 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
2675 {
2676     const IMAGE_NT_HEADERS *nt;
2677     DWORD addr;
2678
2679     if ((ULONG_PTR)module & 1)  /* mapped as data file */
2680     {
2681         module = (HMODULE)((ULONG_PTR)module & ~1);
2682         image = FALSE;
2683     }
2684     if (!(nt = RtlImageNtHeader( module ))) return NULL;
2685     if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
2686     {
2687         const IMAGE_NT_HEADERS64 *nt64 = (const IMAGE_NT_HEADERS64 *)nt;
2688
2689         if (dir >= nt64->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2690         if (!(addr = nt64->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2691         *size = nt64->OptionalHeader.DataDirectory[dir].Size;
2692         if (image || addr < nt64->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2693     }
2694     else if (nt->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC)
2695     {
2696         const IMAGE_NT_HEADERS32 *nt32 = (const IMAGE_NT_HEADERS32 *)nt;
2697
2698         if (dir >= nt32->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2699         if (!(addr = nt32->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2700         *size = nt32->OptionalHeader.DataDirectory[dir].Size;
2701         if (image || addr < nt32->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2702     }
2703     else return NULL;
2704
2705     /* not mapped as image, need to find the section containing the virtual address */
2706     return RtlImageRvaToVa( nt, module, addr, NULL );
2707 }
2708
2709
2710 /***********************************************************************
2711  *           RtlImageRvaToSection   (NTDLL.@)
2712  */
2713 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
2714                                                    HMODULE module, DWORD rva )
2715 {
2716     int i;
2717     const IMAGE_SECTION_HEADER *sec;
2718
2719     sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
2720                                         nt->FileHeader.SizeOfOptionalHeader);
2721     for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
2722     {
2723         if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2724             return (PIMAGE_SECTION_HEADER)sec;
2725     }
2726     return NULL;
2727 }
2728
2729
2730 /***********************************************************************
2731  *           RtlImageRvaToVa   (NTDLL.@)
2732  */
2733 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
2734                               DWORD rva, IMAGE_SECTION_HEADER **section )
2735 {
2736     IMAGE_SECTION_HEADER *sec;
2737
2738     if (section && *section)  /* try this section first */
2739     {
2740         sec = *section;
2741         if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2742             goto found;
2743     }
2744     if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
2745  found:
2746     if (section) *section = sec;
2747     return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
2748 }
2749
2750
2751 /***********************************************************************
2752  *           RtlPcToFileHeader   (NTDLL.@)
2753  */
2754 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
2755 {
2756     LDR_MODULE *module;
2757     PVOID ret = NULL;
2758
2759     RtlEnterCriticalSection( &loader_section );
2760     if (!LdrFindEntryForAddress( pc, &module )) ret = module->BaseAddress;
2761     RtlLeaveCriticalSection( &loader_section );
2762     *address = ret;
2763     return ret;
2764 }
2765
2766
2767 /***********************************************************************
2768  *           NtLoadDriver   (NTDLL.@)
2769  *           ZwLoadDriver   (NTDLL.@)
2770  */
2771 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
2772 {
2773     FIXME("(%p), stub!\n",DriverServiceName);
2774     return STATUS_NOT_IMPLEMENTED;
2775 }
2776
2777
2778 /***********************************************************************
2779  *           NtUnloadDriver   (NTDLL.@)
2780  *           ZwUnloadDriver   (NTDLL.@)
2781  */
2782 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
2783 {
2784     FIXME("(%p), stub!\n",DriverServiceName);
2785     return STATUS_NOT_IMPLEMENTED;
2786 }
2787
2788
2789 /******************************************************************
2790  *              DllMain   (NTDLL.@)
2791  */
2792 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
2793 {
2794     if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
2795     return TRUE;
2796 }
2797
2798
2799 /******************************************************************
2800  *              __wine_init_windows_dir   (NTDLL.@)
2801  *
2802  * Windows and system dir initialization once kernel32 has been loaded.
2803  */
2804 void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
2805 {
2806     PLIST_ENTRY mark, entry;
2807     LPWSTR buffer, p;
2808
2809     DIR_init_windows_dir( windir, sysdir );
2810     strcpyW( user_shared_data->NtSystemRoot, windir );
2811
2812     /* prepend the system dir to the name of the already created modules */
2813     mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2814     for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2815     {
2816         LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
2817
2818         assert( mod->Flags & LDR_WINE_INTERNAL );
2819
2820         buffer = RtlAllocateHeap( GetProcessHeap(), 0,
2821                                   system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
2822         if (!buffer) continue;
2823         strcpyW( buffer, system_dir.Buffer );
2824         p = buffer + strlenW( buffer );
2825         if (p > buffer && p[-1] != '\\') *p++ = '\\';
2826         strcpyW( p, mod->FullDllName.Buffer );
2827         RtlInitUnicodeString( &mod->FullDllName, buffer );
2828         RtlInitUnicodeString( &mod->BaseDllName, p );
2829     }
2830 }
2831
2832
2833 /***********************************************************************
2834  *           __wine_process_init
2835  */
2836 void __wine_process_init(void)
2837 {
2838     static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
2839
2840     WINE_MODREF *wm;
2841     NTSTATUS status;
2842     ANSI_STRING func_name;
2843     void (* DECLSPEC_NORETURN CDECL init_func)(void);
2844     extern mode_t FILE_umask;
2845
2846     main_exe_file = thread_init();
2847
2848     /* retrieve current umask */
2849     FILE_umask = umask(0777);
2850     umask( FILE_umask );
2851
2852     load_global_options();
2853
2854     /* setup the load callback and create ntdll modref */
2855     wine_dll_set_callback( load_builtin_callback );
2856
2857     if ((status = load_builtin_dll( NULL, kernel32W, 0, 0, &wm )) != STATUS_SUCCESS)
2858     {
2859         MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
2860         exit(1);
2861     }
2862     RtlInitAnsiString( &func_name, "UnhandledExceptionFilter" );
2863     LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name, 0, (void **)&unhandled_exception_filter );
2864
2865     RtlInitAnsiString( &func_name, "__wine_kernel_init" );
2866     if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
2867                                           0, (void **)&init_func )) != STATUS_SUCCESS)
2868     {
2869         MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status );
2870         exit(1);
2871     }
2872     init_func();
2873 }