jscript: Added Object.toString for host objects implementation.
[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         ULONG flags = MEM_EXECUTE_OPTION_ENABLE;
813         WARN( "disabling no-exec because of %s\n", debugstr_w(wm->ldr.BaseDllName.Buffer) );
814         NtSetInformationProcess( GetCurrentProcess(), ProcessExecuteFlags, &flags, sizeof(flags) );
815     }
816     return wm;
817 }
818
819
820 /*************************************************************************
821  *              alloc_process_tls
822  *
823  * Allocate the process-wide structure for module TLS storage.
824  */
825 static NTSTATUS alloc_process_tls(void)
826 {
827     PLIST_ENTRY mark, entry;
828     PLDR_MODULE mod;
829     const IMAGE_TLS_DIRECTORY *dir;
830     ULONG size, i;
831
832     mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
833     for (entry = mark->Flink; entry != mark; entry = entry->Flink)
834     {
835         mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
836         if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
837                                                   IMAGE_DIRECTORY_ENTRY_TLS, &size )))
838             continue;
839         size = (dir->EndAddressOfRawData - dir->StartAddressOfRawData) + dir->SizeOfZeroFill;
840         if (!size) continue;
841         tls_total_size += size;
842         tls_module_count++;
843     }
844     if (!tls_module_count) return STATUS_SUCCESS;
845
846     TRACE( "count %u size %u\n", tls_module_count, tls_total_size );
847
848     tls_dirs = RtlAllocateHeap( GetProcessHeap(), 0, tls_module_count * sizeof(*tls_dirs) );
849     if (!tls_dirs) return STATUS_NO_MEMORY;
850
851     for (i = 0, entry = mark->Flink; entry != mark; entry = entry->Flink)
852     {
853         mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
854         if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
855                                                   IMAGE_DIRECTORY_ENTRY_TLS, &size )))
856             continue;
857         tls_dirs[i] = dir;
858         *(DWORD *)dir->AddressOfIndex = i;
859         mod->TlsIndex = i;
860         mod->LoadCount = -1;  /* can't unload it */
861         i++;
862     }
863     return STATUS_SUCCESS;
864 }
865
866
867 /*************************************************************************
868  *              alloc_thread_tls
869  *
870  * Allocate the per-thread structure for module TLS storage.
871  */
872 static NTSTATUS alloc_thread_tls(void)
873 {
874     void **pointers;
875     char *data;
876     UINT i;
877
878     if (!tls_module_count) return STATUS_SUCCESS;
879
880     if (!(pointers = RtlAllocateHeap( GetProcessHeap(), 0,
881                                       tls_module_count * sizeof(*pointers) )))
882         return STATUS_NO_MEMORY;
883
884     if (!(data = RtlAllocateHeap( GetProcessHeap(), 0, tls_total_size )))
885     {
886         RtlFreeHeap( GetProcessHeap(), 0, pointers );
887         return STATUS_NO_MEMORY;
888     }
889
890     for (i = 0; i < tls_module_count; i++)
891     {
892         const IMAGE_TLS_DIRECTORY *dir = tls_dirs[i];
893         ULONG size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
894
895         TRACE( "thread %04x idx %d: %d/%d bytes from %p to %p\n",
896                GetCurrentThreadId(), i, size, dir->SizeOfZeroFill,
897                (void *)dir->StartAddressOfRawData, data );
898
899         pointers[i] = data;
900         memcpy( data, (void *)dir->StartAddressOfRawData, size );
901         data += size;
902         memset( data, 0, dir->SizeOfZeroFill );
903         data += dir->SizeOfZeroFill;
904     }
905     NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
906     return STATUS_SUCCESS;
907 }
908
909
910 /*************************************************************************
911  *              call_tls_callbacks
912  */
913 static void call_tls_callbacks( HMODULE module, UINT reason )
914 {
915     const IMAGE_TLS_DIRECTORY *dir;
916     const PIMAGE_TLS_CALLBACK *callback;
917     ULONG dirsize;
918
919     dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
920     if (!dir || !dir->AddressOfCallBacks) return;
921
922     for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
923     {
924         if (TRACE_ON(relay))
925             DPRINTF("%04x:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
926                     GetCurrentThreadId(), *callback, module, reason_names[reason] );
927         __TRY
928         {
929             (*callback)( module, reason, NULL );
930         }
931         __EXCEPT_ALL
932         {
933             if (TRACE_ON(relay))
934                 DPRINTF("%04x:exception in TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
935                         GetCurrentThreadId(), callback, module, reason_names[reason] );
936             return;
937         }
938         __ENDTRY
939         if (TRACE_ON(relay))
940             DPRINTF("%04x:Ret  TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
941                     GetCurrentThreadId(), *callback, module, reason_names[reason] );
942     }
943 }
944
945
946 /*************************************************************************
947  *              MODULE_InitDLL
948  */
949 static NTSTATUS MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
950 {
951     WCHAR mod_name[32];
952     NTSTATUS status = STATUS_SUCCESS;
953     DLLENTRYPROC entry = wm->ldr.EntryPoint;
954     void *module = wm->ldr.BaseAddress;
955     BOOL retv = TRUE;
956
957     /* Skip calls for modules loaded with special load flags */
958
959     if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return STATUS_SUCCESS;
960     if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.BaseAddress, reason );
961     if (!entry) return STATUS_SUCCESS;
962
963     if (TRACE_ON(relay))
964     {
965         size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
966         memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
967         mod_name[len / sizeof(WCHAR)] = 0;
968         DPRINTF("%04x:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
969                 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
970                 reason_names[reason], lpReserved );
971     }
972     else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
973                reason_names[reason], lpReserved );
974
975     __TRY
976     {
977         retv = call_dll_entry_point( entry, module, reason, lpReserved );
978         if (!retv)
979             status = STATUS_DLL_INIT_FAILED;
980     }
981     __EXCEPT_ALL
982     {
983         if (TRACE_ON(relay))
984             DPRINTF("%04x:exception in PE entry point (proc=%p,module=%p,reason=%s,res=%p)\n",
985                     GetCurrentThreadId(), entry, module, reason_names[reason], lpReserved );
986         status = GetExceptionCode();
987     }
988     __ENDTRY
989
990     /* The state of the module list may have changed due to the call
991        to the dll. We cannot assume that this module has not been
992        deleted.  */
993     if (TRACE_ON(relay))
994         DPRINTF("%04x:Ret  PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
995                 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
996                 reason_names[reason], lpReserved, retv );
997     else TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
998
999     return status;
1000 }
1001
1002
1003 /*************************************************************************
1004  *              process_attach
1005  *
1006  * Send the process attach notification to all DLLs the given module
1007  * depends on (recursively). This is somewhat complicated due to the fact that
1008  *
1009  * - we have to respect the module dependencies, i.e. modules implicitly
1010  *   referenced by another module have to be initialized before the module
1011  *   itself can be initialized
1012  *
1013  * - the initialization routine of a DLL can itself call LoadLibrary,
1014  *   thereby introducing a whole new set of dependencies (even involving
1015  *   the 'old' modules) at any time during the whole process
1016  *
1017  * (Note that this routine can be recursively entered not only directly
1018  *  from itself, but also via LoadLibrary from one of the called initialization
1019  *  routines.)
1020  *
1021  * Furthermore, we need to rearrange the main WINE_MODREF list to allow
1022  * the process *detach* notifications to be sent in the correct order.
1023  * This must not only take into account module dependencies, but also
1024  * 'hidden' dependencies created by modules calling LoadLibrary in their
1025  * attach notification routine.
1026  *
1027  * The strategy is rather simple: we move a WINE_MODREF to the head of the
1028  * list after the attach notification has returned.  This implies that the
1029  * detach notifications are called in the reverse of the sequence the attach
1030  * notifications *returned*.
1031  *
1032  * The loader_section must be locked while calling this function.
1033  */
1034 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
1035 {
1036     NTSTATUS status = STATUS_SUCCESS;
1037     ULONG_PTR cookie;
1038     int i;
1039
1040     if (process_detaching) return status;
1041
1042     /* prevent infinite recursion in case of cyclical dependencies */
1043     if (    ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
1044          || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
1045         return status;
1046
1047     TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1048
1049     /* Tag current MODREF to prevent recursive loop */
1050     wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
1051     if (lpReserved) wm->ldr.LoadCount = -1;  /* pin it if imported by the main exe */
1052     if (wm->ldr.ActivationContext) RtlActivateActivationContext( 0, wm->ldr.ActivationContext, &cookie );
1053
1054     /* Recursively attach all DLLs this one depends on */
1055     for ( i = 0; i < wm->nDeps; i++ )
1056     {
1057         if (!wm->deps[i]) continue;
1058         if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
1059     }
1060
1061     /* Call DLL entry point */
1062     if (status == STATUS_SUCCESS)
1063     {
1064         WINE_MODREF *prev = current_modref;
1065         current_modref = wm;
1066         status = MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved );
1067         if (status == STATUS_SUCCESS)
1068             wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
1069         else
1070         {
1071             /* point to the name so LdrInitializeThunk can print it */
1072             last_failed_modref = wm;
1073             WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
1074         }
1075         current_modref = prev;
1076     }
1077
1078     if (!wm->ldr.InInitializationOrderModuleList.Flink)
1079         InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
1080                        &wm->ldr.InInitializationOrderModuleList);
1081
1082     if (wm->ldr.ActivationContext) RtlDeactivateActivationContext( 0, cookie );
1083     /* Remove recursion flag */
1084     wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
1085
1086     TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
1087     return status;
1088 }
1089
1090
1091 /**********************************************************************
1092  *          attach_implicitly_loaded_dlls
1093  *
1094  * Attach to the (builtin) dlls that have been implicitly loaded because
1095  * of a dependency at the Unix level, but not imported at the Win32 level.
1096  */
1097 static void attach_implicitly_loaded_dlls( LPVOID reserved )
1098 {
1099     for (;;)
1100     {
1101         PLIST_ENTRY mark, entry;
1102
1103         mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1104         for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1105         {
1106             LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1107
1108             if (mod->Flags & (LDR_LOAD_IN_PROGRESS | LDR_PROCESS_ATTACHED)) continue;
1109             TRACE( "found implicitly loaded %s, attaching to it\n",
1110                    debugstr_w(mod->BaseDllName.Buffer));
1111             process_attach( CONTAINING_RECORD(mod, WINE_MODREF, ldr), reserved );
1112             break;  /* restart the search from the start */
1113         }
1114         if (entry == mark) break;  /* nothing found */
1115     }
1116 }
1117
1118
1119 /*************************************************************************
1120  *              process_detach
1121  *
1122  * Send DLL process detach notifications.  See the comment about calling
1123  * sequence at process_attach.  Unless the bForceDetach flag
1124  * is set, only DLLs with zero refcount are notified.
1125  */
1126 static void process_detach( BOOL bForceDetach, LPVOID lpReserved )
1127 {
1128     PLIST_ENTRY mark, entry;
1129     PLDR_MODULE mod;
1130
1131     RtlEnterCriticalSection( &loader_section );
1132     if (bForceDetach) process_detaching = 1;
1133     mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1134     do
1135     {
1136         for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1137         {
1138             mod = CONTAINING_RECORD(entry, LDR_MODULE, 
1139                                     InInitializationOrderModuleList);
1140             /* Check whether to detach this DLL */
1141             if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1142                 continue;
1143             if ( mod->LoadCount && !bForceDetach )
1144                 continue;
1145
1146             /* Call detach notification */
1147             mod->Flags &= ~LDR_PROCESS_ATTACHED;
1148             MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr), 
1149                             DLL_PROCESS_DETACH, lpReserved );
1150
1151             /* Restart at head of WINE_MODREF list, as entries might have
1152                been added and/or removed while performing the call ... */
1153             break;
1154         }
1155     } while (entry != mark);
1156
1157     RtlLeaveCriticalSection( &loader_section );
1158 }
1159
1160 /*************************************************************************
1161  *              MODULE_DllThreadAttach
1162  *
1163  * Send DLL thread attach notifications. These are sent in the
1164  * reverse sequence of process detach notification.
1165  *
1166  */
1167 NTSTATUS MODULE_DllThreadAttach( LPVOID lpReserved )
1168 {
1169     PLIST_ENTRY mark, entry;
1170     PLDR_MODULE mod;
1171     NTSTATUS    status;
1172
1173     /* don't do any attach calls if process is exiting */
1174     if (process_detaching) return STATUS_SUCCESS;
1175     /* FIXME: there is still a race here */
1176
1177     RtlEnterCriticalSection( &loader_section );
1178
1179     if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto done;
1180
1181     mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1182     for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1183     {
1184         mod = CONTAINING_RECORD(entry, LDR_MODULE, 
1185                                 InInitializationOrderModuleList);
1186         if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1187             continue;
1188         if ( mod->Flags & LDR_NO_DLL_CALLS )
1189             continue;
1190
1191         MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1192                         DLL_THREAD_ATTACH, lpReserved );
1193     }
1194
1195 done:
1196     RtlLeaveCriticalSection( &loader_section );
1197     return status;
1198 }
1199
1200 /******************************************************************
1201  *              LdrDisableThreadCalloutsForDll (NTDLL.@)
1202  *
1203  */
1204 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1205 {
1206     WINE_MODREF *wm;
1207     NTSTATUS    ret = STATUS_SUCCESS;
1208
1209     RtlEnterCriticalSection( &loader_section );
1210
1211     wm = get_modref( hModule );
1212     if (!wm || wm->ldr.TlsIndex != -1)
1213         ret = STATUS_DLL_NOT_FOUND;
1214     else
1215         wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1216
1217     RtlLeaveCriticalSection( &loader_section );
1218
1219     return ret;
1220 }
1221
1222 /******************************************************************
1223  *              LdrFindEntryForAddress (NTDLL.@)
1224  *
1225  * The loader_section must be locked while calling this function
1226  */
1227 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
1228 {
1229     PLIST_ENTRY mark, entry;
1230     PLDR_MODULE mod;
1231
1232     mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1233     for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1234     {
1235         mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
1236         if (mod->BaseAddress <= addr &&
1237             (const char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
1238         {
1239             *pmod = mod;
1240             return STATUS_SUCCESS;
1241         }
1242         if (mod->BaseAddress > addr) break;
1243     }
1244     return STATUS_NO_MORE_ENTRIES;
1245 }
1246
1247 /******************************************************************
1248  *              LdrLockLoaderLock  (NTDLL.@)
1249  *
1250  * Note: flags are not implemented.
1251  * Flag 0x01 is used to raise exceptions on errors.
1252  * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
1253  */
1254 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG *magic )
1255 {
1256     if (flags) FIXME( "flags %x not supported\n", flags );
1257
1258     if (result) *result = 1;
1259     if (!magic) return STATUS_INVALID_PARAMETER_3;
1260     RtlEnterCriticalSection( &loader_section );
1261     *magic = GetCurrentThreadId();
1262     return STATUS_SUCCESS;
1263 }
1264
1265
1266 /******************************************************************
1267  *              LdrUnlockLoaderUnlock  (NTDLL.@)
1268  */
1269 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG magic )
1270 {
1271     if (magic)
1272     {
1273         if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1274         RtlLeaveCriticalSection( &loader_section );
1275     }
1276     return STATUS_SUCCESS;
1277 }
1278
1279
1280 /******************************************************************
1281  *              LdrGetProcedureAddress  (NTDLL.@)
1282  */
1283 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1284                                        ULONG ord, PVOID *address)
1285 {
1286     IMAGE_EXPORT_DIRECTORY *exports;
1287     DWORD exp_size;
1288     NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1289
1290     RtlEnterCriticalSection( &loader_section );
1291
1292     /* check if the module itself is invalid to return the proper error */
1293     if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1294     else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1295                                                       IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1296     {
1297         LPCWSTR load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1298         void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1, load_path )
1299                           : find_ordinal_export( module, exports, exp_size, ord - exports->Base, load_path );
1300         if (proc)
1301         {
1302             *address = proc;
1303             ret = STATUS_SUCCESS;
1304         }
1305     }
1306
1307     RtlLeaveCriticalSection( &loader_section );
1308     return ret;
1309 }
1310
1311
1312 /***********************************************************************
1313  *           is_fake_dll
1314  *
1315  * Check if a loaded native dll is a Wine fake dll.
1316  */
1317 static BOOL is_fake_dll( HANDLE handle )
1318 {
1319     static const char fakedll_signature[] = "Wine placeholder DLL";
1320     char buffer[sizeof(IMAGE_DOS_HEADER) + sizeof(fakedll_signature)];
1321     const IMAGE_DOS_HEADER *dos = (const IMAGE_DOS_HEADER *)buffer;
1322     IO_STATUS_BLOCK io;
1323     LARGE_INTEGER offset;
1324
1325     offset.QuadPart = 0;
1326     if (NtReadFile( handle, 0, NULL, 0, &io, buffer, sizeof(buffer), &offset, NULL )) return FALSE;
1327     if (io.Information < sizeof(buffer)) return FALSE;
1328     if (dos->e_magic != IMAGE_DOS_SIGNATURE) return FALSE;
1329     if (dos->e_lfanew >= sizeof(*dos) + sizeof(fakedll_signature) &&
1330         !memcmp( dos + 1, fakedll_signature, sizeof(fakedll_signature) )) return TRUE;
1331     return FALSE;
1332 }
1333
1334
1335 /***********************************************************************
1336  *           get_builtin_fullname
1337  *
1338  * Build the full pathname for a builtin dll.
1339  */
1340 static WCHAR *get_builtin_fullname( const WCHAR *path, const char *filename )
1341 {
1342     static const WCHAR soW[] = {'.','s','o',0};
1343     WCHAR *p, *fullname;
1344     size_t i, len = strlen(filename);
1345
1346     /* check if path can correspond to the dll we have */
1347     if (path && (p = strrchrW( path, '\\' )))
1348     {
1349         p++;
1350         for (i = 0; i < len; i++)
1351             if (tolowerW(p[i]) != tolowerW( (WCHAR)filename[i]) ) break;
1352         if (i == len && (!p[len] || !strcmpiW( p + len, soW )))
1353         {
1354             /* the filename matches, use path as the full path */
1355             len += p - path;
1356             if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0, (len + 1) * sizeof(WCHAR) )))
1357             {
1358                 memcpy( fullname, path, len * sizeof(WCHAR) );
1359                 fullname[len] = 0;
1360             }
1361             return fullname;
1362         }
1363     }
1364
1365     if ((fullname = RtlAllocateHeap( GetProcessHeap(), 0,
1366                                      system_dir.MaximumLength + (len + 1) * sizeof(WCHAR) )))
1367     {
1368         memcpy( fullname, system_dir.Buffer, system_dir.Length );
1369         p = fullname + system_dir.Length / sizeof(WCHAR);
1370         if (p > fullname && p[-1] != '\\') *p++ = '\\';
1371         ascii_to_unicode( p, filename, len + 1 );
1372     }
1373     return fullname;
1374 }
1375
1376
1377 /***********************************************************************
1378  *           load_builtin_callback
1379  *
1380  * Load a library in memory; callback function for wine_dll_register
1381  */
1382 static void load_builtin_callback( void *module, const char *filename )
1383 {
1384     static const WCHAR emptyW[1];
1385     IMAGE_NT_HEADERS *nt;
1386     WINE_MODREF *wm;
1387     WCHAR *fullname;
1388     const WCHAR *load_path;
1389
1390     if (!module)
1391     {
1392         ERR("could not map image for %s\n", filename ? filename : "main exe" );
1393         return;
1394     }
1395     if (!(nt = RtlImageNtHeader( module )))
1396     {
1397         ERR( "bad module for %s\n", filename ? filename : "main exe" );
1398         builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1399         return;
1400     }
1401     virtual_create_system_view( module, nt->OptionalHeader.SizeOfImage,
1402                                 VPROT_SYSTEM | VPROT_IMAGE | VPROT_COMMITTED |
1403                                 VPROT_READ | VPROT_WRITECOPY | VPROT_EXEC );
1404
1405     /* create the MODREF */
1406
1407     if (!(fullname = get_builtin_fullname( builtin_load_info->filename, filename )))
1408     {
1409         ERR( "can't load %s\n", filename );
1410         builtin_load_info->status = STATUS_NO_MEMORY;
1411         return;
1412     }
1413
1414     wm = alloc_module( module, fullname );
1415     RtlFreeHeap( GetProcessHeap(), 0, fullname );
1416     if (!wm)
1417     {
1418         ERR( "can't load %s\n", filename );
1419         builtin_load_info->status = STATUS_NO_MEMORY;
1420         return;
1421     }
1422     wm->ldr.Flags |= LDR_WINE_INTERNAL;
1423
1424     if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL) &&
1425         !NtCurrentTeb()->Peb->ImageBaseAddress)  /* if we already have an executable, ignore this one */
1426     {
1427         NtCurrentTeb()->Peb->ImageBaseAddress = module;
1428     }
1429     else
1430     {
1431         /* fixup imports */
1432
1433         load_path = builtin_load_info->load_path;
1434         if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1435         if (!load_path) load_path = emptyW;
1436         if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1437         {
1438             /* the module has only be inserted in the load & memory order lists */
1439             RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1440             RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1441             /* FIXME: free the modref */
1442             builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1443             return;
1444         }
1445     }
1446
1447     builtin_load_info->wm = wm;
1448     TRACE( "loaded %s %p %p\n", filename, wm, module );
1449
1450     /* send the DLL load event */
1451
1452     SERVER_START_REQ( load_dll )
1453     {
1454         req->handle     = 0;
1455         req->base       = wine_server_client_ptr( module );
1456         req->size       = nt->OptionalHeader.SizeOfImage;
1457         req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1458         req->dbg_size   = nt->FileHeader.NumberOfSymbols;
1459         req->name       = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1460         wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1461         wine_server_call( req );
1462     }
1463     SERVER_END_REQ;
1464
1465     /* setup relay debugging entry points */
1466     if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1467 }
1468
1469
1470 /******************************************************************************
1471  *      load_native_dll  (internal)
1472  */
1473 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1474                                  DWORD flags, WINE_MODREF** pwm )
1475 {
1476     void *module;
1477     HANDLE mapping;
1478     LARGE_INTEGER size;
1479     IMAGE_NT_HEADERS *nt;
1480     SIZE_T len = 0;
1481     WINE_MODREF *wm;
1482     NTSTATUS status;
1483
1484     TRACE("Trying native dll %s\n", debugstr_w(name));
1485
1486     size.QuadPart = 0;
1487     status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1488                               NULL, &size, PAGE_READONLY, SEC_IMAGE, file );
1489     if (status != STATUS_SUCCESS) return status;
1490
1491     module = NULL;
1492     status = NtMapViewOfSection( mapping, NtCurrentProcess(),
1493                                  &module, 0, 0, &size, &len, ViewShare, 0, PAGE_READONLY );
1494     NtClose( mapping );
1495     if (status != STATUS_SUCCESS) return status;
1496
1497     /* create the MODREF */
1498
1499     if (!(wm = alloc_module( module, name ))) return STATUS_NO_MEMORY;
1500
1501     /* fixup imports */
1502
1503     if (!(flags & DONT_RESOLVE_DLL_REFERENCES))
1504     {
1505         if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1506         {
1507             /* the module has only be inserted in the load & memory order lists */
1508             RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1509             RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1510
1511             /* FIXME: there are several more dangling references
1512              * left. Including dlls loaded by this dll before the
1513              * failed one. Unrolling is rather difficult with the
1514              * current structure and we can leave them lying
1515              * around with no problems, so we don't care.
1516              * As these might reference our wm, we don't free it.
1517              */
1518             return status;
1519         }
1520     }
1521
1522     /* send DLL load event */
1523
1524     nt = RtlImageNtHeader( module );
1525
1526     SERVER_START_REQ( load_dll )
1527     {
1528         req->handle     = wine_server_obj_handle( file );
1529         req->base       = wine_server_client_ptr( module );
1530         req->size       = nt->OptionalHeader.SizeOfImage;
1531         req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1532         req->dbg_size   = nt->FileHeader.NumberOfSymbols;
1533         req->name       = wine_server_client_ptr( &wm->ldr.FullDllName.Buffer );
1534         wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1535         wine_server_call( req );
1536     }
1537     SERVER_END_REQ;
1538
1539     if ((wm->ldr.Flags & LDR_IMAGE_IS_DLL) && TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1540
1541     TRACE_(loaddll)( "Loaded %s at %p: native\n", debugstr_w(wm->ldr.FullDllName.Buffer), module );
1542
1543     wm->ldr.LoadCount = 1;
1544     *pwm = wm;
1545     return STATUS_SUCCESS;
1546 }
1547
1548
1549 /***********************************************************************
1550  *           load_builtin_dll
1551  */
1552 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, HANDLE file,
1553                                   DWORD flags, WINE_MODREF** pwm )
1554 {
1555     char error[256], dllname[MAX_PATH];
1556     const WCHAR *name, *p;
1557     DWORD len, i;
1558     void *handle = NULL;
1559     struct builtin_load_info info, *prev_info;
1560
1561     /* Fix the name in case we have a full path and extension */
1562     name = path;
1563     if ((p = strrchrW( name, '\\' ))) name = p + 1;
1564     if ((p = strrchrW( name, '/' ))) name = p + 1;
1565
1566     /* load_library will modify info.status. Note also that load_library can be
1567      * called several times, if the .so file we're loading has dependencies.
1568      * info.status will gather all the errors we may get while loading all these
1569      * libraries
1570      */
1571     info.load_path = load_path;
1572     info.filename  = NULL;
1573     info.status    = STATUS_SUCCESS;
1574     info.wm        = NULL;
1575
1576     if (file)  /* we have a real file, try to load it */
1577     {
1578         UNICODE_STRING nt_name;
1579         ANSI_STRING unix_name;
1580
1581         TRACE("Trying built-in %s\n", debugstr_w(path));
1582
1583         if (!RtlDosPathNameToNtPathName_U( path, &nt_name, NULL, NULL ))
1584             return STATUS_DLL_NOT_FOUND;
1585
1586         if (wine_nt_to_unix_file_name( &nt_name, &unix_name, FILE_OPEN, FALSE ))
1587         {
1588             RtlFreeUnicodeString( &nt_name );
1589             return STATUS_DLL_NOT_FOUND;
1590         }
1591         prev_info = builtin_load_info;
1592         info.filename = nt_name.Buffer + 4;  /* skip \??\ */
1593         builtin_load_info = &info;
1594         handle = wine_dlopen( unix_name.Buffer, RTLD_NOW, error, sizeof(error) );
1595         builtin_load_info = prev_info;
1596         RtlFreeUnicodeString( &nt_name );
1597         RtlFreeHeap( GetProcessHeap(), 0, unix_name.Buffer );
1598         if (!handle)
1599         {
1600             WARN( "failed to load .so lib for builtin %s: %s\n", debugstr_w(path), error );
1601             return STATUS_INVALID_IMAGE_FORMAT;
1602         }
1603     }
1604     else
1605     {
1606         int file_exists;
1607
1608         TRACE("Trying built-in %s\n", debugstr_w(name));
1609
1610         /* we don't want to depend on the current codepage here */
1611         len = strlenW( name ) + 1;
1612         if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1613         for (i = 0; i < len; i++)
1614         {
1615             if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1616             dllname[i] = (char)name[i];
1617             if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1618         }
1619
1620         prev_info = builtin_load_info;
1621         builtin_load_info = &info;
1622         handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1623         builtin_load_info = prev_info;
1624         if (!handle)
1625         {
1626             if (!file_exists)
1627             {
1628                 /* The file does not exist -> WARN() */
1629                 WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
1630                 return STATUS_DLL_NOT_FOUND;
1631             }
1632             /* ERR() for all other errors (missing functions, ...) */
1633             ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
1634             return STATUS_PROCEDURE_NOT_FOUND;
1635         }
1636     }
1637
1638     if (info.status != STATUS_SUCCESS)
1639     {
1640         wine_dll_unload( handle );
1641         return info.status;
1642     }
1643
1644     if (!info.wm)
1645     {
1646         PLIST_ENTRY mark, entry;
1647
1648         /* The constructor wasn't called, this means the .so is already
1649          * loaded under a different name. Try to find the wm for it. */
1650
1651         mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1652         for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1653         {
1654             LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1655             if (mod->Flags & LDR_WINE_INTERNAL && mod->SectionHandle == handle)
1656             {
1657                 info.wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1658                 TRACE( "Found %s at %p for builtin %s\n",
1659                        debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress, debugstr_w(path) );
1660                 break;
1661             }
1662         }
1663         wine_dll_unload( handle );  /* release the libdl refcount */
1664         if (!info.wm) return STATUS_INVALID_IMAGE_FORMAT;
1665         if (info.wm->ldr.LoadCount != -1) info.wm->ldr.LoadCount++;
1666     }
1667     else
1668     {
1669         TRACE_(loaddll)( "Loaded %s at %p: builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer), info.wm->ldr.BaseAddress );
1670         info.wm->ldr.LoadCount = 1;
1671         info.wm->ldr.SectionHandle = handle;
1672     }
1673
1674     *pwm = info.wm;
1675     return STATUS_SUCCESS;
1676 }
1677
1678
1679 /***********************************************************************
1680  *      find_actctx_dll
1681  *
1682  * Find the full path (if any) of the dll from the activation context.
1683  */
1684 static NTSTATUS find_actctx_dll( LPCWSTR libname, LPWSTR *fullname )
1685 {
1686     static const WCHAR winsxsW[] = {'\\','w','i','n','s','x','s','\\'};
1687     static const WCHAR dotManifestW[] = {'.','m','a','n','i','f','e','s','t',0};
1688
1689     ACTIVATION_CONTEXT_ASSEMBLY_DETAILED_INFORMATION *info;
1690     ACTCTX_SECTION_KEYED_DATA data;
1691     UNICODE_STRING nameW;
1692     NTSTATUS status;
1693     SIZE_T needed, size = 1024;
1694     WCHAR *p;
1695
1696     RtlInitUnicodeString( &nameW, libname );
1697     data.cbSize = sizeof(data);
1698     status = RtlFindActivationContextSectionString( FIND_ACTCTX_SECTION_KEY_RETURN_HACTCTX, NULL,
1699                                                     ACTIVATION_CONTEXT_SECTION_DLL_REDIRECTION,
1700                                                     &nameW, &data );
1701     if (status != STATUS_SUCCESS) return status;
1702
1703     for (;;)
1704     {
1705         if (!(info = RtlAllocateHeap( GetProcessHeap(), 0, size )))
1706         {
1707             status = STATUS_NO_MEMORY;
1708             goto done;
1709         }
1710         status = RtlQueryInformationActivationContext( 0, data.hActCtx, &data.ulAssemblyRosterIndex,
1711                                                        AssemblyDetailedInformationInActivationContext,
1712                                                        info, size, &needed );
1713         if (status == STATUS_SUCCESS) break;
1714         if (status != STATUS_BUFFER_TOO_SMALL) goto done;
1715         RtlFreeHeap( GetProcessHeap(), 0, info );
1716         size = needed;
1717         /* restart with larger buffer */
1718     }
1719
1720     if (!info->lpAssemblyManifestPath || !info->lpAssemblyDirectoryName)
1721     {
1722         status = STATUS_SXS_KEY_NOT_FOUND;
1723         goto done;
1724     }
1725
1726     if ((p = strrchrW( info->lpAssemblyManifestPath, '\\' )))
1727     {
1728         DWORD dirlen = info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1729
1730         p++;
1731         if (strncmpiW( p, info->lpAssemblyDirectoryName, dirlen ) || strcmpiW( p + dirlen, dotManifestW ))
1732         {
1733             /* manifest name does not match directory name, so it's not a global
1734              * windows/winsxs manifest; use the manifest directory name instead */
1735             dirlen = p - info->lpAssemblyManifestPath;
1736             needed = (dirlen + 1) * sizeof(WCHAR) + nameW.Length;
1737             if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1738             {
1739                 status = STATUS_NO_MEMORY;
1740                 goto done;
1741             }
1742             memcpy( p, info->lpAssemblyManifestPath, dirlen * sizeof(WCHAR) );
1743             p += dirlen;
1744             strcpyW( p, libname );
1745             goto done;
1746         }
1747     }
1748
1749     needed = (windows_dir.Length + sizeof(winsxsW) + info->ulAssemblyDirectoryNameLength +
1750               nameW.Length + 2*sizeof(WCHAR));
1751
1752     if (!(*fullname = p = RtlAllocateHeap( GetProcessHeap(), 0, needed )))
1753     {
1754         status = STATUS_NO_MEMORY;
1755         goto done;
1756     }
1757     memcpy( p, windows_dir.Buffer, windows_dir.Length );
1758     p += windows_dir.Length / sizeof(WCHAR);
1759     memcpy( p, winsxsW, sizeof(winsxsW) );
1760     p += sizeof(winsxsW) / sizeof(WCHAR);
1761     memcpy( p, info->lpAssemblyDirectoryName, info->ulAssemblyDirectoryNameLength );
1762     p += info->ulAssemblyDirectoryNameLength / sizeof(WCHAR);
1763     *p++ = '\\';
1764     strcpyW( p, libname );
1765 done:
1766     RtlFreeHeap( GetProcessHeap(), 0, info );
1767     RtlReleaseActivationContext( data.hActCtx );
1768     return status;
1769 }
1770
1771
1772 /***********************************************************************
1773  *      find_dll_file
1774  *
1775  * Find the file (or already loaded module) for a given dll name.
1776  */
1777 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
1778                                WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
1779 {
1780     OBJECT_ATTRIBUTES attr;
1781     IO_STATUS_BLOCK io;
1782     UNICODE_STRING nt_name;
1783     WCHAR *file_part, *ext, *dllname;
1784     ULONG len;
1785
1786     /* first append .dll if needed */
1787
1788     dllname = NULL;
1789     if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
1790     {
1791         if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
1792                                          (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
1793             return STATUS_NO_MEMORY;
1794         strcpyW( dllname, libname );
1795         strcatW( dllname, dllW );
1796         libname = dllname;
1797     }
1798
1799     nt_name.Buffer = NULL;
1800
1801     if (!contains_path( libname ))
1802     {
1803         NTSTATUS status;
1804         WCHAR *fullname = NULL;
1805
1806         if ((*pwm = find_basename_module( libname )) != NULL) goto found;
1807
1808         status = find_actctx_dll( libname, &fullname );
1809         if (status == STATUS_SUCCESS)
1810         {
1811             TRACE ("found %s for %s\n", debugstr_w(fullname), debugstr_w(libname) );
1812             RtlFreeHeap( GetProcessHeap(), 0, dllname );
1813             libname = dllname = fullname;
1814         }
1815         else if (status != STATUS_SXS_KEY_NOT_FOUND)
1816         {
1817             RtlFreeHeap( GetProcessHeap(), 0, dllname );
1818             return status;
1819         }
1820     }
1821
1822     if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
1823     {
1824         /* we need to search for it */
1825         len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
1826         if (len)
1827         {
1828             if (len >= *size) goto overflow;
1829             if ((*pwm = find_fullname_module( filename )) || !handle) goto found;
1830
1831             if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
1832             {
1833                 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1834                 return STATUS_NO_MEMORY;
1835             }
1836             attr.Length = sizeof(attr);
1837             attr.RootDirectory = 0;
1838             attr.Attributes = OBJ_CASE_INSENSITIVE;
1839             attr.ObjectName = &nt_name;
1840             attr.SecurityDescriptor = NULL;
1841             attr.SecurityQualityOfService = NULL;
1842             if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1843             goto found;
1844         }
1845
1846         /* not found */
1847
1848         if (!contains_path( libname ))
1849         {
1850             /* if libname doesn't contain a path at all, we simply return the name as is,
1851              * to be loaded as builtin */
1852             len = strlenW(libname) * sizeof(WCHAR);
1853             if (len >= *size) goto overflow;
1854             strcpyW( filename, libname );
1855             goto found;
1856         }
1857     }
1858
1859     /* absolute path name, or relative path name but not found above */
1860
1861     if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
1862     {
1863         RtlFreeHeap( GetProcessHeap(), 0, dllname );
1864         return STATUS_NO_MEMORY;
1865     }
1866     len = nt_name.Length - 4*sizeof(WCHAR);  /* for \??\ prefix */
1867     if (len >= *size) goto overflow;
1868     memcpy( filename, nt_name.Buffer + 4, len + sizeof(WCHAR) );
1869     if (!(*pwm = find_fullname_module( filename )) && handle)
1870     {
1871         attr.Length = sizeof(attr);
1872         attr.RootDirectory = 0;
1873         attr.Attributes = OBJ_CASE_INSENSITIVE;
1874         attr.ObjectName = &nt_name;
1875         attr.SecurityDescriptor = NULL;
1876         attr.SecurityQualityOfService = NULL;
1877         if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1878     }
1879 found:
1880     RtlFreeUnicodeString( &nt_name );
1881     RtlFreeHeap( GetProcessHeap(), 0, dllname );
1882     return STATUS_SUCCESS;
1883
1884 overflow:
1885     RtlFreeUnicodeString( &nt_name );
1886     RtlFreeHeap( GetProcessHeap(), 0, dllname );
1887     *size = len + sizeof(WCHAR);
1888     return STATUS_BUFFER_TOO_SMALL;
1889 }
1890
1891
1892 /***********************************************************************
1893  *      load_dll  (internal)
1894  *
1895  * Load a PE style module according to the load order.
1896  * The loader_section must be locked while calling this function.
1897  */
1898 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
1899 {
1900     enum loadorder loadorder;
1901     WCHAR buffer[32];
1902     WCHAR *filename;
1903     ULONG size;
1904     WINE_MODREF *main_exe;
1905     HANDLE handle = 0;
1906     NTSTATUS nts;
1907
1908     TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
1909
1910     *pwm = NULL;
1911     filename = buffer;
1912     size = sizeof(buffer);
1913     for (;;)
1914     {
1915         nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
1916         if (nts == STATUS_SUCCESS) break;
1917         if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1918         if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
1919         /* grow the buffer and retry */
1920         if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
1921     }
1922
1923     if (*pwm)  /* found already loaded module */
1924     {
1925         if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
1926
1927         if (!(flags & DONT_RESOLVE_DLL_REFERENCES)) fixup_imports( *pwm, load_path );
1928
1929         TRACE("Found %s for %s at %p, count=%d\n",
1930               debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
1931               (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
1932         if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1933         return STATUS_SUCCESS;
1934     }
1935
1936     main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
1937     loadorder = get_load_order( main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
1938
1939     if (handle && is_fake_dll( handle ))
1940     {
1941         TRACE( "%s is a fake Wine dll\n", debugstr_w(filename) );
1942         NtClose( handle );
1943         handle = 0;
1944     }
1945
1946     switch(loadorder)
1947     {
1948     case LO_INVALID:
1949         nts = STATUS_NO_MEMORY;
1950         break;
1951     case LO_DISABLED:
1952         nts = STATUS_DLL_NOT_FOUND;
1953         break;
1954     case LO_NATIVE:
1955     case LO_NATIVE_BUILTIN:
1956         if (!handle) nts = STATUS_DLL_NOT_FOUND;
1957         else
1958         {
1959             nts = load_native_dll( load_path, filename, handle, flags, pwm );
1960             if (nts == STATUS_INVALID_FILE_FOR_SECTION)
1961                 /* not in PE format, maybe it's a builtin */
1962                 nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1963         }
1964         if (nts == STATUS_DLL_NOT_FOUND && loadorder == LO_NATIVE_BUILTIN)
1965             nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1966         break;
1967     case LO_BUILTIN:
1968     case LO_BUILTIN_NATIVE:
1969     case LO_DEFAULT:  /* default is builtin,native */
1970         nts = load_builtin_dll( load_path, filename, handle, flags, pwm );
1971         if (!handle) break;  /* nothing else we can try */
1972         /* file is not a builtin library, try without using the specified file */
1973         if (nts != STATUS_SUCCESS)
1974             nts = load_builtin_dll( load_path, filename, 0, flags, pwm );
1975         if (nts == STATUS_SUCCESS && loadorder == LO_DEFAULT &&
1976             (MODULE_InitDLL( *pwm, DLL_WINE_PREATTACH, NULL ) != STATUS_SUCCESS))
1977         {
1978             /* stub-only dll, try native */
1979             TRACE( "%s pre-attach returned FALSE, preferring native\n", debugstr_w(filename) );
1980             LdrUnloadDll( (*pwm)->ldr.BaseAddress );
1981             nts = STATUS_DLL_NOT_FOUND;
1982         }
1983         if (nts == STATUS_DLL_NOT_FOUND && loadorder != LO_BUILTIN)
1984             nts = load_native_dll( load_path, filename, handle, flags, pwm );
1985         break;
1986     }
1987
1988     if (nts == STATUS_SUCCESS)
1989     {
1990         /* Initialize DLL just loaded */
1991         TRACE("Loaded module %s (%s) at %p\n", debugstr_w(filename),
1992               ((*pwm)->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native",
1993               (*pwm)->ldr.BaseAddress);
1994         if (handle) NtClose( handle );
1995         if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1996         return nts;
1997     }
1998
1999     WARN("Failed to load module %s; status=%x\n", debugstr_w(libname), nts);
2000     if (handle) NtClose( handle );
2001     if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2002     return nts;
2003 }
2004
2005 /******************************************************************
2006  *              LdrLoadDll (NTDLL.@)
2007  */
2008 NTSTATUS WINAPI LdrLoadDll(LPCWSTR path_name, DWORD flags,
2009                            const UNICODE_STRING *libname, HMODULE* hModule)
2010 {
2011     WINE_MODREF *wm;
2012     NTSTATUS nts;
2013
2014     RtlEnterCriticalSection( &loader_section );
2015
2016     if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2017     nts = load_dll( path_name, libname->Buffer, flags, &wm );
2018
2019     if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
2020     {
2021         nts = process_attach( wm, NULL );
2022         if (nts != STATUS_SUCCESS)
2023         {
2024             LdrUnloadDll(wm->ldr.BaseAddress);
2025             wm = NULL;
2026         }
2027     }
2028     *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
2029
2030     RtlLeaveCriticalSection( &loader_section );
2031     return nts;
2032 }
2033
2034
2035 /******************************************************************
2036  *              LdrGetDllHandle (NTDLL.@)
2037  */
2038 NTSTATUS WINAPI LdrGetDllHandle( LPCWSTR load_path, ULONG flags, const UNICODE_STRING *name, HMODULE *base )
2039 {
2040     NTSTATUS status;
2041     WCHAR buffer[128];
2042     WCHAR *filename;
2043     ULONG size;
2044     WINE_MODREF *wm;
2045
2046     RtlEnterCriticalSection( &loader_section );
2047
2048     if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2049
2050     filename = buffer;
2051     size = sizeof(buffer);
2052     for (;;)
2053     {
2054         status = find_dll_file( load_path, name->Buffer, filename, &size, &wm, NULL );
2055         if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
2056         if (status != STATUS_BUFFER_TOO_SMALL) break;
2057         /* grow the buffer and retry */
2058         if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size )))
2059         {
2060             status = STATUS_NO_MEMORY;
2061             break;
2062         }
2063     }
2064
2065     if (status == STATUS_SUCCESS)
2066     {
2067         if (wm) *base = wm->ldr.BaseAddress;
2068         else status = STATUS_DLL_NOT_FOUND;
2069     }
2070
2071     RtlLeaveCriticalSection( &loader_section );
2072     TRACE( "%s -> %p (load path %s)\n", debugstr_us(name), status ? NULL : *base, debugstr_w(load_path) );
2073     return status;
2074 }
2075
2076
2077 /******************************************************************
2078  *              LdrAddRefDll (NTDLL.@)
2079  */
2080 NTSTATUS WINAPI LdrAddRefDll( ULONG flags, HMODULE module )
2081 {
2082     NTSTATUS ret = STATUS_SUCCESS;
2083     WINE_MODREF *wm;
2084
2085     if (flags) FIXME( "%p flags %x not implemented\n", module, flags );
2086
2087     RtlEnterCriticalSection( &loader_section );
2088
2089     if ((wm = get_modref( module )))
2090     {
2091         if (wm->ldr.LoadCount != -1) wm->ldr.LoadCount++;
2092         TRACE( "(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2093     }
2094     else ret = STATUS_INVALID_PARAMETER;
2095
2096     RtlLeaveCriticalSection( &loader_section );
2097     return ret;
2098 }
2099
2100
2101 /***********************************************************************
2102  *           LdrProcessRelocationBlock  (NTDLL.@)
2103  *
2104  * Apply relocations to a given page of a mapped PE image.
2105  */
2106 IMAGE_BASE_RELOCATION * WINAPI LdrProcessRelocationBlock( void *page, UINT count,
2107                                                           USHORT *relocs, INT_PTR delta )
2108 {
2109     while (count--)
2110     {
2111         USHORT offset = *relocs & 0xfff;
2112         int type = *relocs >> 12;
2113         switch(type)
2114         {
2115         case IMAGE_REL_BASED_ABSOLUTE:
2116             break;
2117 #ifdef __i386__
2118         case IMAGE_REL_BASED_HIGH:
2119             *(short *)((char *)page + offset) += HIWORD(delta);
2120             break;
2121         case IMAGE_REL_BASED_LOW:
2122             *(short *)((char *)page + offset) += LOWORD(delta);
2123             break;
2124         case IMAGE_REL_BASED_HIGHLOW:
2125             *(int *)((char *)page + offset) += delta;
2126             break;
2127 #elif defined(__x86_64__)
2128         case IMAGE_REL_BASED_DIR64:
2129             *(INT_PTR *)((char *)page + offset) += delta;
2130             break;
2131 #endif
2132         default:
2133             FIXME("Unknown/unsupported fixup type %x.\n", type);
2134             return NULL;
2135         }
2136         relocs++;
2137     }
2138     return (IMAGE_BASE_RELOCATION *)relocs;  /* return address of next block */
2139 }
2140
2141
2142 /******************************************************************
2143  *              LdrQueryProcessModuleInformation
2144  *
2145  */
2146 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi, 
2147                                                  ULONG buf_size, ULONG* req_size)
2148 {
2149     SYSTEM_MODULE*      sm = &smi->Modules[0];
2150     ULONG               size = sizeof(ULONG);
2151     NTSTATUS            nts = STATUS_SUCCESS;
2152     ANSI_STRING         str;
2153     char*               ptr;
2154     PLIST_ENTRY         mark, entry;
2155     PLDR_MODULE         mod;
2156     WORD id = 0;
2157
2158     smi->ModulesCount = 0;
2159
2160     RtlEnterCriticalSection( &loader_section );
2161     mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2162     for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2163     {
2164         mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2165         size += sizeof(*sm);
2166         if (size <= buf_size)
2167         {
2168             sm->Reserved1 = 0; /* FIXME */
2169             sm->Reserved2 = 0; /* FIXME */
2170             sm->ImageBaseAddress = mod->BaseAddress;
2171             sm->ImageSize = mod->SizeOfImage;
2172             sm->Flags = mod->Flags;
2173             sm->Id = id++;
2174             sm->Rank = 0; /* FIXME */
2175             sm->Unknown = 0; /* FIXME */
2176             str.Length = 0;
2177             str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
2178             str.Buffer = (char*)sm->Name;
2179             RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
2180             ptr = strrchr(str.Buffer, '\\');
2181             sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
2182
2183             smi->ModulesCount++;
2184             sm++;
2185         }
2186         else nts = STATUS_INFO_LENGTH_MISMATCH;
2187     }
2188     RtlLeaveCriticalSection( &loader_section );
2189
2190     if (req_size) *req_size = size;
2191
2192     return nts;
2193 }
2194
2195
2196 /******************************************************************
2197  *              RtlDllShutdownInProgress  (NTDLL.@)
2198  */
2199 BOOLEAN WINAPI RtlDllShutdownInProgress(void)
2200 {
2201     return process_detaching;
2202 }
2203
2204
2205 /******************************************************************
2206  *              LdrShutdownProcess (NTDLL.@)
2207  *
2208  */
2209 void WINAPI LdrShutdownProcess(void)
2210 {
2211     TRACE("()\n");
2212     process_detach( TRUE, (LPVOID)1 );
2213 }
2214
2215 /******************************************************************
2216  *              LdrShutdownThread (NTDLL.@)
2217  *
2218  */
2219 void WINAPI LdrShutdownThread(void)
2220 {
2221     PLIST_ENTRY mark, entry;
2222     PLDR_MODULE mod;
2223
2224     TRACE("()\n");
2225
2226     /* don't do any detach calls if process is exiting */
2227     if (process_detaching) return;
2228     /* FIXME: there is still a race here */
2229
2230     RtlEnterCriticalSection( &loader_section );
2231
2232     mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2233     for (entry = mark->Blink; entry != mark; entry = entry->Blink)
2234     {
2235         mod = CONTAINING_RECORD(entry, LDR_MODULE, 
2236                                 InInitializationOrderModuleList);
2237         if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
2238             continue;
2239         if ( mod->Flags & LDR_NO_DLL_CALLS )
2240             continue;
2241
2242         MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr), 
2243                         DLL_THREAD_DETACH, NULL );
2244     }
2245
2246     RtlLeaveCriticalSection( &loader_section );
2247     RtlFreeHeap( GetProcessHeap(), 0, NtCurrentTeb()->ThreadLocalStoragePointer );
2248 }
2249
2250
2251 /***********************************************************************
2252  *           free_modref
2253  *
2254  */
2255 static void free_modref( WINE_MODREF *wm )
2256 {
2257     RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
2258     RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
2259     if (wm->ldr.InInitializationOrderModuleList.Flink)
2260         RemoveEntryList(&wm->ldr.InInitializationOrderModuleList);
2261
2262     TRACE(" unloading %s\n", debugstr_w(wm->ldr.FullDllName.Buffer));
2263     if (!TRACE_ON(module))
2264         TRACE_(loaddll)("Unloaded module %s : %s\n",
2265                         debugstr_w(wm->ldr.FullDllName.Buffer),
2266                         (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
2267
2268     SERVER_START_REQ( unload_dll )
2269     {
2270         req->base = wine_server_client_ptr( wm->ldr.BaseAddress );
2271         wine_server_call( req );
2272     }
2273     SERVER_END_REQ;
2274
2275     RtlReleaseActivationContext( wm->ldr.ActivationContext );
2276     NtUnmapViewOfSection( NtCurrentProcess(), wm->ldr.BaseAddress );
2277     if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
2278     if (cached_modref == wm) cached_modref = NULL;
2279     RtlFreeUnicodeString( &wm->ldr.FullDllName );
2280     RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
2281     RtlFreeHeap( GetProcessHeap(), 0, wm );
2282 }
2283
2284 /***********************************************************************
2285  *           MODULE_FlushModrefs
2286  *
2287  * Remove all unused modrefs and call the internal unloading routines
2288  * for the library type.
2289  *
2290  * The loader_section must be locked while calling this function.
2291  */
2292 static void MODULE_FlushModrefs(void)
2293 {
2294     PLIST_ENTRY mark, entry, prev;
2295     PLDR_MODULE mod;
2296     WINE_MODREF*wm;
2297
2298     mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
2299     for (entry = mark->Blink; entry != mark; entry = prev)
2300     {
2301         mod = CONTAINING_RECORD(entry, LDR_MODULE, InInitializationOrderModuleList);
2302         wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2303         prev = entry->Blink;
2304         if (!mod->LoadCount) free_modref( wm );
2305     }
2306
2307     /* check load order list too for modules that haven't been initialized yet */
2308     mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2309     for (entry = mark->Blink; entry != mark; entry = prev)
2310     {
2311         mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
2312         wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
2313         prev = entry->Blink;
2314         if (!mod->LoadCount) free_modref( wm );
2315     }
2316 }
2317
2318 /***********************************************************************
2319  *           MODULE_DecRefCount
2320  *
2321  * The loader_section must be locked while calling this function.
2322  */
2323 static void MODULE_DecRefCount( WINE_MODREF *wm )
2324 {
2325     int i;
2326
2327     if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
2328         return;
2329
2330     if ( wm->ldr.LoadCount <= 0 )
2331         return;
2332
2333     --wm->ldr.LoadCount;
2334     TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
2335
2336     if ( wm->ldr.LoadCount == 0 )
2337     {
2338         wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
2339
2340         for ( i = 0; i < wm->nDeps; i++ )
2341             if ( wm->deps[i] )
2342                 MODULE_DecRefCount( wm->deps[i] );
2343
2344         wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
2345     }
2346 }
2347
2348 /******************************************************************
2349  *              LdrUnloadDll (NTDLL.@)
2350  *
2351  *
2352  */
2353 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
2354 {
2355     NTSTATUS retv = STATUS_SUCCESS;
2356
2357     TRACE("(%p)\n", hModule);
2358
2359     RtlEnterCriticalSection( &loader_section );
2360
2361     /* if we're stopping the whole process (and forcing the removal of all
2362      * DLLs) the library will be freed anyway
2363      */
2364     if (!process_detaching)
2365     {
2366         WINE_MODREF *wm;
2367
2368         free_lib_count++;
2369         if ((wm = get_modref( hModule )) != NULL)
2370         {
2371             TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
2372
2373             /* Recursively decrement reference counts */
2374             MODULE_DecRefCount( wm );
2375
2376             /* Call process detach notifications */
2377             if ( free_lib_count <= 1 )
2378             {
2379                 process_detach( FALSE, NULL );
2380                 MODULE_FlushModrefs();
2381             }
2382
2383             TRACE("END\n");
2384         }
2385         else
2386             retv = STATUS_DLL_NOT_FOUND;
2387
2388         free_lib_count--;
2389     }
2390
2391     RtlLeaveCriticalSection( &loader_section );
2392
2393     return retv;
2394 }
2395
2396 /***********************************************************************
2397  *           RtlImageNtHeader   (NTDLL.@)
2398  */
2399 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
2400 {
2401     IMAGE_NT_HEADERS *ret;
2402
2403     __TRY
2404     {
2405         IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
2406
2407         ret = NULL;
2408         if (dos->e_magic == IMAGE_DOS_SIGNATURE)
2409         {
2410             ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
2411             if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
2412         }
2413     }
2414     __EXCEPT_PAGE_FAULT
2415     {
2416         return NULL;
2417     }
2418     __ENDTRY
2419     return ret;
2420 }
2421
2422
2423 /***********************************************************************
2424  *           attach_process_dlls
2425  *
2426  * Initial attach to all the dlls loaded by the process.
2427  */
2428 static NTSTATUS attach_process_dlls( void *wm )
2429 {
2430     NTSTATUS status;
2431
2432     pthread_sigmask( SIG_UNBLOCK, &server_block_set, NULL );
2433
2434     RtlEnterCriticalSection( &loader_section );
2435     if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS)
2436     {
2437         if (last_failed_modref)
2438             ERR( "%s failed to initialize, aborting\n",
2439                  debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
2440         return status;
2441     }
2442     attach_implicitly_loaded_dlls( (LPVOID)1 );
2443     RtlLeaveCriticalSection( &loader_section );
2444     return status;
2445 }
2446
2447
2448 /***********************************************************************
2449  *           start_process
2450  */
2451 static void start_process( void *kernel_start )
2452 {
2453     call_thread_entry_point( kernel_start, NtCurrentTeb()->Peb );
2454 }
2455
2456 /******************************************************************
2457  *              LdrInitializeThunk (NTDLL.@)
2458  *
2459  */
2460 void WINAPI LdrInitializeThunk( void *kernel_start, ULONG_PTR unknown2,
2461                                 ULONG_PTR unknown3, ULONG_PTR unknown4 )
2462 {
2463     NTSTATUS status;
2464     WINE_MODREF *wm;
2465     LPCWSTR load_path;
2466     PEB *peb = NtCurrentTeb()->Peb;
2467     IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
2468
2469     if (main_exe_file) NtClose( main_exe_file );  /* at this point the main module is created */
2470
2471     /* allocate the modref for the main exe (if not already done) */
2472     wm = get_modref( peb->ImageBaseAddress );
2473     assert( wm );
2474     if (wm->ldr.Flags & LDR_IMAGE_IS_DLL)
2475     {
2476         ERR("%s is a dll, not an executable\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
2477         exit(1);
2478     }
2479
2480     peb->LoaderLock = &loader_section;
2481     peb->ProcessParameters->ImagePathName = wm->ldr.FullDllName;
2482     version_init( wm->ldr.FullDllName.Buffer );
2483
2484     /* the main exe needs to be the first in the load order list */
2485     RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
2486     InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
2487
2488     if ((status = virtual_alloc_thread_stack( NtCurrentTeb(), 0, 0 )) != STATUS_SUCCESS) goto error;
2489     if ((status = server_init_process_done()) != STATUS_SUCCESS) goto error;
2490
2491     actctx_init();
2492     load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
2493     if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
2494     if ((status = alloc_process_tls()) != STATUS_SUCCESS) goto error;
2495     if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto error;
2496
2497     status = wine_call_on_stack( attach_process_dlls, wm, NtCurrentTeb()->Tib.StackBase );
2498     if (status != STATUS_SUCCESS) goto error;
2499
2500     virtual_release_address_space( nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE );
2501     virtual_clear_thread_stack();
2502     wine_switch_to_stack( start_process, kernel_start, NtCurrentTeb()->Tib.StackBase );
2503
2504 error:
2505     ERR( "Main exe initialization for %s failed, status %x\n",
2506          debugstr_w(peb->ProcessParameters->ImagePathName.Buffer), status );
2507     NtTerminateProcess( GetCurrentProcess(), status );
2508 }
2509
2510
2511 /***********************************************************************
2512  *           RtlImageDirectoryEntryToData   (NTDLL.@)
2513  */
2514 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
2515 {
2516     const IMAGE_NT_HEADERS *nt;
2517     DWORD addr;
2518
2519     if ((ULONG_PTR)module & 1)  /* mapped as data file */
2520     {
2521         module = (HMODULE)((ULONG_PTR)module & ~1);
2522         image = FALSE;
2523     }
2524     if (!(nt = RtlImageNtHeader( module ))) return NULL;
2525     if (dir >= nt->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2526     if (!(addr = nt->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2527     *size = nt->OptionalHeader.DataDirectory[dir].Size;
2528     if (image || addr < nt->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2529
2530     /* not mapped as image, need to find the section containing the virtual address */
2531     return RtlImageRvaToVa( nt, module, addr, NULL );
2532 }
2533
2534
2535 /***********************************************************************
2536  *           RtlImageRvaToSection   (NTDLL.@)
2537  */
2538 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
2539                                                    HMODULE module, DWORD rva )
2540 {
2541     int i;
2542     const IMAGE_SECTION_HEADER *sec;
2543
2544     sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
2545                                         nt->FileHeader.SizeOfOptionalHeader);
2546     for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
2547     {
2548         if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2549             return (PIMAGE_SECTION_HEADER)sec;
2550     }
2551     return NULL;
2552 }
2553
2554
2555 /***********************************************************************
2556  *           RtlImageRvaToVa   (NTDLL.@)
2557  */
2558 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
2559                               DWORD rva, IMAGE_SECTION_HEADER **section )
2560 {
2561     IMAGE_SECTION_HEADER *sec;
2562
2563     if (section && *section)  /* try this section first */
2564     {
2565         sec = *section;
2566         if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2567             goto found;
2568     }
2569     if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
2570  found:
2571     if (section) *section = sec;
2572     return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
2573 }
2574
2575
2576 /***********************************************************************
2577  *           RtlPcToFileHeader   (NTDLL.@)
2578  */
2579 PVOID WINAPI RtlPcToFileHeader( PVOID pc, PVOID *address )
2580 {
2581     LDR_MODULE *module;
2582     PVOID ret = NULL;
2583
2584     RtlEnterCriticalSection( &loader_section );
2585     if (!LdrFindEntryForAddress( pc, &module )) ret = module->BaseAddress;
2586     RtlLeaveCriticalSection( &loader_section );
2587     *address = ret;
2588     return ret;
2589 }
2590
2591
2592 /***********************************************************************
2593  *           NtLoadDriver   (NTDLL.@)
2594  *           ZwLoadDriver   (NTDLL.@)
2595  */
2596 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
2597 {
2598     FIXME("(%p), stub!\n",DriverServiceName);
2599     return STATUS_NOT_IMPLEMENTED;
2600 }
2601
2602
2603 /***********************************************************************
2604  *           NtUnloadDriver   (NTDLL.@)
2605  *           ZwUnloadDriver   (NTDLL.@)
2606  */
2607 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
2608 {
2609     FIXME("(%p), stub!\n",DriverServiceName);
2610     return STATUS_NOT_IMPLEMENTED;
2611 }
2612
2613
2614 /******************************************************************
2615  *              DllMain   (NTDLL.@)
2616  */
2617 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
2618 {
2619     if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
2620     return TRUE;
2621 }
2622
2623
2624 /******************************************************************
2625  *              __wine_init_windows_dir   (NTDLL.@)
2626  *
2627  * Windows and system dir initialization once kernel32 has been loaded.
2628  */
2629 void CDECL __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
2630 {
2631     PLIST_ENTRY mark, entry;
2632     LPWSTR buffer, p;
2633
2634     RtlCreateUnicodeString( &windows_dir, windir );
2635     RtlCreateUnicodeString( &system_dir, sysdir );
2636     strcpyW( user_shared_data->NtSystemRoot, windir );
2637
2638     /* prepend the system dir to the name of the already created modules */
2639     mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2640     for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2641     {
2642         LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
2643
2644         assert( mod->Flags & LDR_WINE_INTERNAL );
2645
2646         buffer = RtlAllocateHeap( GetProcessHeap(), 0,
2647                                   system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
2648         if (!buffer) continue;
2649         strcpyW( buffer, system_dir.Buffer );
2650         p = buffer + strlenW( buffer );
2651         if (p > buffer && p[-1] != '\\') *p++ = '\\';
2652         strcpyW( p, mod->FullDllName.Buffer );
2653         RtlInitUnicodeString( &mod->FullDllName, buffer );
2654         RtlInitUnicodeString( &mod->BaseDllName, p );
2655     }
2656 }
2657
2658
2659 /***********************************************************************
2660  *           __wine_process_init
2661  */
2662 void __wine_process_init(void)
2663 {
2664     static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
2665
2666     WINE_MODREF *wm;
2667     NTSTATUS status;
2668     ANSI_STRING func_name;
2669     void (* DECLSPEC_NORETURN CDECL init_func)(void);
2670     extern mode_t FILE_umask;
2671
2672     main_exe_file = thread_init();
2673
2674     /* retrieve current umask */
2675     FILE_umask = umask(0777);
2676     umask( FILE_umask );
2677
2678     /* setup the load callback and create ntdll modref */
2679     wine_dll_set_callback( load_builtin_callback );
2680
2681     if ((status = load_builtin_dll( NULL, kernel32W, 0, 0, &wm )) != STATUS_SUCCESS)
2682     {
2683         MESSAGE( "wine: could not load kernel32.dll, status %x\n", status );
2684         exit(1);
2685     }
2686     RtlInitAnsiString( &func_name, "UnhandledExceptionFilter" );
2687     LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name, 0, (void **)&unhandled_exception_filter );
2688
2689     RtlInitAnsiString( &func_name, "__wine_kernel_init" );
2690     if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
2691                                           0, (void **)&init_func )) != STATUS_SUCCESS)
2692     {
2693         MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %x\n", status );
2694         exit(1);
2695     }
2696     init_func();
2697 }