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