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