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