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