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