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