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