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