Fixed some trace format strings (reported by Gerald Pfeifer).
[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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  */
21
22 #include "config.h"
23 #include "wine/port.h"
24
25 #include <assert.h>
26 #include <stdarg.h>
27
28 #define NONAMELESSUNION
29 #define NONAMELESSSTRUCT
30
31 #include "windef.h"
32 #include "winnt.h"
33 #include "winternl.h"
34
35 #include "module.h"
36 #include "wine/exception.h"
37 #include "excpt.h"
38 #include "wine/library.h"
39 #include "wine/unicode.h"
40 #include "wine/debug.h"
41 #include "wine/server.h"
42 #include "ntdll_misc.h"
43
44 WINE_DEFAULT_DEBUG_CHANNEL(module);
45 WINE_DECLARE_DEBUG_CHANNEL(relay);
46 WINE_DECLARE_DEBUG_CHANNEL(snoop);
47 WINE_DECLARE_DEBUG_CHANNEL(loaddll);
48 WINE_DECLARE_DEBUG_CHANNEL(imports);
49
50 typedef DWORD (CALLBACK *DLLENTRYPROC)(HMODULE,DWORD,LPVOID);
51
52 static int process_detaching = 0;  /* set on process detach to avoid deadlocks with thread detach */
53 static int free_lib_count;   /* recursion depth of LdrUnloadDll calls */
54
55 /* filter for page-fault exceptions */
56 static WINE_EXCEPTION_FILTER(page_fault)
57 {
58     if (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION)
59         return EXCEPTION_EXECUTE_HANDLER;
60     return EXCEPTION_CONTINUE_SEARCH;
61 }
62
63 static const char * const reason_names[] =
64 {
65     "PROCESS_DETACH",
66     "PROCESS_ATTACH",
67     "THREAD_ATTACH",
68     "THREAD_DETACH"
69 };
70
71 static const WCHAR dllW[] = {'.','d','l','l',0};
72
73 /* internal representation of 32bit modules. per process. */
74 typedef struct _wine_modref
75 {
76     LDR_MODULE            ldr;
77     int                   nDeps;
78     struct _wine_modref **deps;
79 } WINE_MODREF;
80
81 /* info about the current builtin dll load */
82 /* used to keep track of things across the register_dll constructor call */
83 struct builtin_load_info
84 {
85     const WCHAR *load_path;
86     NTSTATUS     status;
87     WINE_MODREF *wm;
88 };
89
90 static struct builtin_load_info default_load_info;
91 static struct builtin_load_info *builtin_load_info = &default_load_info;
92
93 static UINT tls_module_count;      /* number of modules with TLS directory */
94 static UINT tls_total_size;        /* total size of TLS storage */
95 static const IMAGE_TLS_DIRECTORY **tls_dirs;  /* array of TLS directories */
96
97 UNICODE_STRING system_dir = { 0, 0, NULL };  /* system directory */
98
99 static RTL_CRITICAL_SECTION loader_section;
100 static RTL_CRITICAL_SECTION_DEBUG critsect_debug =
101 {
102     0, 0, &loader_section,
103     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
104       0, 0, { (DWORD_PTR)(__FILE__ ": loader_section") }
105 };
106 static RTL_CRITICAL_SECTION loader_section = { &critsect_debug, -1, 0, 0, 0, 0 };
107
108 static WINE_MODREF *cached_modref;
109 static WINE_MODREF *current_modref;
110 static WINE_MODREF *last_failed_modref;
111
112 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm );
113 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
114                                   DWORD exp_size, const char *name, int hint );
115
116 /* convert PE image VirtualAddress to Real Address */
117 inline static void *get_rva( HMODULE module, DWORD va )
118 {
119     return (void *)((char *)module + va);
120 }
121
122 /* check whether the file name contains a path */
123 inline static int contains_path( LPCWSTR name )
124 {
125     return ((*name && (name[1] == ':')) || strchrW(name, '/') || strchrW(name, '\\'));
126 }
127
128 /* convert from straight ASCII to Unicode without depending on the current codepage */
129 inline static void ascii_to_unicode( WCHAR *dst, const char *src, size_t len )
130 {
131     while (len--) *dst++ = (unsigned char)*src++;
132 }
133
134
135 /*************************************************************************
136  *              call_dll_entry_point
137  *
138  * Some brain-damaged dlls (ir32_32.dll for instance) modify ebx in
139  * their entry point, so we need a small asm wrapper.
140  */
141 #ifdef __i386__
142 extern BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module, UINT reason, void *reserved );
143 __ASM_GLOBAL_FUNC(call_dll_entry_point,
144                   "pushl %ebp\n\t"
145                   "movl %esp,%ebp\n\t"
146                   "pushl %ebx\n\t"
147                   "pushl 20(%ebp)\n\t"
148                   "pushl 16(%ebp)\n\t"
149                   "pushl 12(%ebp)\n\t"
150                   "movl 8(%ebp),%eax\n\t"
151                   "call *%eax\n\t"
152                   "leal -4(%ebp),%esp\n\t"
153                   "popl %ebx\n\t"
154                   "popl %ebp\n\t"
155                   "ret" );
156 #else /* __i386__ */
157 static inline BOOL call_dll_entry_point( DLLENTRYPROC proc, void *module,
158                                          UINT reason, void *reserved )
159 {
160     return proc( module, reason, reserved );
161 }
162 #endif /* __i386__ */
163
164
165 #ifdef __i386__
166 /*************************************************************************
167  *              stub_entry_point
168  *
169  * Entry point for stub functions.
170  */
171 static void stub_entry_point( const char *dll, const char *name, ... )
172 {
173     EXCEPTION_RECORD rec;
174
175     rec.ExceptionCode           = EXCEPTION_WINE_STUB;
176     rec.ExceptionFlags          = EH_NONCONTINUABLE;
177     rec.ExceptionRecord         = NULL;
178 #ifdef __GNUC__
179     rec.ExceptionAddress        = __builtin_return_address(0);
180 #else
181     rec.ExceptionAddress        = *((void **)&dll - 1);
182 #endif
183     rec.NumberParameters        = 2;
184     rec.ExceptionInformation[0] = (ULONG_PTR)dll;
185     rec.ExceptionInformation[1] = (ULONG_PTR)name;
186     for (;;) RtlRaiseException( &rec );
187 }
188
189
190 #include "pshpack1.h"
191 struct stub
192 {
193     BYTE        popl_eax;   /* popl %eax */
194     BYTE        pushl1;     /* pushl $name */
195     const char *name;
196     BYTE        pushl2;     /* pushl $dll */
197     const char *dll;
198     BYTE        pushl_eax;  /* pushl %eax */
199     BYTE        jmp;        /* jmp stub_entry_point */
200     DWORD       entry;
201 };
202 #include "poppack.h"
203
204 /*************************************************************************
205  *              allocate_stub
206  *
207  * Allocate a stub entry point.
208  */
209 static ULONG_PTR allocate_stub( const char *dll, const char *name )
210 {
211 #define MAX_SIZE 65536
212     static struct stub *stubs;
213     static unsigned int nb_stubs;
214     struct stub *stub;
215
216     if (nb_stubs >= MAX_SIZE / sizeof(*stub)) return 0xdeadbeef;
217
218     if (!stubs)
219     {
220         ULONG size = MAX_SIZE;
221         if (NtAllocateVirtualMemory( NtCurrentProcess(), (void **)&stubs, 0, &size,
222                                      MEM_COMMIT, PAGE_EXECUTE_WRITECOPY ) != STATUS_SUCCESS)
223             return 0xdeadbeef;
224     }
225     stub = &stubs[nb_stubs++];
226     stub->popl_eax  = 0x58;  /* popl %eax */
227     stub->pushl1    = 0x68;  /* pushl $name */
228     stub->name      = name;
229     stub->pushl2    = 0x68;  /* pushl $dll */
230     stub->dll       = dll;
231     stub->pushl_eax = 0x50;  /* pushl %eax */
232     stub->jmp       = 0xe9;  /* jmp stub_entry_point */
233     stub->entry     = (BYTE *)stub_entry_point - (BYTE *)(&stub->entry + 1);
234     return (ULONG_PTR)stub;
235 }
236
237 #else  /* __i386__ */
238 static inline ULONG_PTR allocate_stub( const char *dll, const char *name ) { return 0xdeadbeef; }
239 #endif  /* __i386__ */
240
241
242 /*************************************************************************
243  *              get_modref
244  *
245  * Looks for the referenced HMODULE in the current process
246  * The loader_section must be locked while calling this function.
247  */
248 static WINE_MODREF *get_modref( HMODULE hmod )
249 {
250     PLIST_ENTRY mark, entry;
251     PLDR_MODULE mod;
252
253     if (cached_modref && cached_modref->ldr.BaseAddress == hmod) return cached_modref;
254
255     mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
256     for (entry = mark->Flink; entry != mark; entry = entry->Flink)
257     {
258         mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
259         if (mod->BaseAddress == hmod)
260             return cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
261         if (mod->BaseAddress > (void*)hmod) break;
262     }
263     return NULL;
264 }
265
266
267 /**********************************************************************
268  *          find_basename_module
269  *
270  * Find a module from its base name.
271  * The loader_section must be locked while calling this function
272  */
273 static WINE_MODREF *find_basename_module( LPCWSTR name )
274 {
275     PLIST_ENTRY mark, entry;
276
277     if (cached_modref && !strcmpiW( name, cached_modref->ldr.BaseDllName.Buffer ))
278         return cached_modref;
279
280     mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
281     for (entry = mark->Flink; entry != mark; entry = entry->Flink)
282     {
283         LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
284         if (!strcmpiW( name, mod->BaseDllName.Buffer ))
285         {
286             cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
287             return cached_modref;
288         }
289     }
290     return NULL;
291 }
292
293
294 /**********************************************************************
295  *          find_fullname_module
296  *
297  * Find a module from its full path name.
298  * The loader_section must be locked while calling this function
299  */
300 static WINE_MODREF *find_fullname_module( LPCWSTR name )
301 {
302     PLIST_ENTRY mark, entry;
303
304     if (cached_modref && !strcmpiW( name, cached_modref->ldr.FullDllName.Buffer ))
305         return cached_modref;
306
307     mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
308     for (entry = mark->Flink; entry != mark; entry = entry->Flink)
309     {
310         LDR_MODULE *mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
311         if (!strcmpiW( name, mod->FullDllName.Buffer ))
312         {
313             cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
314             return cached_modref;
315         }
316     }
317     return NULL;
318 }
319
320
321 /*************************************************************************
322  *              find_forwarded_export
323  *
324  * Find the final function pointer for a forwarded function.
325  * The loader_section must be locked while calling this function.
326  */
327 static FARPROC find_forwarded_export( HMODULE module, const char *forward )
328 {
329     const IMAGE_EXPORT_DIRECTORY *exports;
330     DWORD exp_size;
331     WINE_MODREF *wm;
332     WCHAR mod_name[32];
333     const char *end = strchr(forward, '.');
334     FARPROC proc = NULL;
335
336     if (!end) return NULL;
337     if ((end - forward) * sizeof(WCHAR) >= sizeof(mod_name) - sizeof(dllW)) return NULL;
338     ascii_to_unicode( mod_name, forward, end - forward );
339     memcpy( mod_name + (end - forward), dllW, sizeof(dllW) );
340
341     if (!(wm = find_basename_module( mod_name )))
342     {
343         ERR("module not found for forward '%s' used by %s\n",
344             forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer) );
345         return NULL;
346     }
347     if ((exports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
348                                                  IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
349         proc = find_named_export( wm->ldr.BaseAddress, exports, exp_size, end + 1, -1 );
350
351     if (!proc)
352     {
353         ERR("function not found for forward '%s' used by %s."
354             " If you are using builtin %s, try using the native one instead.\n",
355             forward, debugstr_w(get_modref(module)->ldr.FullDllName.Buffer),
356             debugstr_w(get_modref(module)->ldr.BaseDllName.Buffer) );
357     }
358     return proc;
359 }
360
361
362 /*************************************************************************
363  *              find_ordinal_export
364  *
365  * Find an exported function by ordinal.
366  * The exports base must have been subtracted from the ordinal already.
367  * The loader_section must be locked while calling this function.
368  */
369 static FARPROC find_ordinal_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
370                                     DWORD exp_size, int ordinal )
371 {
372     FARPROC proc;
373     const DWORD *functions = get_rva( module, exports->AddressOfFunctions );
374
375     if (ordinal >= exports->NumberOfFunctions)
376     {
377         TRACE(" ordinal %ld out of range!\n", ordinal + exports->Base );
378         return NULL;
379     }
380     if (!functions[ordinal]) return NULL;
381
382     proc = get_rva( module, functions[ordinal] );
383
384     /* if the address falls into the export dir, it's a forward */
385     if (((const char *)proc >= (const char *)exports) && 
386         ((const char *)proc < (const char *)exports + exp_size))
387         return find_forwarded_export( module, (const char *)proc );
388
389     if (TRACE_ON(snoop))
390     {
391         const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
392         proc = SNOOP_GetProcAddress( module, exports, exp_size, proc, ordinal, user );
393     }
394     if (TRACE_ON(relay))
395     {
396         const WCHAR *user = current_modref ? current_modref->ldr.BaseDllName.Buffer : NULL;
397         proc = RELAY_GetProcAddress( module, exports, exp_size, proc, user );
398     }
399     return proc;
400 }
401
402
403 /*************************************************************************
404  *              find_named_export
405  *
406  * Find an exported function by name.
407  * The loader_section must be locked while calling this function.
408  */
409 static FARPROC find_named_export( HMODULE module, const IMAGE_EXPORT_DIRECTORY *exports,
410                                   DWORD exp_size, const char *name, int hint )
411 {
412     const WORD *ordinals = get_rva( module, exports->AddressOfNameOrdinals );
413     const DWORD *names = get_rva( module, exports->AddressOfNames );
414     int min = 0, max = exports->NumberOfNames - 1;
415
416     /* first check the hint */
417     if (hint >= 0 && hint <= max)
418     {
419         char *ename = get_rva( module, names[hint] );
420         if (!strcmp( ename, name ))
421             return find_ordinal_export( module, exports, exp_size, ordinals[hint] );
422     }
423
424     /* then do a binary search */
425     while (min <= max)
426     {
427         int res, pos = (min + max) / 2;
428         char *ename = get_rva( module, names[pos] );
429         if (!(res = strcmp( ename, name )))
430             return find_ordinal_export( module, exports, exp_size, ordinals[pos] );
431         if (res > 0) max = pos - 1;
432         else min = pos + 1;
433     }
434     return NULL;
435
436 }
437
438
439 /*************************************************************************
440  *              import_dll
441  *
442  * Import the dll specified by the given import descriptor.
443  * The loader_section must be locked while calling this function.
444  */
445 static WINE_MODREF *import_dll( HMODULE module, const IMAGE_IMPORT_DESCRIPTOR *descr, LPCWSTR load_path )
446 {
447     NTSTATUS status;
448     WINE_MODREF *wmImp;
449     HMODULE imp_mod;
450     const IMAGE_EXPORT_DIRECTORY *exports;
451     DWORD exp_size;
452     const IMAGE_THUNK_DATA *import_list;
453     IMAGE_THUNK_DATA *thunk_list;
454     WCHAR buffer[32];
455     const char *name = get_rva( module, descr->Name );
456     DWORD len = strlen(name) + 1;
457     PVOID protect_base;
458     SIZE_T protect_size = 0;
459     DWORD protect_old;
460
461     thunk_list = get_rva( module, (DWORD)descr->FirstThunk );
462     if (descr->u.OriginalFirstThunk)
463         import_list = get_rva( module, (DWORD)descr->u.OriginalFirstThunk );
464     else
465         import_list = thunk_list;
466
467     if (len * sizeof(WCHAR) <= sizeof(buffer))
468     {
469         ascii_to_unicode( buffer, name, len );
470         status = load_dll( load_path, buffer, 0, &wmImp );
471     }
472     else  /* need to allocate a larger buffer */
473     {
474         WCHAR *ptr = RtlAllocateHeap( GetProcessHeap(), 0, len * sizeof(WCHAR) );
475         if (!ptr) return NULL;
476         ascii_to_unicode( ptr, name, len );
477         status = load_dll( load_path, ptr, 0, &wmImp );
478         RtlFreeHeap( GetProcessHeap(), 0, ptr );
479     }
480
481     if (status)
482     {
483         if (status == STATUS_DLL_NOT_FOUND)
484             ERR("Library %s (which is needed by %s) not found\n",
485                 name, debugstr_w(current_modref->ldr.FullDllName.Buffer));
486         else
487             ERR("Loading library %s (which is needed by %s) failed (error %lx).\n",
488                 name, debugstr_w(current_modref->ldr.FullDllName.Buffer), status);
489         return NULL;
490     }
491
492     /* unprotect the import address table since it can be located in
493      * readonly section */
494     while (import_list[protect_size].u1.Ordinal) protect_size++;
495     protect_base = thunk_list;
496     protect_size *= sizeof(*thunk_list);
497     NtProtectVirtualMemory( NtCurrentProcess(), &protect_base,
498                             &protect_size, PAGE_WRITECOPY, &protect_old );
499
500     imp_mod = wmImp->ldr.BaseAddress;
501     exports = RtlImageDirectoryEntryToData( imp_mod, TRUE, IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size );
502
503     if (!exports)
504     {
505         /* set all imported function to deadbeef */
506         while (import_list->u1.Ordinal)
507         {
508             if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
509             {
510                 int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
511                 WARN("No implementation for %s.%d", name, ordinal );
512                 thunk_list->u1.Function = allocate_stub( name, (const char *)ordinal );
513             }
514             else
515             {
516                 IMAGE_IMPORT_BY_NAME *pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
517                 WARN("No implementation for %s.%s", name, pe_name->Name );
518                 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
519             }
520             WARN(" imported from %s, allocating stub %p\n",
521                  debugstr_w(current_modref->ldr.FullDllName.Buffer),
522                  (void *)thunk_list->u1.Function );
523             import_list++;
524             thunk_list++;
525         }
526         goto done;
527     }
528
529     while (import_list->u1.Ordinal)
530     {
531         if (IMAGE_SNAP_BY_ORDINAL(import_list->u1.Ordinal))
532         {
533             int ordinal = IMAGE_ORDINAL(import_list->u1.Ordinal);
534
535             thunk_list->u1.Function = (ULONG_PTR)find_ordinal_export( imp_mod, exports, exp_size,
536                                                                       ordinal - exports->Base );
537             if (!thunk_list->u1.Function)
538             {
539                 thunk_list->u1.Function = allocate_stub( name, (const char *)ordinal );
540                 WARN("No implementation for %s.%d imported from %s, setting to %p\n",
541                      name, ordinal, debugstr_w(current_modref->ldr.FullDllName.Buffer),
542                      (void *)thunk_list->u1.Function );
543             }
544             TRACE_(imports)("--- Ordinal %s.%d = %p\n", name, ordinal, (void *)thunk_list->u1.Function );
545         }
546         else  /* import by name */
547         {
548             IMAGE_IMPORT_BY_NAME *pe_name;
549             pe_name = get_rva( module, (DWORD)import_list->u1.AddressOfData );
550             thunk_list->u1.Function = (ULONG_PTR)find_named_export( imp_mod, exports, exp_size,
551                                                                     (const char*)pe_name->Name, pe_name->Hint );
552             if (!thunk_list->u1.Function)
553             {
554                 thunk_list->u1.Function = allocate_stub( name, (const char*)pe_name->Name );
555                 WARN("No implementation for %s.%s imported from %s, setting to %p\n",
556                      name, pe_name->Name, debugstr_w(current_modref->ldr.FullDllName.Buffer),
557                      (void *)thunk_list->u1.Function );
558             }
559             TRACE_(imports)("--- %s %s.%d = %p\n",
560                             pe_name->Name, name, pe_name->Hint, (void *)thunk_list->u1.Function);
561         }
562         import_list++;
563         thunk_list++;
564     }
565
566 done:
567     /* restore old protection of the import address table */
568     NtProtectVirtualMemory( NtCurrentProcess(), &protect_base, &protect_size, protect_old, NULL );
569     return wmImp;
570 }
571
572
573 /****************************************************************
574  *       fixup_imports
575  *
576  * Fixup all imports of a given module.
577  * The loader_section must be locked while calling this function.
578  */
579 static NTSTATUS fixup_imports( WINE_MODREF *wm, LPCWSTR load_path )
580 {
581     int i, nb_imports;
582     const IMAGE_IMPORT_DESCRIPTOR *imports;
583     WINE_MODREF *prev;
584     DWORD size;
585     NTSTATUS status;
586
587     if (!(imports = RtlImageDirectoryEntryToData( wm->ldr.BaseAddress, TRUE,
588                                                   IMAGE_DIRECTORY_ENTRY_IMPORT, &size )))
589         return STATUS_SUCCESS;
590
591     nb_imports = size / sizeof(*imports);
592     for (i = 0; i < nb_imports; i++)
593     {
594         if (!imports[i].Name)
595         {
596             nb_imports = i;
597             break;
598         }
599     }
600     if (!nb_imports) return STATUS_SUCCESS;  /* no imports */
601
602     /* Allocate module dependency list */
603     wm->nDeps = nb_imports;
604     wm->deps  = RtlAllocateHeap( GetProcessHeap(), 0, nb_imports*sizeof(WINE_MODREF *) );
605
606     /* load the imported modules. They are automatically
607      * added to the modref list of the process.
608      */
609     prev = current_modref;
610     current_modref = wm;
611     status = STATUS_SUCCESS;
612     for (i = 0; i < nb_imports; i++)
613     {
614         if (!(wm->deps[i] = import_dll( wm->ldr.BaseAddress, &imports[i], load_path )))
615             status = STATUS_DLL_NOT_FOUND;
616     }
617     current_modref = prev;
618     return status;
619 }
620
621
622 /*************************************************************************
623  *              alloc_module
624  *
625  * Allocate a WINE_MODREF structure and add it to the process list
626  * The loader_section must be locked while calling this function.
627  */
628 static WINE_MODREF *alloc_module( HMODULE hModule, LPCWSTR filename )
629 {
630     WINE_MODREF *wm;
631     const WCHAR *p;
632     const IMAGE_NT_HEADERS *nt = RtlImageNtHeader(hModule);
633     PLIST_ENTRY entry, mark;
634
635     if (!(wm = RtlAllocateHeap( GetProcessHeap(), 0, sizeof(*wm) ))) return NULL;
636
637     wm->nDeps    = 0;
638     wm->deps     = NULL;
639
640     wm->ldr.BaseAddress   = hModule;
641     wm->ldr.EntryPoint    = NULL;
642     wm->ldr.SizeOfImage   = nt->OptionalHeader.SizeOfImage;
643     wm->ldr.Flags         = 0;
644     wm->ldr.LoadCount     = 0;
645     wm->ldr.TlsIndex      = -1;
646     wm->ldr.SectionHandle = NULL;
647     wm->ldr.CheckSum      = 0;
648     wm->ldr.TimeDateStamp = 0;
649
650     RtlCreateUnicodeString( &wm->ldr.FullDllName, filename );
651     if ((p = strrchrW( wm->ldr.FullDllName.Buffer, '\\' ))) p++;
652     else p = wm->ldr.FullDllName.Buffer;
653     RtlInitUnicodeString( &wm->ldr.BaseDllName, p );
654
655     if (nt->FileHeader.Characteristics & IMAGE_FILE_DLL)
656     {
657         wm->ldr.Flags |= LDR_IMAGE_IS_DLL;
658         if (nt->OptionalHeader.AddressOfEntryPoint)
659             wm->ldr.EntryPoint = (char *)hModule + nt->OptionalHeader.AddressOfEntryPoint;
660     }
661
662     InsertTailList(&NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList,
663                    &wm->ldr.InLoadOrderModuleList);
664
665     /* insert module in MemoryList, sorted in increasing base addresses */
666     mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
667     for (entry = mark->Flink; entry != mark; entry = entry->Flink)
668     {
669         if (CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList)->BaseAddress > wm->ldr.BaseAddress)
670             break;
671     }
672     entry->Blink->Flink = &wm->ldr.InMemoryOrderModuleList;
673     wm->ldr.InMemoryOrderModuleList.Blink = entry->Blink;
674     wm->ldr.InMemoryOrderModuleList.Flink = entry;
675     entry->Blink = &wm->ldr.InMemoryOrderModuleList;
676
677     /* wait until init is called for inserting into this list */
678     wm->ldr.InInitializationOrderModuleList.Flink = NULL;
679     wm->ldr.InInitializationOrderModuleList.Blink = NULL;
680     return wm;
681 }
682
683
684 /*************************************************************************
685  *              alloc_process_tls
686  *
687  * Allocate the process-wide structure for module TLS storage.
688  */
689 static NTSTATUS alloc_process_tls(void)
690 {
691     PLIST_ENTRY mark, entry;
692     PLDR_MODULE mod;
693     const IMAGE_TLS_DIRECTORY *dir;
694     ULONG size, i;
695
696     mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
697     for (entry = mark->Flink; entry != mark; entry = entry->Flink)
698     {
699         mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
700         if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
701                                                   IMAGE_DIRECTORY_ENTRY_TLS, &size )))
702             continue;
703         size = (dir->EndAddressOfRawData - dir->StartAddressOfRawData) + dir->SizeOfZeroFill;
704         if (!size) continue;
705         tls_total_size += size;
706         tls_module_count++;
707     }
708     if (!tls_module_count) return STATUS_SUCCESS;
709
710     TRACE( "count %u size %u\n", tls_module_count, tls_total_size );
711
712     tls_dirs = RtlAllocateHeap( GetProcessHeap(), 0, tls_module_count * sizeof(*tls_dirs) );
713     if (!tls_dirs) return STATUS_NO_MEMORY;
714
715     for (i = 0, entry = mark->Flink; entry != mark; entry = entry->Flink)
716     {
717         mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
718         if (!(dir = RtlImageDirectoryEntryToData( mod->BaseAddress, TRUE,
719                                                   IMAGE_DIRECTORY_ENTRY_TLS, &size )))
720             continue;
721         tls_dirs[i] = dir;
722         *(DWORD *)dir->AddressOfIndex = i;
723         mod->TlsIndex = i;
724         mod->LoadCount = -1;  /* can't unload it */
725         i++;
726     }
727     return STATUS_SUCCESS;
728 }
729
730
731 /*************************************************************************
732  *              alloc_thread_tls
733  *
734  * Allocate the per-thread structure for module TLS storage.
735  */
736 static NTSTATUS alloc_thread_tls(void)
737 {
738     void **pointers;
739     char *data;
740     UINT i;
741
742     if (!tls_module_count) return STATUS_SUCCESS;
743
744     if (!(pointers = RtlAllocateHeap( GetProcessHeap(), 0,
745                                       tls_module_count * sizeof(*pointers) )))
746         return STATUS_NO_MEMORY;
747
748     if (!(data = RtlAllocateHeap( GetProcessHeap(), 0, tls_total_size )))
749     {
750         RtlFreeHeap( GetProcessHeap(), 0, pointers );
751         return STATUS_NO_MEMORY;
752     }
753
754     for (i = 0; i < tls_module_count; i++)
755     {
756         const IMAGE_TLS_DIRECTORY *dir = tls_dirs[i];
757         ULONG size = dir->EndAddressOfRawData - dir->StartAddressOfRawData;
758
759         TRACE( "thread %04lx idx %d: %ld/%ld bytes from %p to %p\n",
760                GetCurrentThreadId(), i, size, dir->SizeOfZeroFill,
761                (void *)dir->StartAddressOfRawData, data );
762
763         pointers[i] = data;
764         memcpy( data, (void *)dir->StartAddressOfRawData, size );
765         data += size;
766         memset( data, 0, dir->SizeOfZeroFill );
767         data += dir->SizeOfZeroFill;
768     }
769     NtCurrentTeb()->ThreadLocalStoragePointer = pointers;
770     return STATUS_SUCCESS;
771 }
772
773
774 /*************************************************************************
775  *              call_tls_callbacks
776  */
777 static void call_tls_callbacks( HMODULE module, UINT reason )
778 {
779     const IMAGE_TLS_DIRECTORY *dir;
780     const PIMAGE_TLS_CALLBACK *callback;
781     ULONG dirsize;
782
783     dir = RtlImageDirectoryEntryToData( module, TRUE, IMAGE_DIRECTORY_ENTRY_TLS, &dirsize );
784     if (!dir || !dir->AddressOfCallBacks) return;
785
786     for (callback = (const PIMAGE_TLS_CALLBACK *)dir->AddressOfCallBacks; *callback; callback++)
787     {
788         if (TRACE_ON(relay))
789             DPRINTF("%04lx:Call TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
790                     GetCurrentThreadId(), *callback, module, reason_names[reason] );
791         (*callback)( module, reason, NULL );
792         if (TRACE_ON(relay))
793             DPRINTF("%04lx:Ret  TLS callback (proc=%p,module=%p,reason=%s,reserved=0)\n",
794                     GetCurrentThreadId(), *callback, module, reason_names[reason] );
795     }
796 }
797
798
799 /*************************************************************************
800  *              MODULE_InitDLL
801  */
802 static BOOL MODULE_InitDLL( WINE_MODREF *wm, UINT reason, LPVOID lpReserved )
803 {
804     WCHAR mod_name[32];
805     BOOL retv = TRUE;
806     DLLENTRYPROC entry = wm->ldr.EntryPoint;
807     void *module = wm->ldr.BaseAddress;
808
809     /* Skip calls for modules loaded with special load flags */
810
811     if (wm->ldr.Flags & LDR_DONT_RESOLVE_REFS) return TRUE;
812     if (wm->ldr.TlsIndex != -1) call_tls_callbacks( wm->ldr.BaseAddress, reason );
813     if (!entry) return TRUE;
814
815     if (TRACE_ON(relay))
816     {
817         size_t len = min( wm->ldr.BaseDllName.Length, sizeof(mod_name)-sizeof(WCHAR) );
818         memcpy( mod_name, wm->ldr.BaseDllName.Buffer, len );
819         mod_name[len / sizeof(WCHAR)] = 0;
820         DPRINTF("%04lx:Call PE DLL (proc=%p,module=%p %s,reason=%s,res=%p)\n",
821                 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
822                 reason_names[reason], lpReserved );
823     }
824     else TRACE("(%p %s,%s,%p) - CALL\n", module, debugstr_w(wm->ldr.BaseDllName.Buffer),
825                reason_names[reason], lpReserved );
826
827     retv = call_dll_entry_point( entry, module, reason, lpReserved );
828
829     /* The state of the module list may have changed due to the call
830        to the dll. We cannot assume that this module has not been
831        deleted.  */
832     if (TRACE_ON(relay))
833         DPRINTF("%04lx:Ret  PE DLL (proc=%p,module=%p %s,reason=%s,res=%p) retval=%x\n",
834                 GetCurrentThreadId(), entry, module, debugstr_w(mod_name),
835                 reason_names[reason], lpReserved, retv );
836     else TRACE("(%p,%s,%p) - RETURN %d\n", module, reason_names[reason], lpReserved, retv );
837
838     return retv;
839 }
840
841
842 /*************************************************************************
843  *              process_attach
844  *
845  * Send the process attach notification to all DLLs the given module
846  * depends on (recursively). This is somewhat complicated due to the fact that
847  *
848  * - we have to respect the module dependencies, i.e. modules implicitly
849  *   referenced by another module have to be initialized before the module
850  *   itself can be initialized
851  *
852  * - the initialization routine of a DLL can itself call LoadLibrary,
853  *   thereby introducing a whole new set of dependencies (even involving
854  *   the 'old' modules) at any time during the whole process
855  *
856  * (Note that this routine can be recursively entered not only directly
857  *  from itself, but also via LoadLibrary from one of the called initialization
858  *  routines.)
859  *
860  * Furthermore, we need to rearrange the main WINE_MODREF list to allow
861  * the process *detach* notifications to be sent in the correct order.
862  * This must not only take into account module dependencies, but also
863  * 'hidden' dependencies created by modules calling LoadLibrary in their
864  * attach notification routine.
865  *
866  * The strategy is rather simple: we move a WINE_MODREF to the head of the
867  * list after the attach notification has returned.  This implies that the
868  * detach notifications are called in the reverse of the sequence the attach
869  * notifications *returned*.
870  *
871  * The loader_section must be locked while calling this function.
872  */
873 static NTSTATUS process_attach( WINE_MODREF *wm, LPVOID lpReserved )
874 {
875     NTSTATUS status = STATUS_SUCCESS;
876     int i;
877
878     if (process_detaching) return status;
879
880     /* prevent infinite recursion in case of cyclical dependencies */
881     if (    ( wm->ldr.Flags & LDR_LOAD_IN_PROGRESS )
882          || ( wm->ldr.Flags & LDR_PROCESS_ATTACHED ) )
883         return status;
884
885     TRACE("(%s,%p) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
886
887     /* Tag current MODREF to prevent recursive loop */
888     wm->ldr.Flags |= LDR_LOAD_IN_PROGRESS;
889
890     /* Recursively attach all DLLs this one depends on */
891     for ( i = 0; i < wm->nDeps; i++ )
892     {
893         if (!wm->deps[i]) continue;
894         if ((status = process_attach( wm->deps[i], lpReserved )) != STATUS_SUCCESS) break;
895     }
896
897     /* Call DLL entry point */
898     if (status == STATUS_SUCCESS)
899     {
900         WINE_MODREF *prev = current_modref;
901         current_modref = wm;
902         if (MODULE_InitDLL( wm, DLL_PROCESS_ATTACH, lpReserved ))
903         {
904             wm->ldr.Flags |= LDR_PROCESS_ATTACHED;
905         }
906         else
907         {
908             /* point to the name so LdrInitializeThunk can print it */
909             last_failed_modref = wm;
910             WARN("Initialization of %s failed\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
911             status = STATUS_DLL_INIT_FAILED;
912         }
913         current_modref = prev;
914     }
915
916     if (!wm->ldr.InInitializationOrderModuleList.Flink)
917         InsertTailList(&NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList,
918                        &wm->ldr.InInitializationOrderModuleList);
919
920     /* Remove recursion flag */
921     wm->ldr.Flags &= ~LDR_LOAD_IN_PROGRESS;
922
923     TRACE("(%s,%p) - END\n", debugstr_w(wm->ldr.BaseDllName.Buffer), lpReserved );
924     return status;
925 }
926
927 /*************************************************************************
928  *              process_detach
929  *
930  * Send DLL process detach notifications.  See the comment about calling
931  * sequence at process_attach.  Unless the bForceDetach flag
932  * is set, only DLLs with zero refcount are notified.
933  */
934 static void process_detach( BOOL bForceDetach, LPVOID lpReserved )
935 {
936     PLIST_ENTRY mark, entry;
937     PLDR_MODULE mod;
938
939     RtlEnterCriticalSection( &loader_section );
940     if (bForceDetach) process_detaching = 1;
941     mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
942     do
943     {
944         for (entry = mark->Blink; entry != mark; entry = entry->Blink)
945         {
946             mod = CONTAINING_RECORD(entry, LDR_MODULE, 
947                                     InInitializationOrderModuleList);
948             /* Check whether to detach this DLL */
949             if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
950                 continue;
951             if ( mod->LoadCount && !bForceDetach )
952                 continue;
953
954             /* Call detach notification */
955             mod->Flags &= ~LDR_PROCESS_ATTACHED;
956             MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr), 
957                             DLL_PROCESS_DETACH, lpReserved );
958
959             /* Restart at head of WINE_MODREF list, as entries might have
960                been added and/or removed while performing the call ... */
961             break;
962         }
963     } while (entry != mark);
964
965     RtlLeaveCriticalSection( &loader_section );
966 }
967
968 /*************************************************************************
969  *              MODULE_DllThreadAttach
970  *
971  * Send DLL thread attach notifications. These are sent in the
972  * reverse sequence of process detach notification.
973  *
974  */
975 NTSTATUS MODULE_DllThreadAttach( LPVOID lpReserved )
976 {
977     PLIST_ENTRY mark, entry;
978     PLDR_MODULE mod;
979     NTSTATUS    status;
980
981     /* don't do any attach calls if process is exiting */
982     if (process_detaching) return STATUS_SUCCESS;
983     /* FIXME: there is still a race here */
984
985     RtlEnterCriticalSection( &loader_section );
986
987     if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto done;
988
989     mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
990     for (entry = mark->Flink; entry != mark; entry = entry->Flink)
991     {
992         mod = CONTAINING_RECORD(entry, LDR_MODULE, 
993                                 InInitializationOrderModuleList);
994         if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
995             continue;
996         if ( mod->Flags & LDR_NO_DLL_CALLS )
997             continue;
998
999         MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1000                         DLL_THREAD_ATTACH, lpReserved );
1001     }
1002
1003 done:
1004     RtlLeaveCriticalSection( &loader_section );
1005     return status;
1006 }
1007
1008 /******************************************************************
1009  *              LdrDisableThreadCalloutsForDll (NTDLL.@)
1010  *
1011  */
1012 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1013 {
1014     WINE_MODREF *wm;
1015     NTSTATUS    ret = STATUS_SUCCESS;
1016
1017     RtlEnterCriticalSection( &loader_section );
1018
1019     wm = get_modref( hModule );
1020     if (!wm || wm->ldr.TlsIndex != -1)
1021         ret = STATUS_DLL_NOT_FOUND;
1022     else
1023         wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1024
1025     RtlLeaveCriticalSection( &loader_section );
1026
1027     return ret;
1028 }
1029
1030 /******************************************************************
1031  *              LdrFindEntryForAddress (NTDLL.@)
1032  *
1033  * The loader_section must be locked while calling this function
1034  */
1035 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
1036 {
1037     PLIST_ENTRY mark, entry;
1038     PLDR_MODULE mod;
1039
1040     mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1041     for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1042     {
1043         mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
1044         if ((const void *)mod->BaseAddress <= addr &&
1045             (const char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
1046         {
1047             *pmod = mod;
1048             return STATUS_SUCCESS;
1049         }
1050         if ((const void *)mod->BaseAddress > addr) break;
1051     }
1052     return STATUS_NO_MORE_ENTRIES;
1053 }
1054
1055 /******************************************************************
1056  *              LdrLockLoaderLock  (NTDLL.@)
1057  *
1058  * Note: flags are not implemented.
1059  * Flag 0x01 is used to raise exceptions on errors.
1060  * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
1061  */
1062 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG *magic )
1063 {
1064     if (flags) FIXME( "flags %lx not supported\n", flags );
1065
1066     if (result) *result = 1;
1067     if (!magic) return STATUS_INVALID_PARAMETER_3;
1068     RtlEnterCriticalSection( &loader_section );
1069     *magic = GetCurrentThreadId();
1070     return STATUS_SUCCESS;
1071 }
1072
1073
1074 /******************************************************************
1075  *              LdrUnlockLoaderUnlock  (NTDLL.@)
1076  */
1077 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG magic )
1078 {
1079     if (magic)
1080     {
1081         if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1082         RtlLeaveCriticalSection( &loader_section );
1083     }
1084     return STATUS_SUCCESS;
1085 }
1086
1087
1088 /******************************************************************
1089  *              LdrGetDllHandle (NTDLL.@)
1090  */
1091 NTSTATUS WINAPI LdrGetDllHandle(ULONG x, ULONG y, const UNICODE_STRING *name, HMODULE *base)
1092 {
1093     NTSTATUS status = STATUS_DLL_NOT_FOUND;
1094     WCHAR dllname[MAX_PATH+4], *p;
1095     UNICODE_STRING str;
1096     PLIST_ENTRY mark, entry;
1097     PLDR_MODULE mod;
1098
1099     if (x != 0 || y != 0)
1100         FIXME("Unknown behavior, please report\n");
1101
1102     /* Append .DLL to name if no extension present */
1103     if (!(p = strrchrW( name->Buffer, '.')) || strchrW( p, '/' ) || strchrW( p, '\\'))
1104     {
1105         if (name->Length >= MAX_PATH) return STATUS_NAME_TOO_LONG;
1106         strcpyW( dllname, name->Buffer );
1107         strcatW( dllname, dllW );
1108         RtlInitUnicodeString( &str, dllname );
1109         name = &str;
1110     }
1111
1112     RtlEnterCriticalSection( &loader_section );
1113
1114     if (cached_modref)
1115     {
1116         if (RtlEqualUnicodeString( name, &cached_modref->ldr.FullDllName, TRUE ) ||
1117             RtlEqualUnicodeString( name, &cached_modref->ldr.BaseDllName, TRUE ))
1118         {
1119             *base = cached_modref->ldr.BaseAddress;
1120             status = STATUS_SUCCESS;
1121             goto done;
1122         }
1123     }
1124
1125     mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1126     for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1127     {
1128         mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1129
1130         if (RtlEqualUnicodeString( name, &mod->FullDllName, TRUE ) ||
1131             RtlEqualUnicodeString( name, &mod->BaseDllName, TRUE ))
1132         {
1133             cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1134             *base = mod->BaseAddress;
1135             status = STATUS_SUCCESS;
1136             break;
1137         }
1138     }
1139 done:
1140     RtlLeaveCriticalSection( &loader_section );
1141     TRACE("%lx %lx %s -> %p\n", x, y, debugstr_us(name), status ? NULL : *base);
1142     return status;
1143 }
1144
1145
1146 /******************************************************************
1147  *              LdrGetProcedureAddress  (NTDLL.@)
1148  */
1149 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1150                                        ULONG ord, PVOID *address)
1151 {
1152     IMAGE_EXPORT_DIRECTORY *exports;
1153     DWORD exp_size;
1154     NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1155
1156     RtlEnterCriticalSection( &loader_section );
1157
1158     if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1159                                                  IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1160     {
1161         void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1 )
1162                           : find_ordinal_export( module, exports, exp_size, ord - exports->Base );
1163         if (proc)
1164         {
1165             *address = proc;
1166             ret = STATUS_SUCCESS;
1167         }
1168     }
1169     else
1170     {
1171         /* check if the module itself is invalid to return the proper error */
1172         if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1173     }
1174
1175     RtlLeaveCriticalSection( &loader_section );
1176     return ret;
1177 }
1178
1179
1180 /***********************************************************************
1181  *           load_builtin_callback
1182  *
1183  * Load a library in memory; callback function for wine_dll_register
1184  */
1185 static void load_builtin_callback( void *module, const char *filename )
1186 {
1187     static const WCHAR emptyW[1];
1188     void *addr;
1189     IMAGE_NT_HEADERS *nt;
1190     WINE_MODREF *wm;
1191     WCHAR *fullname, *p;
1192     const WCHAR *load_path;
1193
1194     if (!module)
1195     {
1196         ERR("could not map image for %s\n", filename ? filename : "main exe" );
1197         return;
1198     }
1199     if (!(nt = RtlImageNtHeader( module )))
1200     {
1201         ERR( "bad module for %s\n", filename ? filename : "main exe" );
1202         builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1203         return;
1204     }
1205     addr = module;
1206     NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 0, &nt->OptionalHeader.SizeOfImage,
1207                              MEM_SYSTEM | MEM_IMAGE, PAGE_EXECUTE_WRITECOPY );
1208     if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL))
1209     {
1210         /* if we already have an executable, ignore this one */
1211         if (!NtCurrentTeb()->Peb->ImageBaseAddress)
1212         {
1213             NtCurrentTeb()->Peb->ImageBaseAddress = module;
1214             return; /* don't create the modref here, will be done later on */
1215         }
1216     }
1217
1218     /* create the MODREF */
1219
1220     if (!(fullname = RtlAllocateHeap( GetProcessHeap(), 0,
1221                                       system_dir.MaximumLength + (strlen(filename) + 1) * sizeof(WCHAR) )))
1222     {
1223         ERR( "can't load %s\n", filename );
1224         builtin_load_info->status = STATUS_NO_MEMORY;
1225         return;
1226     }
1227     memcpy( fullname, system_dir.Buffer, system_dir.Length );
1228     p = fullname + system_dir.Length / sizeof(WCHAR);
1229     if (p > fullname && p[-1] != '\\') *p++ = '\\';
1230     ascii_to_unicode( p, filename, strlen(filename) + 1 );
1231
1232     wm = alloc_module( module, fullname );
1233     RtlFreeHeap( GetProcessHeap(), 0, fullname );
1234     if (!wm)
1235     {
1236         ERR( "can't load %s\n", filename );
1237         builtin_load_info->status = STATUS_NO_MEMORY;
1238         return;
1239     }
1240     wm->ldr.Flags |= LDR_WINE_INTERNAL;
1241
1242     /* fixup imports */
1243
1244     load_path = builtin_load_info->load_path;
1245     if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1246     if (!load_path) load_path = emptyW;
1247     if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1248     {
1249         /* the module has only be inserted in the load & memory order lists */
1250         RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1251         RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1252         /* FIXME: free the modref */
1253         builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1254         return;
1255     }
1256     builtin_load_info->wm = wm;
1257     TRACE( "loaded %s %p %p\n", filename, wm, module );
1258
1259     /* send the DLL load event */
1260
1261     SERVER_START_REQ( load_dll )
1262     {
1263         req->handle     = 0;
1264         req->base       = module;
1265         req->size       = nt->OptionalHeader.SizeOfImage;
1266         req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1267         req->dbg_size   = nt->FileHeader.NumberOfSymbols;
1268         req->name       = &wm->ldr.FullDllName.Buffer;
1269         wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1270         wine_server_call( req );
1271     }
1272     SERVER_END_REQ;
1273
1274     /* setup relay debugging entry points */
1275     if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1276 }
1277
1278
1279 /******************************************************************************
1280  *      load_native_dll  (internal)
1281  */
1282 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1283                                  DWORD flags, WINE_MODREF** pwm )
1284 {
1285     void *module;
1286     HANDLE mapping;
1287     OBJECT_ATTRIBUTES attr;
1288     LARGE_INTEGER size;
1289     IMAGE_NT_HEADERS *nt;
1290     SIZE_T len = 0;
1291     WINE_MODREF *wm;
1292     NTSTATUS status;
1293
1294     TRACE( "loading %s\n", debugstr_w(name) );
1295
1296     attr.Length                   = sizeof(attr);
1297     attr.RootDirectory            = 0;
1298     attr.ObjectName               = NULL;
1299     attr.Attributes               = 0;
1300     attr.SecurityDescriptor       = NULL;
1301     attr.SecurityQualityOfService = NULL;
1302     size.QuadPart = 0;
1303
1304     status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1305                               &attr, &size, 0, SEC_IMAGE, file );
1306     if (status != STATUS_SUCCESS) return status;
1307
1308     module = NULL;
1309     status = NtMapViewOfSection( mapping, NtCurrentProcess(),
1310                                  &module, 0, 0, &size, &len, ViewShare, 0, PAGE_READONLY );
1311     NtClose( mapping );
1312     if (status != STATUS_SUCCESS) return status;
1313
1314     /* create the MODREF */
1315
1316     if (!(wm = alloc_module( module, name ))) return STATUS_NO_MEMORY;
1317
1318     /* fixup imports */
1319
1320     if (!(flags & DONT_RESOLVE_DLL_REFERENCES))
1321     {
1322         if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1323         {
1324             /* the module has only be inserted in the load & memory order lists */
1325             RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1326             RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1327
1328             /* FIXME: there are several more dangling references
1329              * left. Including dlls loaded by this dll before the
1330              * failed one. Unrolling is rather difficult with the
1331              * current structure and we can leave them lying
1332              * around with no problems, so we don't care.
1333              * As these might reference our wm, we don't free it.
1334              */
1335             return status;
1336         }
1337     }
1338     else wm->ldr.Flags |= LDR_DONT_RESOLVE_REFS;
1339
1340     /* send DLL load event */
1341
1342     nt = RtlImageNtHeader( module );
1343
1344     /* don't keep the file open if the mapping is from removable media */
1345     if (!VIRTUAL_HasMapping( module )) file = 0;
1346
1347     SERVER_START_REQ( load_dll )
1348     {
1349         req->handle     = file;
1350         req->base       = module;
1351         req->size       = nt->OptionalHeader.SizeOfImage;
1352         req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1353         req->dbg_size   = nt->FileHeader.NumberOfSymbols;
1354         req->name       = &wm->ldr.FullDllName.Buffer;
1355         wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1356         wine_server_call( req );
1357     }
1358     SERVER_END_REQ;
1359
1360     if (TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1361
1362     TRACE_(loaddll)( " Loaded module %s : native\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
1363
1364     *pwm = wm;
1365     return STATUS_SUCCESS;
1366 }
1367
1368
1369 /***********************************************************************
1370  *           load_builtin_dll
1371  */
1372 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, DWORD flags, WINE_MODREF** pwm )
1373 {
1374     char error[256], dllname[MAX_PATH];
1375     int file_exists;
1376     const WCHAR *name, *p;
1377     DWORD len, i;
1378     void *handle;
1379     struct builtin_load_info info, *prev_info;
1380
1381     /* Fix the name in case we have a full path and extension */
1382     name = path;
1383     if ((p = strrchrW( name, '\\' ))) name = p + 1;
1384     if ((p = strrchrW( name, '/' ))) name = p + 1;
1385
1386     /* we don't want to depend on the current codepage here */
1387     len = strlenW( name ) + 1;
1388     if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1389     for (i = 0; i < len; i++)
1390     {
1391         if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1392         dllname[i] = (char)name[i];
1393         if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1394     }
1395
1396     /* load_library will modify info.status. Note also that load_library can be
1397      * called several times, if the .so file we're loading has dependencies.
1398      * info.status will gather all the errors we may get while loading all these
1399      * libraries
1400      */
1401     info.load_path = load_path;
1402     info.status    = STATUS_SUCCESS;
1403     info.wm        = NULL;
1404     prev_info = builtin_load_info;
1405     builtin_load_info = &info;
1406     handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1407     builtin_load_info = prev_info;
1408
1409     if (!handle)
1410     {
1411         if (!file_exists)
1412         {
1413             /* The file does not exist -> WARN() */
1414             WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
1415             return STATUS_DLL_NOT_FOUND;
1416         }
1417         /* ERR() for all other errors (missing functions, ...) */
1418         ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
1419         return STATUS_PROCEDURE_NOT_FOUND;
1420     }
1421     if (info.status != STATUS_SUCCESS) return info.status;
1422
1423     if (!info.wm)
1424     {
1425         /* The constructor wasn't called, this means the .so is already
1426          * loaded under a different name. We can't support multiple names
1427          * for the same module, so return an error. */
1428         return STATUS_INVALID_IMAGE_FORMAT;
1429     }
1430
1431     TRACE_(loaddll)( "Loaded module %s : builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer) );
1432
1433     info.wm->ldr.SectionHandle = handle;
1434     if (strcmpiW( info.wm->ldr.BaseDllName.Buffer, name ))
1435     {
1436         ERR( "loaded .so for %s but got %s instead - probably 16-bit dll\n",
1437              debugstr_w(name), debugstr_w(info.wm->ldr.BaseDllName.Buffer) );
1438         /* wine_dll_unload( handle );*/
1439         return STATUS_INVALID_IMAGE_FORMAT;
1440     }
1441     *pwm = info.wm;
1442     return STATUS_SUCCESS;
1443 }
1444
1445
1446 /***********************************************************************
1447  *      find_dll_file
1448  *
1449  * Find the file (or already loaded module) for a given dll name.
1450  */
1451 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
1452                                WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
1453 {
1454     OBJECT_ATTRIBUTES attr;
1455     IO_STATUS_BLOCK io;
1456     UNICODE_STRING nt_name;
1457     WCHAR *file_part, *ext, *dllname;
1458     ULONG len;
1459
1460     /* first append .dll if needed */
1461
1462     dllname = NULL;
1463     if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
1464     {
1465         if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
1466                                          (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
1467             return STATUS_NO_MEMORY;
1468         strcpyW( dllname, libname );
1469         strcatW( dllname, dllW );
1470         libname = dllname;
1471     }
1472
1473     nt_name.Buffer = NULL;
1474     if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
1475     {
1476         /* we need to search for it */
1477         len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
1478         if (len)
1479         {
1480             if (len >= *size) goto overflow;
1481             if ((*pwm = find_fullname_module( filename )) != NULL) goto found;
1482
1483             /* check for already loaded module in a different path */
1484             if (!contains_path( libname ))
1485             {
1486                 if ((*pwm = find_basename_module( file_part )) != NULL) goto found;
1487             }
1488             if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
1489             {
1490                 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1491                 return STATUS_NO_MEMORY;
1492             }
1493             attr.Length = sizeof(attr);
1494             attr.RootDirectory = 0;
1495             attr.Attributes = OBJ_CASE_INSENSITIVE;
1496             attr.ObjectName = &nt_name;
1497             attr.SecurityDescriptor = NULL;
1498             attr.SecurityQualityOfService = NULL;
1499             if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1500             goto found;
1501         }
1502
1503         /* not found */
1504
1505         if (!contains_path( libname ))
1506         {
1507             /* if libname doesn't contain a path at all, we simply return the name as is,
1508              * to be loaded as builtin */
1509             len = strlenW(libname) * sizeof(WCHAR);
1510             if (len >= *size) goto overflow;
1511             strcpyW( filename, libname );
1512             *pwm = find_basename_module( filename );
1513             goto found;
1514         }
1515     }
1516
1517     /* absolute path name, or relative path name but not found above */
1518
1519     if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
1520     {
1521         RtlFreeHeap( GetProcessHeap(), 0, dllname );
1522         return STATUS_NO_MEMORY;
1523     }
1524     len = nt_name.Length - 4*sizeof(WCHAR);  /* for \??\ prefix */
1525     if (len >= *size) goto overflow;
1526     memcpy( filename, nt_name.Buffer + 4, len + sizeof(WCHAR) );
1527     if (!(*pwm = find_fullname_module( filename )))
1528     {
1529         attr.Length = sizeof(attr);
1530         attr.RootDirectory = 0;
1531         attr.Attributes = OBJ_CASE_INSENSITIVE;
1532         attr.ObjectName = &nt_name;
1533         attr.SecurityDescriptor = NULL;
1534         attr.SecurityQualityOfService = NULL;
1535         if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1536     }
1537 found:
1538     RtlFreeUnicodeString( &nt_name );
1539     RtlFreeHeap( GetProcessHeap(), 0, dllname );
1540     return STATUS_SUCCESS;
1541
1542 overflow:
1543     RtlFreeUnicodeString( &nt_name );
1544     RtlFreeHeap( GetProcessHeap(), 0, dllname );
1545     *size = len + sizeof(WCHAR);
1546     return STATUS_BUFFER_TOO_SMALL;
1547 }
1548
1549
1550 /***********************************************************************
1551  *      load_dll  (internal)
1552  *
1553  * Load a PE style module according to the load order.
1554  * The loader_section must be locked while calling this function.
1555  */
1556 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
1557 {
1558     int i;
1559     enum loadorder_type loadorder[LOADORDER_NTYPES];
1560     WCHAR buffer[32];
1561     WCHAR *filename;
1562     ULONG size;
1563     const char *filetype = "";
1564     WINE_MODREF *main_exe;
1565     HANDLE handle = 0;
1566     NTSTATUS nts;
1567
1568     TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
1569
1570     filename = buffer;
1571     size = sizeof(buffer);
1572     for (;;)
1573     {
1574         nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
1575         if (nts == STATUS_SUCCESS) break;
1576         if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1577         if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
1578         /* grow the buffer and retry */
1579         if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
1580     }
1581
1582     if (*pwm)  /* found already loaded module */
1583     {
1584         if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
1585
1586         if (((*pwm)->ldr.Flags & LDR_DONT_RESOLVE_REFS) &&
1587             !(flags & DONT_RESOLVE_DLL_REFERENCES))
1588         {
1589             (*pwm)->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
1590             fixup_imports( *pwm, load_path );
1591         }
1592         TRACE("Found loaded module %s for %s at %p, count=%d\n",
1593               debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
1594               (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
1595         if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1596         return STATUS_SUCCESS;
1597     }
1598
1599     main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
1600     MODULE_GetLoadOrderW( loadorder, main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
1601
1602     nts = STATUS_DLL_NOT_FOUND;
1603     for (i = 0; i < LOADORDER_NTYPES; i++)
1604     {
1605         if (loadorder[i] == LOADORDER_INVALID) break;
1606
1607         switch (loadorder[i])
1608         {
1609         case LOADORDER_DLL:
1610             TRACE("Trying native dll %s\n", debugstr_w(filename));
1611             if (!handle) continue;  /* it cannot possibly be loaded */
1612             nts = load_native_dll( load_path, filename, handle, flags, pwm );
1613             filetype = "native";
1614             break;
1615         case LOADORDER_BI:
1616             TRACE("Trying built-in %s\n", debugstr_w(filename));
1617             nts = load_builtin_dll( load_path, filename, flags, pwm );
1618             filetype = "builtin";
1619             break;
1620         default:
1621             nts = STATUS_INTERNAL_ERROR;
1622             break;
1623         }
1624
1625         if (nts == STATUS_SUCCESS)
1626         {
1627             /* Initialize DLL just loaded */
1628             TRACE("Loaded module %s (%s) at %p\n",
1629                   debugstr_w(filename), filetype, (*pwm)->ldr.BaseAddress);
1630             /* Set the ldr.LoadCount here so that an attach failure will */
1631             /* decrement the dependencies through the MODULE_FreeLibrary call. */
1632             (*pwm)->ldr.LoadCount = 1;
1633             if (handle) NtClose( handle );
1634             if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1635             return nts;
1636         }
1637         if (nts != STATUS_DLL_NOT_FOUND) break;
1638     }
1639
1640     WARN("Failed to load module %s; status=%lx\n", debugstr_w(libname), nts);
1641     if (handle) NtClose( handle );
1642     if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1643     return nts;
1644 }
1645
1646 /******************************************************************
1647  *              LdrLoadDll (NTDLL.@)
1648  */
1649 NTSTATUS WINAPI LdrLoadDll(LPCWSTR path_name, DWORD flags,
1650                            const UNICODE_STRING *libname, HMODULE* hModule)
1651 {
1652     WINE_MODREF *wm;
1653     NTSTATUS nts;
1654
1655     RtlEnterCriticalSection( &loader_section );
1656
1657     if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1658     nts = load_dll( path_name, libname->Buffer, flags, &wm );
1659
1660     if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
1661     {
1662         nts = process_attach( wm, NULL );
1663         if (nts != STATUS_SUCCESS)
1664         {
1665             LdrUnloadDll(wm->ldr.BaseAddress);
1666             wm = NULL;
1667         }
1668     }
1669     *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
1670
1671     RtlLeaveCriticalSection( &loader_section );
1672     return nts;
1673 }
1674
1675 /******************************************************************
1676  *              LdrQueryProcessModuleInformation
1677  *
1678  */
1679 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi, 
1680                                                  ULONG buf_size, ULONG* req_size)
1681 {
1682     SYSTEM_MODULE*      sm = &smi->Modules[0];
1683     ULONG               size = sizeof(ULONG);
1684     NTSTATUS            nts = STATUS_SUCCESS;
1685     ANSI_STRING         str;
1686     char*               ptr;
1687     PLIST_ENTRY         mark, entry;
1688     PLDR_MODULE         mod;
1689
1690     smi->ModulesCount = 0;
1691
1692     RtlEnterCriticalSection( &loader_section );
1693     mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1694     for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1695     {
1696         mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1697         size += sizeof(*sm);
1698         if (size <= buf_size)
1699         {
1700             sm->Reserved1 = 0; /* FIXME */
1701             sm->Reserved2 = 0; /* FIXME */
1702             sm->ImageBaseAddress = mod->BaseAddress;
1703             sm->ImageSize = mod->SizeOfImage;
1704             sm->Flags = mod->Flags;
1705             sm->Id = 0; /* FIXME */
1706             sm->Rank = 0; /* FIXME */
1707             sm->Unknown = 0; /* FIXME */
1708             str.Length = 0;
1709             str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
1710             str.Buffer = (char*)sm->Name;
1711             RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
1712             ptr = strrchr(str.Buffer, '\\');
1713             sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
1714
1715             smi->ModulesCount++;
1716             sm++;
1717         }
1718         else nts = STATUS_INFO_LENGTH_MISMATCH;
1719     }
1720     RtlLeaveCriticalSection( &loader_section );
1721
1722     if (req_size) *req_size = size;
1723
1724     return nts;
1725 }
1726
1727 /******************************************************************
1728  *              LdrShutdownProcess (NTDLL.@)
1729  *
1730  */
1731 void WINAPI LdrShutdownProcess(void)
1732 {
1733     TRACE("()\n");
1734     process_detach( TRUE, (LPVOID)1 );
1735 }
1736
1737 /******************************************************************
1738  *              LdrShutdownThread (NTDLL.@)
1739  *
1740  */
1741 void WINAPI LdrShutdownThread(void)
1742 {
1743     PLIST_ENTRY mark, entry;
1744     PLDR_MODULE mod;
1745
1746     TRACE("()\n");
1747
1748     /* don't do any detach calls if process is exiting */
1749     if (process_detaching) return;
1750     /* FIXME: there is still a race here */
1751
1752     RtlEnterCriticalSection( &loader_section );
1753
1754     mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1755     for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1756     {
1757         mod = CONTAINING_RECORD(entry, LDR_MODULE, 
1758                                 InInitializationOrderModuleList);
1759         if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1760             continue;
1761         if ( mod->Flags & LDR_NO_DLL_CALLS )
1762             continue;
1763
1764         MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr), 
1765                         DLL_THREAD_DETACH, NULL );
1766     }
1767
1768     RtlLeaveCriticalSection( &loader_section );
1769 }
1770
1771 /***********************************************************************
1772  *           MODULE_FlushModrefs
1773  *
1774  * Remove all unused modrefs and call the internal unloading routines
1775  * for the library type.
1776  *
1777  * The loader_section must be locked while calling this function.
1778  */
1779 static void MODULE_FlushModrefs(void)
1780 {
1781     PLIST_ENTRY mark, entry, prev;
1782     PLDR_MODULE mod;
1783     WINE_MODREF*wm;
1784
1785     mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1786     for (entry = mark->Blink; entry != mark; entry = prev)
1787     {
1788         mod = CONTAINING_RECORD(entry, LDR_MODULE, 
1789                                 InInitializationOrderModuleList);
1790         wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1791
1792         prev = entry->Blink;
1793         if (mod->LoadCount) continue;
1794
1795         RemoveEntryList(&mod->InLoadOrderModuleList);
1796         RemoveEntryList(&mod->InMemoryOrderModuleList);
1797         RemoveEntryList(&mod->InInitializationOrderModuleList);
1798
1799         TRACE(" unloading %s\n", debugstr_w(mod->FullDllName.Buffer));
1800         if (!TRACE_ON(module))
1801             TRACE_(loaddll)("Unloaded module %s : %s\n",
1802                             debugstr_w(mod->FullDllName.Buffer),
1803                             (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
1804
1805         SERVER_START_REQ( unload_dll )
1806         {
1807             req->base = mod->BaseAddress;
1808             wine_server_call( req );
1809         }
1810         SERVER_END_REQ;
1811
1812         NtUnmapViewOfSection( NtCurrentProcess(), mod->BaseAddress );
1813         if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
1814         if (cached_modref == wm) cached_modref = NULL;
1815         RtlFreeUnicodeString( &mod->FullDllName );
1816         RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
1817         RtlFreeHeap( GetProcessHeap(), 0, wm );
1818     }
1819 }
1820
1821 /***********************************************************************
1822  *           MODULE_DecRefCount
1823  *
1824  * The loader_section must be locked while calling this function.
1825  */
1826 static void MODULE_DecRefCount( WINE_MODREF *wm )
1827 {
1828     int i;
1829
1830     if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
1831         return;
1832
1833     if ( wm->ldr.LoadCount <= 0 )
1834         return;
1835
1836     --wm->ldr.LoadCount;
1837     TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
1838
1839     if ( wm->ldr.LoadCount == 0 )
1840     {
1841         wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
1842
1843         for ( i = 0; i < wm->nDeps; i++ )
1844             if ( wm->deps[i] )
1845                 MODULE_DecRefCount( wm->deps[i] );
1846
1847         wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
1848     }
1849 }
1850
1851 /******************************************************************
1852  *              LdrUnloadDll (NTDLL.@)
1853  *
1854  *
1855  */
1856 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
1857 {
1858     NTSTATUS retv = STATUS_SUCCESS;
1859
1860     TRACE("(%p)\n", hModule);
1861
1862     RtlEnterCriticalSection( &loader_section );
1863
1864     /* if we're stopping the whole process (and forcing the removal of all
1865      * DLLs) the library will be freed anyway
1866      */
1867     if (!process_detaching)
1868     {
1869         WINE_MODREF *wm;
1870
1871         free_lib_count++;
1872         if ((wm = get_modref( hModule )) != NULL)
1873         {
1874             TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
1875
1876             /* Recursively decrement reference counts */
1877             MODULE_DecRefCount( wm );
1878
1879             /* Call process detach notifications */
1880             if ( free_lib_count <= 1 )
1881             {
1882                 process_detach( FALSE, NULL );
1883                 MODULE_FlushModrefs();
1884             }
1885
1886             TRACE("END\n");
1887         }
1888         else
1889             retv = STATUS_DLL_NOT_FOUND;
1890
1891         free_lib_count--;
1892     }
1893
1894     RtlLeaveCriticalSection( &loader_section );
1895
1896     return retv;
1897 }
1898
1899 /***********************************************************************
1900  *           RtlImageNtHeader   (NTDLL.@)
1901  */
1902 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
1903 {
1904     IMAGE_NT_HEADERS *ret;
1905
1906     __TRY
1907     {
1908         IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
1909
1910         ret = NULL;
1911         if (dos->e_magic == IMAGE_DOS_SIGNATURE)
1912         {
1913             ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
1914             if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
1915         }
1916     }
1917     __EXCEPT(page_fault)
1918     {
1919         return NULL;
1920     }
1921     __ENDTRY
1922     return ret;
1923 }
1924
1925
1926 /******************************************************************
1927  *              LdrInitializeThunk (NTDLL.@)
1928  *
1929  * FIXME: the arguments are not correct, main_file is a Wine invention.
1930  */
1931 void WINAPI LdrInitializeThunk( HANDLE main_file, ULONG unknown2, ULONG unknown3, ULONG unknown4 )
1932 {
1933     NTSTATUS status;
1934     WINE_MODREF *wm;
1935     LPCWSTR load_path;
1936     PEB *peb = NtCurrentTeb()->Peb;
1937     UNICODE_STRING *main_exe_name = &peb->ProcessParameters->ImagePathName;
1938     IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
1939
1940     version_init( main_exe_name->Buffer );
1941
1942     /* allocate the modref for the main exe */
1943     if (!(wm = alloc_module( peb->ImageBaseAddress, main_exe_name->Buffer )))
1944     {
1945         status = STATUS_NO_MEMORY;
1946         goto error;
1947     }
1948     wm->ldr.LoadCount = -1;  /* can't unload main exe */
1949
1950     /* the main exe needs to be the first in the load order list */
1951     RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
1952     InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
1953
1954     /* Install signal handlers; this cannot be done before, since we cannot
1955      * send exceptions to the debugger before the create process event that
1956      * is sent by REQ_INIT_PROCESS_DONE.
1957      * We do need the handlers in place by the time the request is over, so
1958      * we set them up here. If we segfault between here and the server call
1959      * something is very wrong... */
1960     if (!SIGNAL_Init()) exit(1);
1961
1962     /* Signal the parent process to continue */
1963     SERVER_START_REQ( init_process_done )
1964     {
1965         req->module      = peb->ImageBaseAddress;
1966         req->module_size = wm->ldr.SizeOfImage;
1967         req->entry       = (char *)peb->ImageBaseAddress + nt->OptionalHeader.AddressOfEntryPoint;
1968         /* API requires a double indirection */
1969         req->name        = &main_exe_name->Buffer;
1970         req->exe_file    = main_file;
1971         req->gui         = (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_WINDOWS_CUI);
1972         wine_server_add_data( req, main_exe_name->Buffer, main_exe_name->Length );
1973         wine_server_call( req );
1974     }
1975     SERVER_END_REQ;
1976
1977     if (main_file) NtClose( main_file ); /* we no longer need it */
1978
1979     RtlEnterCriticalSection( &loader_section );
1980
1981     load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1982     if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
1983     if ((status = alloc_process_tls()) != STATUS_SUCCESS) goto error;
1984     if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto error;
1985     if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS)
1986     {
1987         if (last_failed_modref)
1988             ERR( "%s failed to initialize, aborting\n", debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
1989         goto error;
1990     }
1991
1992     RtlLeaveCriticalSection( &loader_section );
1993
1994     if (nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE) VIRTUAL_UseLargeAddressSpace();
1995     return;
1996
1997 error:
1998     ERR( "Main exe initialization for %s failed, status %lx\n", debugstr_w(main_exe_name->Buffer), status );
1999     exit(1);
2000 }
2001
2002
2003 /***********************************************************************
2004  *           RtlImageDirectoryEntryToData   (NTDLL.@)
2005  */
2006 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
2007 {
2008     const IMAGE_NT_HEADERS *nt;
2009     DWORD addr;
2010
2011     if ((ULONG_PTR)module & 1)  /* mapped as data file */
2012     {
2013         module = (HMODULE)((ULONG_PTR)module & ~1);
2014         image = FALSE;
2015     }
2016     if (!(nt = RtlImageNtHeader( module ))) return NULL;
2017     if (dir >= nt->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2018     if (!(addr = nt->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2019     *size = nt->OptionalHeader.DataDirectory[dir].Size;
2020     if (image || addr < nt->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2021
2022     /* not mapped as image, need to find the section containing the virtual address */
2023     return RtlImageRvaToVa( nt, module, addr, NULL );
2024 }
2025
2026
2027 /***********************************************************************
2028  *           RtlImageRvaToSection   (NTDLL.@)
2029  */
2030 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
2031                                                    HMODULE module, DWORD rva )
2032 {
2033     int i;
2034     const IMAGE_SECTION_HEADER *sec;
2035
2036     sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
2037                                         nt->FileHeader.SizeOfOptionalHeader);
2038     for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
2039     {
2040         if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2041             return (PIMAGE_SECTION_HEADER)sec;
2042     }
2043     return NULL;
2044 }
2045
2046
2047 /***********************************************************************
2048  *           RtlImageRvaToVa   (NTDLL.@)
2049  */
2050 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
2051                               DWORD rva, IMAGE_SECTION_HEADER **section )
2052 {
2053     IMAGE_SECTION_HEADER *sec;
2054
2055     if (section && *section)  /* try this section first */
2056     {
2057         sec = *section;
2058         if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2059             goto found;
2060     }
2061     if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
2062  found:
2063     if (section) *section = sec;
2064     return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
2065 }
2066
2067
2068 /***********************************************************************
2069  *           NtLoadDriver   (NTDLL.@)
2070  *           ZwLoadDriver   (NTDLL.@)
2071  */
2072 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
2073 {
2074     FIXME("(%p), stub!\n",DriverServiceName);
2075     return STATUS_NOT_IMPLEMENTED;
2076 }
2077
2078
2079 /***********************************************************************
2080  *           NtUnloadDriver   (NTDLL.@)
2081  *           ZwUnloadDriver   (NTDLL.@)
2082  */
2083 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
2084 {
2085     FIXME("(%p), stub!\n",DriverServiceName);
2086     return STATUS_NOT_IMPLEMENTED;
2087 }
2088
2089
2090 /******************************************************************
2091  *              DllMain   (NTDLL.@)
2092  */
2093 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
2094 {
2095     if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
2096     return TRUE;
2097 }
2098
2099
2100 /******************************************************************
2101  *              __wine_init_windows_dir   (NTDLL.@)
2102  *
2103  * Windows and system dir initialization once kernel32 has been loaded.
2104  */
2105 void __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
2106 {
2107     PLIST_ENTRY mark, entry;
2108     LPWSTR buffer, p;
2109
2110     RtlCreateUnicodeString( &system_dir, sysdir );
2111
2112     /* prepend the system dir to the name of the already created modules */
2113     mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2114     for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2115     {
2116         LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
2117
2118         assert( mod->Flags & LDR_WINE_INTERNAL );
2119
2120         buffer = RtlAllocateHeap( GetProcessHeap(), 0,
2121                                   system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
2122         if (!buffer) continue;
2123         strcpyW( buffer, system_dir.Buffer );
2124         p = buffer + strlenW( buffer );
2125         if (p > buffer && p[-1] != '\\') *p++ = '\\';
2126         strcpyW( p, mod->FullDllName.Buffer );
2127         RtlInitUnicodeString( &mod->FullDllName, buffer );
2128         RtlInitUnicodeString( &mod->BaseDllName, p );
2129     }
2130 }
2131
2132
2133 /***********************************************************************
2134  *           __wine_process_init
2135  */
2136 void __wine_process_init( int argc, char *argv[] )
2137 {
2138     static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
2139
2140     WINE_MODREF *wm;
2141     NTSTATUS status;
2142     ANSI_STRING func_name;
2143     void (* DECLSPEC_NORETURN init_func)();
2144     extern mode_t FILE_umask;
2145
2146     thread_init();
2147
2148     /* retrieve current umask */
2149     FILE_umask = umask(0777);
2150     umask( FILE_umask );
2151
2152     /* setup the load callback and create ntdll modref */
2153     wine_dll_set_callback( load_builtin_callback );
2154
2155     if ((status = load_builtin_dll( NULL, kernel32W, 0, &wm )) != STATUS_SUCCESS)
2156     {
2157         MESSAGE( "wine: could not load kernel32.dll, status %lx\n", status );
2158         exit(1);
2159     }
2160     RtlInitAnsiString( &func_name, "__wine_kernel_init" );
2161     if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
2162                                           0, (void **)&init_func )) != STATUS_SUCCESS)
2163     {
2164         MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %lx\n", status );
2165         exit(1);
2166     }
2167     init_func();
2168 }