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