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