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