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