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