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