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