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