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