kernel: Reimplemented the SMap/SUnmap functions in assembly.
[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             mod->LoadCount = -1;  /* we can't unload it anyway */
938             process_attach( CONTAINING_RECORD(mod, WINE_MODREF, ldr), reserved );
939             break;  /* restart the search from the start */
940         }
941         if (entry == mark) break;  /* nothing found */
942     }
943 }
944
945
946 /*************************************************************************
947  *              process_detach
948  *
949  * Send DLL process detach notifications.  See the comment about calling
950  * sequence at process_attach.  Unless the bForceDetach flag
951  * is set, only DLLs with zero refcount are notified.
952  */
953 static void process_detach( BOOL bForceDetach, LPVOID lpReserved )
954 {
955     PLIST_ENTRY mark, entry;
956     PLDR_MODULE mod;
957
958     RtlEnterCriticalSection( &loader_section );
959     if (bForceDetach) process_detaching = 1;
960     mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
961     do
962     {
963         for (entry = mark->Blink; entry != mark; entry = entry->Blink)
964         {
965             mod = CONTAINING_RECORD(entry, LDR_MODULE, 
966                                     InInitializationOrderModuleList);
967             /* Check whether to detach this DLL */
968             if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
969                 continue;
970             if ( mod->LoadCount && !bForceDetach )
971                 continue;
972
973             /* Call detach notification */
974             mod->Flags &= ~LDR_PROCESS_ATTACHED;
975             MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr), 
976                             DLL_PROCESS_DETACH, lpReserved );
977
978             /* Restart at head of WINE_MODREF list, as entries might have
979                been added and/or removed while performing the call ... */
980             break;
981         }
982     } while (entry != mark);
983
984     RtlLeaveCriticalSection( &loader_section );
985 }
986
987 /*************************************************************************
988  *              MODULE_DllThreadAttach
989  *
990  * Send DLL thread attach notifications. These are sent in the
991  * reverse sequence of process detach notification.
992  *
993  */
994 NTSTATUS MODULE_DllThreadAttach( LPVOID lpReserved )
995 {
996     PLIST_ENTRY mark, entry;
997     PLDR_MODULE mod;
998     NTSTATUS    status;
999
1000     /* don't do any attach calls if process is exiting */
1001     if (process_detaching) return STATUS_SUCCESS;
1002     /* FIXME: there is still a race here */
1003
1004     RtlEnterCriticalSection( &loader_section );
1005
1006     if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto done;
1007
1008     mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1009     for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1010     {
1011         mod = CONTAINING_RECORD(entry, LDR_MODULE, 
1012                                 InInitializationOrderModuleList);
1013         if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1014             continue;
1015         if ( mod->Flags & LDR_NO_DLL_CALLS )
1016             continue;
1017
1018         MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr),
1019                         DLL_THREAD_ATTACH, lpReserved );
1020     }
1021
1022 done:
1023     RtlLeaveCriticalSection( &loader_section );
1024     return status;
1025 }
1026
1027 /******************************************************************
1028  *              LdrDisableThreadCalloutsForDll (NTDLL.@)
1029  *
1030  */
1031 NTSTATUS WINAPI LdrDisableThreadCalloutsForDll(HMODULE hModule)
1032 {
1033     WINE_MODREF *wm;
1034     NTSTATUS    ret = STATUS_SUCCESS;
1035
1036     RtlEnterCriticalSection( &loader_section );
1037
1038     wm = get_modref( hModule );
1039     if (!wm || wm->ldr.TlsIndex != -1)
1040         ret = STATUS_DLL_NOT_FOUND;
1041     else
1042         wm->ldr.Flags |= LDR_NO_DLL_CALLS;
1043
1044     RtlLeaveCriticalSection( &loader_section );
1045
1046     return ret;
1047 }
1048
1049 /******************************************************************
1050  *              LdrFindEntryForAddress (NTDLL.@)
1051  *
1052  * The loader_section must be locked while calling this function
1053  */
1054 NTSTATUS WINAPI LdrFindEntryForAddress(const void* addr, PLDR_MODULE* pmod)
1055 {
1056     PLIST_ENTRY mark, entry;
1057     PLDR_MODULE mod;
1058
1059     mark = &NtCurrentTeb()->Peb->LdrData->InMemoryOrderModuleList;
1060     for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1061     {
1062         mod = CONTAINING_RECORD(entry, LDR_MODULE, InMemoryOrderModuleList);
1063         if ((const void *)mod->BaseAddress <= addr &&
1064             (const char *)addr < (char*)mod->BaseAddress + mod->SizeOfImage)
1065         {
1066             *pmod = mod;
1067             return STATUS_SUCCESS;
1068         }
1069         if ((const void *)mod->BaseAddress > addr) break;
1070     }
1071     return STATUS_NO_MORE_ENTRIES;
1072 }
1073
1074 /******************************************************************
1075  *              LdrLockLoaderLock  (NTDLL.@)
1076  *
1077  * Note: flags are not implemented.
1078  * Flag 0x01 is used to raise exceptions on errors.
1079  * Flag 0x02 is used to avoid waiting on the section (does RtlTryEnterCriticalSection instead).
1080  */
1081 NTSTATUS WINAPI LdrLockLoaderLock( ULONG flags, ULONG *result, ULONG *magic )
1082 {
1083     if (flags) FIXME( "flags %lx not supported\n", flags );
1084
1085     if (result) *result = 1;
1086     if (!magic) return STATUS_INVALID_PARAMETER_3;
1087     RtlEnterCriticalSection( &loader_section );
1088     *magic = GetCurrentThreadId();
1089     return STATUS_SUCCESS;
1090 }
1091
1092
1093 /******************************************************************
1094  *              LdrUnlockLoaderUnlock  (NTDLL.@)
1095  */
1096 NTSTATUS WINAPI LdrUnlockLoaderLock( ULONG flags, ULONG magic )
1097 {
1098     if (magic)
1099     {
1100         if (magic != GetCurrentThreadId()) return STATUS_INVALID_PARAMETER_2;
1101         RtlLeaveCriticalSection( &loader_section );
1102     }
1103     return STATUS_SUCCESS;
1104 }
1105
1106
1107 /******************************************************************
1108  *              LdrGetDllHandle (NTDLL.@)
1109  */
1110 NTSTATUS WINAPI LdrGetDllHandle(ULONG x, ULONG y, const UNICODE_STRING *name, HMODULE *base)
1111 {
1112     NTSTATUS status = STATUS_DLL_NOT_FOUND;
1113     WCHAR dllname[MAX_PATH+4], *p;
1114     UNICODE_STRING str;
1115     PLIST_ENTRY mark, entry;
1116     PLDR_MODULE mod;
1117
1118     if (x != 0 || y != 0)
1119         FIXME("Unknown behavior, please report\n");
1120
1121     /* Append .DLL to name if no extension present */
1122     if (!(p = strrchrW( name->Buffer, '.')) || strchrW( p, '/' ) || strchrW( p, '\\'))
1123     {
1124         if (name->Length >= MAX_PATH) return STATUS_NAME_TOO_LONG;
1125         strcpyW( dllname, name->Buffer );
1126         strcatW( dllname, dllW );
1127         RtlInitUnicodeString( &str, dllname );
1128         name = &str;
1129     }
1130
1131     RtlEnterCriticalSection( &loader_section );
1132
1133     if (cached_modref)
1134     {
1135         if (RtlEqualUnicodeString( name, &cached_modref->ldr.FullDllName, TRUE ) ||
1136             RtlEqualUnicodeString( name, &cached_modref->ldr.BaseDllName, TRUE ))
1137         {
1138             *base = cached_modref->ldr.BaseAddress;
1139             status = STATUS_SUCCESS;
1140             goto done;
1141         }
1142     }
1143
1144     mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1145     for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1146     {
1147         mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1148
1149         if (RtlEqualUnicodeString( name, &mod->FullDllName, TRUE ) ||
1150             RtlEqualUnicodeString( name, &mod->BaseDllName, TRUE ))
1151         {
1152             cached_modref = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1153             *base = mod->BaseAddress;
1154             status = STATUS_SUCCESS;
1155             break;
1156         }
1157     }
1158 done:
1159     RtlLeaveCriticalSection( &loader_section );
1160     TRACE("%lx %lx %s -> %p\n", x, y, debugstr_us(name), status ? NULL : *base);
1161     return status;
1162 }
1163
1164
1165 /******************************************************************
1166  *              LdrGetProcedureAddress  (NTDLL.@)
1167  */
1168 NTSTATUS WINAPI LdrGetProcedureAddress(HMODULE module, const ANSI_STRING *name,
1169                                        ULONG ord, PVOID *address)
1170 {
1171     IMAGE_EXPORT_DIRECTORY *exports;
1172     DWORD exp_size;
1173     NTSTATUS ret = STATUS_PROCEDURE_NOT_FOUND;
1174
1175     RtlEnterCriticalSection( &loader_section );
1176
1177     /* check if the module itself is invalid to return the proper error */
1178     if (!get_modref( module )) ret = STATUS_DLL_NOT_FOUND;
1179     else if ((exports = RtlImageDirectoryEntryToData( module, TRUE,
1180                                                       IMAGE_DIRECTORY_ENTRY_EXPORT, &exp_size )))
1181     {
1182         void *proc = name ? find_named_export( module, exports, exp_size, name->Buffer, -1 )
1183                           : find_ordinal_export( module, exports, exp_size, ord - exports->Base );
1184         if (proc)
1185         {
1186             *address = proc;
1187             ret = STATUS_SUCCESS;
1188         }
1189     }
1190
1191     RtlLeaveCriticalSection( &loader_section );
1192     return ret;
1193 }
1194
1195
1196 /***********************************************************************
1197  *           load_builtin_callback
1198  *
1199  * Load a library in memory; callback function for wine_dll_register
1200  */
1201 static void load_builtin_callback( void *module, const char *filename )
1202 {
1203     static const WCHAR emptyW[1];
1204     void *addr;
1205     IMAGE_NT_HEADERS *nt;
1206     WINE_MODREF *wm;
1207     WCHAR *fullname, *p;
1208     const WCHAR *load_path;
1209
1210     if (!module)
1211     {
1212         ERR("could not map image for %s\n", filename ? filename : "main exe" );
1213         return;
1214     }
1215     if (!(nt = RtlImageNtHeader( module )))
1216     {
1217         ERR( "bad module for %s\n", filename ? filename : "main exe" );
1218         builtin_load_info->status = STATUS_INVALID_IMAGE_FORMAT;
1219         return;
1220     }
1221     addr = module;
1222     NtAllocateVirtualMemory( NtCurrentProcess(), &addr, 0, &nt->OptionalHeader.SizeOfImage,
1223                              MEM_SYSTEM | MEM_IMAGE, PAGE_EXECUTE_WRITECOPY );
1224     if (!(nt->FileHeader.Characteristics & IMAGE_FILE_DLL))
1225     {
1226         /* if we already have an executable, ignore this one */
1227         if (!NtCurrentTeb()->Peb->ImageBaseAddress)
1228         {
1229             NtCurrentTeb()->Peb->ImageBaseAddress = module;
1230             return; /* don't create the modref here, will be done later on */
1231         }
1232     }
1233
1234     /* create the MODREF */
1235
1236     if (!(fullname = RtlAllocateHeap( GetProcessHeap(), 0,
1237                                       system_dir.MaximumLength + (strlen(filename) + 1) * sizeof(WCHAR) )))
1238     {
1239         ERR( "can't load %s\n", filename );
1240         builtin_load_info->status = STATUS_NO_MEMORY;
1241         return;
1242     }
1243     memcpy( fullname, system_dir.Buffer, system_dir.Length );
1244     p = fullname + system_dir.Length / sizeof(WCHAR);
1245     if (p > fullname && p[-1] != '\\') *p++ = '\\';
1246     ascii_to_unicode( p, filename, strlen(filename) + 1 );
1247
1248     wm = alloc_module( module, fullname );
1249     RtlFreeHeap( GetProcessHeap(), 0, fullname );
1250     if (!wm)
1251     {
1252         ERR( "can't load %s\n", filename );
1253         builtin_load_info->status = STATUS_NO_MEMORY;
1254         return;
1255     }
1256     wm->ldr.Flags |= LDR_WINE_INTERNAL;
1257
1258     /* fixup imports */
1259
1260     load_path = builtin_load_info->load_path;
1261     if (!load_path) load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1262     if (!load_path) load_path = emptyW;
1263     if (fixup_imports( wm, load_path ) != STATUS_SUCCESS)
1264     {
1265         /* the module has only be inserted in the load & memory order lists */
1266         RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1267         RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1268         /* FIXME: free the modref */
1269         builtin_load_info->status = STATUS_DLL_NOT_FOUND;
1270         return;
1271     }
1272     builtin_load_info->wm = wm;
1273     TRACE( "loaded %s %p %p\n", filename, wm, module );
1274
1275     /* send the DLL load event */
1276
1277     SERVER_START_REQ( load_dll )
1278     {
1279         req->handle     = 0;
1280         req->base       = module;
1281         req->size       = nt->OptionalHeader.SizeOfImage;
1282         req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1283         req->dbg_size   = nt->FileHeader.NumberOfSymbols;
1284         req->name       = &wm->ldr.FullDllName.Buffer;
1285         wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1286         wine_server_call( req );
1287     }
1288     SERVER_END_REQ;
1289
1290     /* setup relay debugging entry points */
1291     if (TRACE_ON(relay)) RELAY_SetupDLL( module );
1292 }
1293
1294
1295 /******************************************************************************
1296  *      load_native_dll  (internal)
1297  */
1298 static NTSTATUS load_native_dll( LPCWSTR load_path, LPCWSTR name, HANDLE file,
1299                                  DWORD flags, WINE_MODREF** pwm )
1300 {
1301     void *module;
1302     HANDLE mapping;
1303     OBJECT_ATTRIBUTES attr;
1304     LARGE_INTEGER size;
1305     IMAGE_NT_HEADERS *nt;
1306     SIZE_T len = 0;
1307     WINE_MODREF *wm;
1308     NTSTATUS status;
1309
1310     TRACE( "loading %s\n", debugstr_w(name) );
1311
1312     attr.Length                   = sizeof(attr);
1313     attr.RootDirectory            = 0;
1314     attr.ObjectName               = NULL;
1315     attr.Attributes               = 0;
1316     attr.SecurityDescriptor       = NULL;
1317     attr.SecurityQualityOfService = NULL;
1318     size.QuadPart = 0;
1319
1320     status = NtCreateSection( &mapping, STANDARD_RIGHTS_REQUIRED | SECTION_QUERY | SECTION_MAP_READ,
1321                               &attr, &size, 0, SEC_IMAGE, file );
1322     if (status != STATUS_SUCCESS) return status;
1323
1324     module = NULL;
1325     status = NtMapViewOfSection( mapping, NtCurrentProcess(),
1326                                  &module, 0, 0, &size, &len, ViewShare, 0, PAGE_READONLY );
1327     NtClose( mapping );
1328     if (status != STATUS_SUCCESS) return status;
1329
1330     /* create the MODREF */
1331
1332     if (!(wm = alloc_module( module, name ))) return STATUS_NO_MEMORY;
1333
1334     /* fixup imports */
1335
1336     if (!(flags & DONT_RESOLVE_DLL_REFERENCES))
1337     {
1338         if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS)
1339         {
1340             /* the module has only be inserted in the load & memory order lists */
1341             RemoveEntryList(&wm->ldr.InLoadOrderModuleList);
1342             RemoveEntryList(&wm->ldr.InMemoryOrderModuleList);
1343
1344             /* FIXME: there are several more dangling references
1345              * left. Including dlls loaded by this dll before the
1346              * failed one. Unrolling is rather difficult with the
1347              * current structure and we can leave them lying
1348              * around with no problems, so we don't care.
1349              * As these might reference our wm, we don't free it.
1350              */
1351             return status;
1352         }
1353     }
1354     else wm->ldr.Flags |= LDR_DONT_RESOLVE_REFS;
1355
1356     /* send DLL load event */
1357
1358     nt = RtlImageNtHeader( module );
1359
1360     /* don't keep the file open if the mapping is from removable media */
1361     if (!VIRTUAL_HasMapping( module )) file = 0;
1362
1363     SERVER_START_REQ( load_dll )
1364     {
1365         req->handle     = file;
1366         req->base       = module;
1367         req->size       = nt->OptionalHeader.SizeOfImage;
1368         req->dbg_offset = nt->FileHeader.PointerToSymbolTable;
1369         req->dbg_size   = nt->FileHeader.NumberOfSymbols;
1370         req->name       = &wm->ldr.FullDllName.Buffer;
1371         wine_server_add_data( req, wm->ldr.FullDllName.Buffer, wm->ldr.FullDllName.Length );
1372         wine_server_call( req );
1373     }
1374     SERVER_END_REQ;
1375
1376     if (TRACE_ON(snoop)) SNOOP_SetupDLL( module );
1377
1378     TRACE_(loaddll)( " Loaded module %s : native\n", debugstr_w(wm->ldr.FullDllName.Buffer) );
1379
1380     *pwm = wm;
1381     return STATUS_SUCCESS;
1382 }
1383
1384
1385 /***********************************************************************
1386  *           load_builtin_dll
1387  */
1388 static NTSTATUS load_builtin_dll( LPCWSTR load_path, LPCWSTR path, DWORD flags, WINE_MODREF** pwm )
1389 {
1390     char error[256], dllname[MAX_PATH];
1391     int file_exists;
1392     const WCHAR *name, *p;
1393     DWORD len, i;
1394     void *handle;
1395     struct builtin_load_info info, *prev_info;
1396
1397     /* Fix the name in case we have a full path and extension */
1398     name = path;
1399     if ((p = strrchrW( name, '\\' ))) name = p + 1;
1400     if ((p = strrchrW( name, '/' ))) name = p + 1;
1401
1402     /* we don't want to depend on the current codepage here */
1403     len = strlenW( name ) + 1;
1404     if (len >= sizeof(dllname)) return STATUS_NAME_TOO_LONG;
1405     for (i = 0; i < len; i++)
1406     {
1407         if (name[i] > 127) return STATUS_DLL_NOT_FOUND;
1408         dllname[i] = (char)name[i];
1409         if (dllname[i] >= 'A' && dllname[i] <= 'Z') dllname[i] += 'a' - 'A';
1410     }
1411
1412     /* load_library will modify info.status. Note also that load_library can be
1413      * called several times, if the .so file we're loading has dependencies.
1414      * info.status will gather all the errors we may get while loading all these
1415      * libraries
1416      */
1417     info.load_path = load_path;
1418     info.status    = STATUS_SUCCESS;
1419     info.wm        = NULL;
1420     prev_info = builtin_load_info;
1421     builtin_load_info = &info;
1422     handle = wine_dll_load( dllname, error, sizeof(error), &file_exists );
1423     builtin_load_info = prev_info;
1424
1425     if (!handle)
1426     {
1427         if (!file_exists)
1428         {
1429             /* The file does not exist -> WARN() */
1430             WARN("cannot open .so lib for builtin %s: %s\n", debugstr_w(name), error);
1431             return STATUS_DLL_NOT_FOUND;
1432         }
1433         /* ERR() for all other errors (missing functions, ...) */
1434         ERR("failed to load .so lib for builtin %s: %s\n", debugstr_w(name), error );
1435         return STATUS_PROCEDURE_NOT_FOUND;
1436     }
1437     if (info.status != STATUS_SUCCESS) return info.status;
1438
1439     if (!info.wm)
1440     {
1441         /* The constructor wasn't called, this means the .so is already
1442          * loaded under a different name. We can't support multiple names
1443          * for the same module, so return an error. */
1444         return STATUS_INVALID_IMAGE_FORMAT;
1445     }
1446
1447     TRACE_(loaddll)( "Loaded module %s : builtin\n", debugstr_w(info.wm->ldr.FullDllName.Buffer) );
1448
1449     info.wm->ldr.SectionHandle = handle;
1450     if (strcmpiW( info.wm->ldr.BaseDllName.Buffer, name ))
1451     {
1452         ERR( "loaded .so for %s but got %s instead - probably 16-bit dll\n",
1453              debugstr_w(name), debugstr_w(info.wm->ldr.BaseDllName.Buffer) );
1454         /* wine_dll_unload( handle );*/
1455         return STATUS_INVALID_IMAGE_FORMAT;
1456     }
1457     *pwm = info.wm;
1458     return STATUS_SUCCESS;
1459 }
1460
1461
1462 /***********************************************************************
1463  *      find_dll_file
1464  *
1465  * Find the file (or already loaded module) for a given dll name.
1466  */
1467 static NTSTATUS find_dll_file( const WCHAR *load_path, const WCHAR *libname,
1468                                WCHAR *filename, ULONG *size, WINE_MODREF **pwm, HANDLE *handle )
1469 {
1470     OBJECT_ATTRIBUTES attr;
1471     IO_STATUS_BLOCK io;
1472     UNICODE_STRING nt_name;
1473     WCHAR *file_part, *ext, *dllname;
1474     ULONG len;
1475
1476     /* first append .dll if needed */
1477
1478     dllname = NULL;
1479     if (!(ext = strrchrW( libname, '.')) || strchrW( ext, '/' ) || strchrW( ext, '\\'))
1480     {
1481         if (!(dllname = RtlAllocateHeap( GetProcessHeap(), 0,
1482                                          (strlenW(libname) * sizeof(WCHAR)) + sizeof(dllW) )))
1483             return STATUS_NO_MEMORY;
1484         strcpyW( dllname, libname );
1485         strcatW( dllname, dllW );
1486         libname = dllname;
1487     }
1488
1489     nt_name.Buffer = NULL;
1490     if (RtlDetermineDosPathNameType_U( libname ) == RELATIVE_PATH)
1491     {
1492         /* we need to search for it */
1493         len = RtlDosSearchPath_U( load_path, libname, NULL, *size, filename, &file_part );
1494         if (len)
1495         {
1496             if (len >= *size) goto overflow;
1497             if ((*pwm = find_fullname_module( filename )) != NULL) goto found;
1498
1499             /* check for already loaded module in a different path */
1500             if (!contains_path( libname ))
1501             {
1502                 if ((*pwm = find_basename_module( file_part )) != NULL) goto found;
1503             }
1504             if (!RtlDosPathNameToNtPathName_U( filename, &nt_name, NULL, NULL ))
1505             {
1506                 RtlFreeHeap( GetProcessHeap(), 0, dllname );
1507                 return STATUS_NO_MEMORY;
1508             }
1509             attr.Length = sizeof(attr);
1510             attr.RootDirectory = 0;
1511             attr.Attributes = OBJ_CASE_INSENSITIVE;
1512             attr.ObjectName = &nt_name;
1513             attr.SecurityDescriptor = NULL;
1514             attr.SecurityQualityOfService = NULL;
1515             if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1516             goto found;
1517         }
1518
1519         /* not found */
1520
1521         if (!contains_path( libname ))
1522         {
1523             /* if libname doesn't contain a path at all, we simply return the name as is,
1524              * to be loaded as builtin */
1525             len = strlenW(libname) * sizeof(WCHAR);
1526             if (len >= *size) goto overflow;
1527             strcpyW( filename, libname );
1528             *pwm = find_basename_module( filename );
1529             goto found;
1530         }
1531     }
1532
1533     /* absolute path name, or relative path name but not found above */
1534
1535     if (!RtlDosPathNameToNtPathName_U( libname, &nt_name, &file_part, NULL ))
1536     {
1537         RtlFreeHeap( GetProcessHeap(), 0, dllname );
1538         return STATUS_NO_MEMORY;
1539     }
1540     len = nt_name.Length - 4*sizeof(WCHAR);  /* for \??\ prefix */
1541     if (len >= *size) goto overflow;
1542     memcpy( filename, nt_name.Buffer + 4, len + sizeof(WCHAR) );
1543     if (!(*pwm = find_fullname_module( filename )))
1544     {
1545         attr.Length = sizeof(attr);
1546         attr.RootDirectory = 0;
1547         attr.Attributes = OBJ_CASE_INSENSITIVE;
1548         attr.ObjectName = &nt_name;
1549         attr.SecurityDescriptor = NULL;
1550         attr.SecurityQualityOfService = NULL;
1551         if (NtOpenFile( handle, GENERIC_READ, &attr, &io, FILE_SHARE_READ|FILE_SHARE_DELETE, 0 )) *handle = 0;
1552     }
1553 found:
1554     RtlFreeUnicodeString( &nt_name );
1555     RtlFreeHeap( GetProcessHeap(), 0, dllname );
1556     return STATUS_SUCCESS;
1557
1558 overflow:
1559     RtlFreeUnicodeString( &nt_name );
1560     RtlFreeHeap( GetProcessHeap(), 0, dllname );
1561     *size = len + sizeof(WCHAR);
1562     return STATUS_BUFFER_TOO_SMALL;
1563 }
1564
1565
1566 /***********************************************************************
1567  *      load_dll  (internal)
1568  *
1569  * Load a PE style module according to the load order.
1570  * The loader_section must be locked while calling this function.
1571  */
1572 static NTSTATUS load_dll( LPCWSTR load_path, LPCWSTR libname, DWORD flags, WINE_MODREF** pwm )
1573 {
1574     int i;
1575     enum loadorder_type loadorder[LOADORDER_NTYPES];
1576     WCHAR buffer[32];
1577     WCHAR *filename;
1578     ULONG size;
1579     const char *filetype = "";
1580     WINE_MODREF *main_exe;
1581     HANDLE handle = 0;
1582     NTSTATUS nts;
1583
1584     TRACE( "looking for %s in %s\n", debugstr_w(libname), debugstr_w(load_path) );
1585
1586     filename = buffer;
1587     size = sizeof(buffer);
1588     for (;;)
1589     {
1590         nts = find_dll_file( load_path, libname, filename, &size, pwm, &handle );
1591         if (nts == STATUS_SUCCESS) break;
1592         if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1593         if (nts != STATUS_BUFFER_TOO_SMALL) return nts;
1594         /* grow the buffer and retry */
1595         if (!(filename = RtlAllocateHeap( GetProcessHeap(), 0, size ))) return STATUS_NO_MEMORY;
1596     }
1597
1598     if (*pwm)  /* found already loaded module */
1599     {
1600         if ((*pwm)->ldr.LoadCount != -1) (*pwm)->ldr.LoadCount++;
1601
1602         if (((*pwm)->ldr.Flags & LDR_DONT_RESOLVE_REFS) &&
1603             !(flags & DONT_RESOLVE_DLL_REFERENCES))
1604         {
1605             (*pwm)->ldr.Flags &= ~LDR_DONT_RESOLVE_REFS;
1606             fixup_imports( *pwm, load_path );
1607         }
1608         TRACE("Found loaded module %s for %s at %p, count=%d\n",
1609               debugstr_w((*pwm)->ldr.FullDllName.Buffer), debugstr_w(libname),
1610               (*pwm)->ldr.BaseAddress, (*pwm)->ldr.LoadCount);
1611         if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1612         return STATUS_SUCCESS;
1613     }
1614
1615     main_exe = get_modref( NtCurrentTeb()->Peb->ImageBaseAddress );
1616     MODULE_GetLoadOrderW( loadorder, main_exe ? main_exe->ldr.BaseDllName.Buffer : NULL, filename );
1617
1618     nts = STATUS_DLL_NOT_FOUND;
1619     for (i = 0; i < LOADORDER_NTYPES; i++)
1620     {
1621         if (loadorder[i] == LOADORDER_INVALID) break;
1622
1623         switch (loadorder[i])
1624         {
1625         case LOADORDER_DLL:
1626             TRACE("Trying native dll %s\n", debugstr_w(filename));
1627             if (!handle) continue;  /* it cannot possibly be loaded */
1628             nts = load_native_dll( load_path, filename, handle, flags, pwm );
1629             filetype = "native";
1630             break;
1631         case LOADORDER_BI:
1632             TRACE("Trying built-in %s\n", debugstr_w(filename));
1633             nts = load_builtin_dll( load_path, filename, flags, pwm );
1634             filetype = "builtin";
1635             break;
1636         default:
1637             nts = STATUS_INTERNAL_ERROR;
1638             break;
1639         }
1640
1641         if (nts == STATUS_SUCCESS)
1642         {
1643             /* Initialize DLL just loaded */
1644             TRACE("Loaded module %s (%s) at %p\n",
1645                   debugstr_w(filename), filetype, (*pwm)->ldr.BaseAddress);
1646             /* Set the ldr.LoadCount here so that an attach failure will */
1647             /* decrement the dependencies through the MODULE_FreeLibrary call. */
1648             (*pwm)->ldr.LoadCount = 1;
1649             if (handle) NtClose( handle );
1650             if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1651             return nts;
1652         }
1653         if (nts != STATUS_DLL_NOT_FOUND) break;
1654     }
1655
1656     WARN("Failed to load module %s; status=%lx\n", debugstr_w(libname), nts);
1657     if (handle) NtClose( handle );
1658     if (filename != buffer) RtlFreeHeap( GetProcessHeap(), 0, filename );
1659     return nts;
1660 }
1661
1662 /******************************************************************
1663  *              LdrLoadDll (NTDLL.@)
1664  */
1665 NTSTATUS WINAPI LdrLoadDll(LPCWSTR path_name, DWORD flags,
1666                            const UNICODE_STRING *libname, HMODULE* hModule)
1667 {
1668     WINE_MODREF *wm;
1669     NTSTATUS nts;
1670
1671     RtlEnterCriticalSection( &loader_section );
1672
1673     if (!path_name) path_name = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1674     nts = load_dll( path_name, libname->Buffer, flags, &wm );
1675
1676     if (nts == STATUS_SUCCESS && !(wm->ldr.Flags & LDR_DONT_RESOLVE_REFS))
1677     {
1678         nts = process_attach( wm, NULL );
1679         if (nts != STATUS_SUCCESS)
1680         {
1681             LdrUnloadDll(wm->ldr.BaseAddress);
1682             wm = NULL;
1683         }
1684     }
1685     *hModule = (wm) ? wm->ldr.BaseAddress : NULL;
1686
1687     RtlLeaveCriticalSection( &loader_section );
1688     return nts;
1689 }
1690
1691 /******************************************************************
1692  *              LdrQueryProcessModuleInformation
1693  *
1694  */
1695 NTSTATUS WINAPI LdrQueryProcessModuleInformation(PSYSTEM_MODULE_INFORMATION smi, 
1696                                                  ULONG buf_size, ULONG* req_size)
1697 {
1698     SYSTEM_MODULE*      sm = &smi->Modules[0];
1699     ULONG               size = sizeof(ULONG);
1700     NTSTATUS            nts = STATUS_SUCCESS;
1701     ANSI_STRING         str;
1702     char*               ptr;
1703     PLIST_ENTRY         mark, entry;
1704     PLDR_MODULE         mod;
1705
1706     smi->ModulesCount = 0;
1707
1708     RtlEnterCriticalSection( &loader_section );
1709     mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
1710     for (entry = mark->Flink; entry != mark; entry = entry->Flink)
1711     {
1712         mod = CONTAINING_RECORD(entry, LDR_MODULE, InLoadOrderModuleList);
1713         size += sizeof(*sm);
1714         if (size <= buf_size)
1715         {
1716             sm->Reserved1 = 0; /* FIXME */
1717             sm->Reserved2 = 0; /* FIXME */
1718             sm->ImageBaseAddress = mod->BaseAddress;
1719             sm->ImageSize = mod->SizeOfImage;
1720             sm->Flags = mod->Flags;
1721             sm->Id = 0; /* FIXME */
1722             sm->Rank = 0; /* FIXME */
1723             sm->Unknown = 0; /* FIXME */
1724             str.Length = 0;
1725             str.MaximumLength = MAXIMUM_FILENAME_LENGTH;
1726             str.Buffer = (char*)sm->Name;
1727             RtlUnicodeStringToAnsiString(&str, &mod->FullDllName, FALSE);
1728             ptr = strrchr(str.Buffer, '\\');
1729             sm->NameOffset = (ptr != NULL) ? (ptr - str.Buffer + 1) : 0;
1730
1731             smi->ModulesCount++;
1732             sm++;
1733         }
1734         else nts = STATUS_INFO_LENGTH_MISMATCH;
1735     }
1736     RtlLeaveCriticalSection( &loader_section );
1737
1738     if (req_size) *req_size = size;
1739
1740     return nts;
1741 }
1742
1743 /******************************************************************
1744  *              LdrShutdownProcess (NTDLL.@)
1745  *
1746  */
1747 void WINAPI LdrShutdownProcess(void)
1748 {
1749     TRACE("()\n");
1750     process_detach( TRUE, (LPVOID)1 );
1751 }
1752
1753 /******************************************************************
1754  *              LdrShutdownThread (NTDLL.@)
1755  *
1756  */
1757 void WINAPI LdrShutdownThread(void)
1758 {
1759     PLIST_ENTRY mark, entry;
1760     PLDR_MODULE mod;
1761
1762     TRACE("()\n");
1763
1764     /* don't do any detach calls if process is exiting */
1765     if (process_detaching) return;
1766     /* FIXME: there is still a race here */
1767
1768     RtlEnterCriticalSection( &loader_section );
1769
1770     mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1771     for (entry = mark->Blink; entry != mark; entry = entry->Blink)
1772     {
1773         mod = CONTAINING_RECORD(entry, LDR_MODULE, 
1774                                 InInitializationOrderModuleList);
1775         if ( !(mod->Flags & LDR_PROCESS_ATTACHED) )
1776             continue;
1777         if ( mod->Flags & LDR_NO_DLL_CALLS )
1778             continue;
1779
1780         MODULE_InitDLL( CONTAINING_RECORD(mod, WINE_MODREF, ldr), 
1781                         DLL_THREAD_DETACH, NULL );
1782     }
1783
1784     RtlLeaveCriticalSection( &loader_section );
1785 }
1786
1787 /***********************************************************************
1788  *           MODULE_FlushModrefs
1789  *
1790  * Remove all unused modrefs and call the internal unloading routines
1791  * for the library type.
1792  *
1793  * The loader_section must be locked while calling this function.
1794  */
1795 static void MODULE_FlushModrefs(void)
1796 {
1797     PLIST_ENTRY mark, entry, prev;
1798     PLDR_MODULE mod;
1799     WINE_MODREF*wm;
1800
1801     mark = &NtCurrentTeb()->Peb->LdrData->InInitializationOrderModuleList;
1802     for (entry = mark->Blink; entry != mark; entry = prev)
1803     {
1804         mod = CONTAINING_RECORD(entry, LDR_MODULE, 
1805                                 InInitializationOrderModuleList);
1806         wm = CONTAINING_RECORD(mod, WINE_MODREF, ldr);
1807
1808         prev = entry->Blink;
1809         if (mod->LoadCount) continue;
1810
1811         RemoveEntryList(&mod->InLoadOrderModuleList);
1812         RemoveEntryList(&mod->InMemoryOrderModuleList);
1813         RemoveEntryList(&mod->InInitializationOrderModuleList);
1814
1815         TRACE(" unloading %s\n", debugstr_w(mod->FullDllName.Buffer));
1816         if (!TRACE_ON(module))
1817             TRACE_(loaddll)("Unloaded module %s : %s\n",
1818                             debugstr_w(mod->FullDllName.Buffer),
1819                             (wm->ldr.Flags & LDR_WINE_INTERNAL) ? "builtin" : "native" );
1820
1821         SERVER_START_REQ( unload_dll )
1822         {
1823             req->base = mod->BaseAddress;
1824             wine_server_call( req );
1825         }
1826         SERVER_END_REQ;
1827
1828         NtUnmapViewOfSection( NtCurrentProcess(), mod->BaseAddress );
1829         if (wm->ldr.Flags & LDR_WINE_INTERNAL) wine_dll_unload( wm->ldr.SectionHandle );
1830         if (cached_modref == wm) cached_modref = NULL;
1831         RtlFreeUnicodeString( &mod->FullDllName );
1832         RtlFreeHeap( GetProcessHeap(), 0, wm->deps );
1833         RtlFreeHeap( GetProcessHeap(), 0, wm );
1834     }
1835 }
1836
1837 /***********************************************************************
1838  *           MODULE_DecRefCount
1839  *
1840  * The loader_section must be locked while calling this function.
1841  */
1842 static void MODULE_DecRefCount( WINE_MODREF *wm )
1843 {
1844     int i;
1845
1846     if ( wm->ldr.Flags & LDR_UNLOAD_IN_PROGRESS )
1847         return;
1848
1849     if ( wm->ldr.LoadCount <= 0 )
1850         return;
1851
1852     --wm->ldr.LoadCount;
1853     TRACE("(%s) ldr.LoadCount: %d\n", debugstr_w(wm->ldr.BaseDllName.Buffer), wm->ldr.LoadCount );
1854
1855     if ( wm->ldr.LoadCount == 0 )
1856     {
1857         wm->ldr.Flags |= LDR_UNLOAD_IN_PROGRESS;
1858
1859         for ( i = 0; i < wm->nDeps; i++ )
1860             if ( wm->deps[i] )
1861                 MODULE_DecRefCount( wm->deps[i] );
1862
1863         wm->ldr.Flags &= ~LDR_UNLOAD_IN_PROGRESS;
1864     }
1865 }
1866
1867 /******************************************************************
1868  *              LdrUnloadDll (NTDLL.@)
1869  *
1870  *
1871  */
1872 NTSTATUS WINAPI LdrUnloadDll( HMODULE hModule )
1873 {
1874     NTSTATUS retv = STATUS_SUCCESS;
1875
1876     TRACE("(%p)\n", hModule);
1877
1878     RtlEnterCriticalSection( &loader_section );
1879
1880     /* if we're stopping the whole process (and forcing the removal of all
1881      * DLLs) the library will be freed anyway
1882      */
1883     if (!process_detaching)
1884     {
1885         WINE_MODREF *wm;
1886
1887         free_lib_count++;
1888         if ((wm = get_modref( hModule )) != NULL)
1889         {
1890             TRACE("(%s) - START\n", debugstr_w(wm->ldr.BaseDllName.Buffer));
1891
1892             /* Recursively decrement reference counts */
1893             MODULE_DecRefCount( wm );
1894
1895             /* Call process detach notifications */
1896             if ( free_lib_count <= 1 )
1897             {
1898                 process_detach( FALSE, NULL );
1899                 MODULE_FlushModrefs();
1900             }
1901
1902             TRACE("END\n");
1903         }
1904         else
1905             retv = STATUS_DLL_NOT_FOUND;
1906
1907         free_lib_count--;
1908     }
1909
1910     RtlLeaveCriticalSection( &loader_section );
1911
1912     return retv;
1913 }
1914
1915 /***********************************************************************
1916  *           RtlImageNtHeader   (NTDLL.@)
1917  */
1918 PIMAGE_NT_HEADERS WINAPI RtlImageNtHeader(HMODULE hModule)
1919 {
1920     IMAGE_NT_HEADERS *ret;
1921
1922     __TRY
1923     {
1924         IMAGE_DOS_HEADER *dos = (IMAGE_DOS_HEADER *)hModule;
1925
1926         ret = NULL;
1927         if (dos->e_magic == IMAGE_DOS_SIGNATURE)
1928         {
1929             ret = (IMAGE_NT_HEADERS *)((char *)dos + dos->e_lfanew);
1930             if (ret->Signature != IMAGE_NT_SIGNATURE) ret = NULL;
1931         }
1932     }
1933     __EXCEPT_PAGE_FAULT
1934     {
1935         return NULL;
1936     }
1937     __ENDTRY
1938     return ret;
1939 }
1940
1941
1942 /******************************************************************
1943  *              LdrInitializeThunk (NTDLL.@)
1944  *
1945  * FIXME: the arguments are not correct, main_file is a Wine invention.
1946  */
1947 void WINAPI LdrInitializeThunk( HANDLE main_file, ULONG unknown2, ULONG unknown3, ULONG unknown4 )
1948 {
1949     NTSTATUS status;
1950     WINE_MODREF *wm;
1951     LPCWSTR load_path;
1952     PEB *peb = NtCurrentTeb()->Peb;
1953     UNICODE_STRING *main_exe_name = &peb->ProcessParameters->ImagePathName;
1954     IMAGE_NT_HEADERS *nt = RtlImageNtHeader( peb->ImageBaseAddress );
1955
1956     version_init( main_exe_name->Buffer );
1957
1958     /* allocate the modref for the main exe */
1959     if (!(wm = alloc_module( peb->ImageBaseAddress, main_exe_name->Buffer )))
1960     {
1961         status = STATUS_NO_MEMORY;
1962         goto error;
1963     }
1964     wm->ldr.LoadCount = -1;  /* can't unload main exe */
1965
1966     /* the main exe needs to be the first in the load order list */
1967     RemoveEntryList( &wm->ldr.InLoadOrderModuleList );
1968     InsertHeadList( &peb->LdrData->InLoadOrderModuleList, &wm->ldr.InLoadOrderModuleList );
1969
1970     /* Install signal handlers; this cannot be done before, since we cannot
1971      * send exceptions to the debugger before the create process event that
1972      * is sent by REQ_INIT_PROCESS_DONE.
1973      * We do need the handlers in place by the time the request is over, so
1974      * we set them up here. If we segfault between here and the server call
1975      * something is very wrong... */
1976     if (!SIGNAL_Init()) exit(1);
1977
1978     /* Signal the parent process to continue */
1979     SERVER_START_REQ( init_process_done )
1980     {
1981         req->module      = peb->ImageBaseAddress;
1982         req->module_size = wm->ldr.SizeOfImage;
1983         req->entry       = (char *)peb->ImageBaseAddress + nt->OptionalHeader.AddressOfEntryPoint;
1984         /* API requires a double indirection */
1985         req->name        = &main_exe_name->Buffer;
1986         req->exe_file    = main_file;
1987         req->gui         = (nt->OptionalHeader.Subsystem != IMAGE_SUBSYSTEM_WINDOWS_CUI);
1988         wine_server_add_data( req, main_exe_name->Buffer, main_exe_name->Length );
1989         wine_server_call( req );
1990     }
1991     SERVER_END_REQ;
1992
1993     if (main_file) NtClose( main_file ); /* we no longer need it */
1994
1995     RtlEnterCriticalSection( &loader_section );
1996
1997     load_path = NtCurrentTeb()->Peb->ProcessParameters->DllPath.Buffer;
1998     if ((status = fixup_imports( wm, load_path )) != STATUS_SUCCESS) goto error;
1999     if ((status = alloc_process_tls()) != STATUS_SUCCESS) goto error;
2000     if ((status = alloc_thread_tls()) != STATUS_SUCCESS) goto error;
2001     if ((status = process_attach( wm, (LPVOID)1 )) != STATUS_SUCCESS)
2002     {
2003         if (last_failed_modref)
2004             ERR( "%s failed to initialize, aborting\n", debugstr_w(last_failed_modref->ldr.BaseDllName.Buffer) + 1 );
2005         goto error;
2006     }
2007     attach_implicitly_loaded_dlls( (LPVOID)1 );
2008
2009     RtlLeaveCriticalSection( &loader_section );
2010
2011     if (nt->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE) VIRTUAL_UseLargeAddressSpace();
2012     return;
2013
2014 error:
2015     ERR( "Main exe initialization for %s failed, status %lx\n", debugstr_w(main_exe_name->Buffer), status );
2016     exit(1);
2017 }
2018
2019
2020 /***********************************************************************
2021  *           RtlImageDirectoryEntryToData   (NTDLL.@)
2022  */
2023 PVOID WINAPI RtlImageDirectoryEntryToData( HMODULE module, BOOL image, WORD dir, ULONG *size )
2024 {
2025     const IMAGE_NT_HEADERS *nt;
2026     DWORD addr;
2027
2028     if ((ULONG_PTR)module & 1)  /* mapped as data file */
2029     {
2030         module = (HMODULE)((ULONG_PTR)module & ~1);
2031         image = FALSE;
2032     }
2033     if (!(nt = RtlImageNtHeader( module ))) return NULL;
2034     if (dir >= nt->OptionalHeader.NumberOfRvaAndSizes) return NULL;
2035     if (!(addr = nt->OptionalHeader.DataDirectory[dir].VirtualAddress)) return NULL;
2036     *size = nt->OptionalHeader.DataDirectory[dir].Size;
2037     if (image || addr < nt->OptionalHeader.SizeOfHeaders) return (char *)module + addr;
2038
2039     /* not mapped as image, need to find the section containing the virtual address */
2040     return RtlImageRvaToVa( nt, module, addr, NULL );
2041 }
2042
2043
2044 /***********************************************************************
2045  *           RtlImageRvaToSection   (NTDLL.@)
2046  */
2047 PIMAGE_SECTION_HEADER WINAPI RtlImageRvaToSection( const IMAGE_NT_HEADERS *nt,
2048                                                    HMODULE module, DWORD rva )
2049 {
2050     int i;
2051     const IMAGE_SECTION_HEADER *sec;
2052
2053     sec = (const IMAGE_SECTION_HEADER*)((const char*)&nt->OptionalHeader +
2054                                         nt->FileHeader.SizeOfOptionalHeader);
2055     for (i = 0; i < nt->FileHeader.NumberOfSections; i++, sec++)
2056     {
2057         if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2058             return (PIMAGE_SECTION_HEADER)sec;
2059     }
2060     return NULL;
2061 }
2062
2063
2064 /***********************************************************************
2065  *           RtlImageRvaToVa   (NTDLL.@)
2066  */
2067 PVOID WINAPI RtlImageRvaToVa( const IMAGE_NT_HEADERS *nt, HMODULE module,
2068                               DWORD rva, IMAGE_SECTION_HEADER **section )
2069 {
2070     IMAGE_SECTION_HEADER *sec;
2071
2072     if (section && *section)  /* try this section first */
2073     {
2074         sec = *section;
2075         if ((sec->VirtualAddress <= rva) && (sec->VirtualAddress + sec->SizeOfRawData > rva))
2076             goto found;
2077     }
2078     if (!(sec = RtlImageRvaToSection( nt, module, rva ))) return NULL;
2079  found:
2080     if (section) *section = sec;
2081     return (char *)module + sec->PointerToRawData + (rva - sec->VirtualAddress);
2082 }
2083
2084
2085 /***********************************************************************
2086  *           NtLoadDriver   (NTDLL.@)
2087  *           ZwLoadDriver   (NTDLL.@)
2088  */
2089 NTSTATUS WINAPI NtLoadDriver( const UNICODE_STRING *DriverServiceName )
2090 {
2091     FIXME("(%p), stub!\n",DriverServiceName);
2092     return STATUS_NOT_IMPLEMENTED;
2093 }
2094
2095
2096 /***********************************************************************
2097  *           NtUnloadDriver   (NTDLL.@)
2098  *           ZwUnloadDriver   (NTDLL.@)
2099  */
2100 NTSTATUS WINAPI NtUnloadDriver( const UNICODE_STRING *DriverServiceName )
2101 {
2102     FIXME("(%p), stub!\n",DriverServiceName);
2103     return STATUS_NOT_IMPLEMENTED;
2104 }
2105
2106
2107 /******************************************************************
2108  *              DllMain   (NTDLL.@)
2109  */
2110 BOOL WINAPI DllMain( HINSTANCE inst, DWORD reason, LPVOID reserved )
2111 {
2112     if (reason == DLL_PROCESS_ATTACH) LdrDisableThreadCalloutsForDll( inst );
2113     return TRUE;
2114 }
2115
2116
2117 /******************************************************************
2118  *              __wine_init_windows_dir   (NTDLL.@)
2119  *
2120  * Windows and system dir initialization once kernel32 has been loaded.
2121  */
2122 void __wine_init_windows_dir( const WCHAR *windir, const WCHAR *sysdir )
2123 {
2124     PLIST_ENTRY mark, entry;
2125     LPWSTR buffer, p;
2126
2127     RtlCreateUnicodeString( &system_dir, sysdir );
2128
2129     /* prepend the system dir to the name of the already created modules */
2130     mark = &NtCurrentTeb()->Peb->LdrData->InLoadOrderModuleList;
2131     for (entry = mark->Flink; entry != mark; entry = entry->Flink)
2132     {
2133         LDR_MODULE *mod = CONTAINING_RECORD( entry, LDR_MODULE, InLoadOrderModuleList );
2134
2135         assert( mod->Flags & LDR_WINE_INTERNAL );
2136
2137         buffer = RtlAllocateHeap( GetProcessHeap(), 0,
2138                                   system_dir.Length + mod->FullDllName.Length + 2*sizeof(WCHAR) );
2139         if (!buffer) continue;
2140         strcpyW( buffer, system_dir.Buffer );
2141         p = buffer + strlenW( buffer );
2142         if (p > buffer && p[-1] != '\\') *p++ = '\\';
2143         strcpyW( p, mod->FullDllName.Buffer );
2144         RtlInitUnicodeString( &mod->FullDllName, buffer );
2145         RtlInitUnicodeString( &mod->BaseDllName, p );
2146     }
2147 }
2148
2149
2150 /***********************************************************************
2151  *           __wine_process_init
2152  */
2153 void __wine_process_init( int argc, char *argv[] )
2154 {
2155     static const WCHAR kernel32W[] = {'k','e','r','n','e','l','3','2','.','d','l','l',0};
2156
2157     WINE_MODREF *wm;
2158     NTSTATUS status;
2159     ANSI_STRING func_name;
2160     void (* DECLSPEC_NORETURN init_func)();
2161     extern mode_t FILE_umask;
2162
2163     thread_init();
2164
2165     /* retrieve current umask */
2166     FILE_umask = umask(0777);
2167     umask( FILE_umask );
2168
2169     /* setup the load callback and create ntdll modref */
2170     wine_dll_set_callback( load_builtin_callback );
2171
2172     if ((status = load_builtin_dll( NULL, kernel32W, 0, &wm )) != STATUS_SUCCESS)
2173     {
2174         MESSAGE( "wine: could not load kernel32.dll, status %lx\n", status );
2175         exit(1);
2176     }
2177     RtlInitAnsiString( &func_name, "__wine_kernel_init" );
2178     if ((status = LdrGetProcedureAddress( wm->ldr.BaseAddress, &func_name,
2179                                           0, (void **)&init_func )) != STATUS_SUCCESS)
2180     {
2181         MESSAGE( "wine: could not find __wine_kernel_init in kernel32.dll, status %lx\n", status );
2182         exit(1);
2183     }
2184     init_func();
2185 }