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