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