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