Don't rely on the reserved area list being empty in reserve_area,
[wine] / libs / wine / loader.c
1 /*
2  * Win32 builtin dlls support
3  *
4  * Copyright 2000 Alexandre Julliard
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
19  */
20
21 #include "config.h"
22 #include "wine/port.h"
23
24 #include <assert.h>
25 #include <ctype.h>
26 #include <fcntl.h>
27 #include <stdarg.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <sys/types.h>
31 #ifdef HAVE_SYS_MMAN_H
32 #include <sys/mman.h>
33 #endif
34 #ifdef HAVE_UNISTD_H
35 # include <unistd.h>
36 #endif
37
38 #define NONAMELESSUNION
39 #define NONAMELESSSTRUCT
40 #include "windef.h"
41 #include "winbase.h"
42 #include "wine/library.h"
43
44 /* argc/argv for the Windows application */
45 int __wine_main_argc = 0;
46 char **__wine_main_argv = NULL;
47 WCHAR **__wine_main_wargv = NULL;
48 char **__wine_main_environ = NULL;
49
50 struct dll_path_context
51 {
52     int   index;
53     char *buffer;
54 };
55
56 #define MAX_DLLS 100
57
58 static struct
59 {
60     const IMAGE_NT_HEADERS *nt;           /* NT header */
61     const char             *filename;     /* DLL file name */
62 } builtin_dlls[MAX_DLLS];
63
64 static int nb_dlls;
65
66 static const IMAGE_NT_HEADERS *main_exe;
67
68 static load_dll_callback_t load_dll_callback;
69
70 static const char **dll_paths;
71 static int nb_dll_paths;
72 static int dll_path_maxlen;
73
74 extern void mmap_init(void);
75
76 /* build the dll load path from the WINEDLLPATH variable */
77 static void build_dll_path(void)
78 {
79     static const char * const dlldir = DLLDIR;
80     int len, count = 0;
81     char *p, *path = getenv( "WINEDLLPATH" );
82
83     if (path)
84     {
85         /* count how many path elements we need */
86         path = strdup(path);
87         p = path;
88         while (*p)
89         {
90             while (*p == ':') p++;
91             if (!*p) break;
92             count++;
93             while (*p && *p != ':') p++;
94         }
95     }
96
97     dll_paths = malloc( (count+1) * sizeof(*dll_paths) );
98
99     if (count)
100     {
101         p = path;
102         nb_dll_paths = 0;
103         while (*p)
104         {
105             while (*p == ':') *p++ = 0;
106             if (!*p) break;
107             dll_paths[nb_dll_paths] = p;
108             while (*p && *p != ':') p++;
109             if (p - dll_paths[nb_dll_paths] > dll_path_maxlen)
110                 dll_path_maxlen = p - dll_paths[nb_dll_paths];
111             nb_dll_paths++;
112         }
113     }
114
115     /* append default dll dir (if not empty) to path */
116     if ((len = strlen(dlldir)))
117     {
118         if (len > dll_path_maxlen) dll_path_maxlen = len;
119         dll_paths[nb_dll_paths++] = dlldir;
120     }
121 }
122
123 /* check if a given file can be opened */
124 inline static int file_exists( const char *name )
125 {
126     int fd = open( name, O_RDONLY );
127     if (fd != -1) close( fd );
128     return (fd != -1);
129 }
130
131
132 /* get a filename from the next entry in the dll path */
133 static char *next_dll_path( struct dll_path_context *context )
134 {
135     int index = context->index++;
136
137     if (index < nb_dll_paths)
138     {
139         int len = strlen( dll_paths[index] );
140         char *path = context->buffer + dll_path_maxlen - len;
141         memcpy( path, dll_paths[index], len );
142         return path;
143     }
144     return NULL;
145 }
146
147
148 /* get a filename from the first entry in the dll path */
149 static char *first_dll_path( const char *name, const char *ext, struct dll_path_context *context )
150 {
151     char *p;
152     int namelen = strlen( name );
153
154     context->buffer = p = malloc( dll_path_maxlen + namelen + strlen(ext) + 2 );
155     context->index = 0;
156
157     /* store the name at the end of the buffer, followed by extension */
158     p += dll_path_maxlen;
159     *p++ = '/';
160     memcpy( p, name, namelen );
161     strcpy( p + namelen, ext );
162     return next_dll_path( context );
163 }
164
165
166 /* free the dll path context created by first_dll_path */
167 inline static void free_dll_path( struct dll_path_context *context )
168 {
169     free( context->buffer );
170 }
171
172
173 /* open a library for a given dll, searching in the dll path
174  * 'name' must be the Windows dll name (e.g. "kernel32.dll") */
175 static void *dlopen_dll( const char *name, char *error, int errorsize,
176                          int test_only, int *exists )
177 {
178     struct dll_path_context context;
179     char *path;
180     void *ret = NULL;
181
182     *exists = 0;
183     for (path = first_dll_path( name, ".so", &context ); path; path = next_dll_path( &context ))
184     {
185         if (!test_only && (ret = wine_dlopen( path, RTLD_NOW, error, errorsize ))) break;
186         if ((*exists = file_exists( path ))) break; /* exists but cannot be loaded, return the error */
187     }
188     free_dll_path( &context );
189     return ret;
190 }
191
192
193 /* adjust an array of pointers to make them into RVAs */
194 static inline void fixup_rva_ptrs( void *array, void *base, int count )
195 {
196     void **ptr = (void **)array;
197     while (count--)
198     {
199         if (*ptr) *ptr = (void *)((char *)*ptr - (char *)base);
200         ptr++;
201     }
202 }
203
204
205 /* fixup RVAs in the import directory */
206 static void fixup_imports( IMAGE_IMPORT_DESCRIPTOR *dir, DWORD size, void *base )
207 {
208     int count = size / sizeof(void *);
209     void **ptr = (void **)dir;
210
211     /* everything is either a pointer or a ordinal value below 0x10000 */
212     while (count--)
213     {
214         if (*ptr >= (void *)0x10000) *ptr = (void *)((char *)*ptr - (char *)base);
215         else if (*ptr) *ptr = (void *)(0x80000000 | (unsigned int)*ptr);
216         ptr++;
217     }
218 }
219
220
221 /* fixup RVAs in the resource directory */
222 static void fixup_resources( IMAGE_RESOURCE_DIRECTORY *dir, char *root, void *base )
223 {
224     IMAGE_RESOURCE_DIRECTORY_ENTRY *entry;
225     int i;
226
227     entry = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(dir + 1);
228     for (i = 0; i < dir->NumberOfNamedEntries + dir->NumberOfIdEntries; i++, entry++)
229     {
230         void *ptr = root + entry->u2.s3.OffsetToDirectory;
231         if (entry->u2.s3.DataIsDirectory) fixup_resources( ptr, root, base );
232         else
233         {
234             IMAGE_RESOURCE_DATA_ENTRY *data = ptr;
235             fixup_rva_ptrs( &data->OffsetToData, base, 1 );
236         }
237     }
238 }
239
240
241 /* map a builtin dll in memory and fixup RVAs */
242 static void *map_dll( const IMAGE_NT_HEADERS *nt_descr )
243 {
244 #ifdef HAVE_MMAP
245     IMAGE_DATA_DIRECTORY *dir;
246     IMAGE_DOS_HEADER *dos;
247     IMAGE_NT_HEADERS *nt;
248     IMAGE_SECTION_HEADER *sec;
249     BYTE *addr;
250     DWORD code_start, data_start, data_end;
251     const size_t page_size = getpagesize();
252     const size_t page_mask = page_size - 1;
253     int nb_sections = 2;  /* code + data */
254
255     size_t size = (sizeof(IMAGE_DOS_HEADER)
256                    + sizeof(IMAGE_NT_HEADERS)
257                    + nb_sections * sizeof(IMAGE_SECTION_HEADER));
258
259     assert( size <= page_size );
260
261     /* module address must be aligned on 64K boundary */
262     addr = (BYTE *)((nt_descr->OptionalHeader.ImageBase + 0xffff) & ~0xffff);
263     if (wine_anon_mmap( addr, page_size, PROT_READ|PROT_WRITE, MAP_FIXED ) != addr) return NULL;
264
265     dos    = (IMAGE_DOS_HEADER *)addr;
266     nt     = (IMAGE_NT_HEADERS *)(dos + 1);
267     sec    = (IMAGE_SECTION_HEADER *)(nt + 1);
268
269     /* Build the DOS and NT headers */
270
271     dos->e_magic  = IMAGE_DOS_SIGNATURE;
272     dos->e_lfanew = sizeof(*dos);
273
274     *nt = *nt_descr;
275
276     code_start = page_size;
277     data_start = ((BYTE *)nt->OptionalHeader.BaseOfData - addr) & ~page_mask;
278     data_end   = (((BYTE *)nt->OptionalHeader.SizeOfImage - addr) + page_mask) & ~page_mask;
279
280     nt->FileHeader.NumberOfSections                = nb_sections;
281     nt->OptionalHeader.BaseOfCode                  = code_start;
282     nt->OptionalHeader.BaseOfData                  = data_start;
283     nt->OptionalHeader.SizeOfCode                  = data_start - code_start;
284     nt->OptionalHeader.SizeOfInitializedData       = data_end - data_start;
285     nt->OptionalHeader.SizeOfUninitializedData     = 0;
286     nt->OptionalHeader.SizeOfImage                 = data_end;
287     nt->OptionalHeader.ImageBase                   = (DWORD)addr;
288
289     fixup_rva_ptrs( &nt->OptionalHeader.AddressOfEntryPoint, addr, 1 );
290
291     /* Build the code section */
292
293     strcpy( sec->Name, ".text" );
294     sec->SizeOfRawData = data_start - code_start;
295     sec->Misc.VirtualSize = sec->SizeOfRawData;
296     sec->VirtualAddress   = code_start;
297     sec->PointerToRawData = code_start;
298     sec->Characteristics  = (IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ);
299     sec++;
300
301     /* Build the data section */
302
303     strcpy( sec->Name, ".data" );
304     sec->SizeOfRawData = data_end - data_start;
305     sec->Misc.VirtualSize = sec->SizeOfRawData;
306     sec->VirtualAddress   = data_start;
307     sec->PointerToRawData = data_start;
308     sec->Characteristics  = (IMAGE_SCN_CNT_INITIALIZED_DATA |
309                              IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_READ);
310     sec++;
311
312     /* Build the import directory */
313
314     dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_IMPORT_DIRECTORY];
315     if (dir->Size)
316     {
317         IMAGE_IMPORT_DESCRIPTOR *imports = (void *)dir->VirtualAddress;
318         fixup_rva_ptrs( &dir->VirtualAddress, addr, 1 );
319         fixup_imports( imports, dir->Size, addr );
320     }
321
322     /* Build the resource directory */
323
324     dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_RESOURCE_DIRECTORY];
325     if (dir->Size)
326     {
327         void *ptr = (void *)dir->VirtualAddress;
328         fixup_rva_ptrs( &dir->VirtualAddress, addr, 1 );
329         fixup_resources( ptr, ptr, addr );
330     }
331
332     /* Build the export directory */
333
334     dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_EXPORT_DIRECTORY];
335     if (dir->Size)
336     {
337         IMAGE_EXPORT_DIRECTORY *exports = (void *)dir->VirtualAddress;
338         fixup_rva_ptrs( &dir->VirtualAddress, addr, 1 );
339         fixup_rva_ptrs( (void *)exports->AddressOfFunctions, addr, exports->NumberOfFunctions );
340         fixup_rva_ptrs( (void *)exports->AddressOfNames, addr, exports->NumberOfNames );
341         fixup_rva_ptrs( &exports->Name, addr, 1 );
342         fixup_rva_ptrs( &exports->AddressOfFunctions, addr, 1 );
343         fixup_rva_ptrs( &exports->AddressOfNames, addr, 1 );
344         fixup_rva_ptrs( &exports->AddressOfNameOrdinals, addr, 1 );
345     }
346     return addr;
347 #else  /* HAVE_MMAP */
348     return NULL;
349 #endif  /* HAVE_MMAP */
350 }
351
352
353 /***********************************************************************
354  *           __wine_dll_register
355  *
356  * Register a built-in DLL descriptor.
357  */
358 void __wine_dll_register( const IMAGE_NT_HEADERS *header, const char *filename )
359 {
360     if (load_dll_callback) load_dll_callback( map_dll(header), filename );
361     else
362     {
363         if (!(header->FileHeader.Characteristics & IMAGE_FILE_DLL))
364             main_exe = header;
365         else
366         {
367             assert( nb_dlls < MAX_DLLS );
368             builtin_dlls[nb_dlls].nt = header;
369             builtin_dlls[nb_dlls].filename = filename;
370             nb_dlls++;
371         }
372     }
373 }
374
375
376 /***********************************************************************
377  *           wine_dll_set_callback
378  *
379  * Set the callback function for dll loading, and call it
380  * for all dlls that were implicitly loaded already.
381  */
382 void wine_dll_set_callback( load_dll_callback_t load )
383 {
384     int i;
385     load_dll_callback = load;
386     for (i = 0; i < nb_dlls; i++)
387     {
388         const IMAGE_NT_HEADERS *nt = builtin_dlls[i].nt;
389         if (!nt) continue;
390         builtin_dlls[i].nt = NULL;
391         load_dll_callback( map_dll(nt), builtin_dlls[i].filename );
392     }
393     nb_dlls = 0;
394     if (main_exe) load_dll_callback( map_dll(main_exe), "" );
395 }
396
397
398 /***********************************************************************
399  *           wine_dll_load
400  *
401  * Load a builtin dll.
402  */
403 void *wine_dll_load( const char *filename, char *error, int errorsize, int *file_exists )
404 {
405     int i;
406
407     /* callback must have been set already */
408     assert( load_dll_callback );
409
410     /* check if we have it in the list */
411     /* this can happen when initializing pre-loaded dlls in wine_dll_set_callback */
412     for (i = 0; i < nb_dlls; i++)
413     {
414         if (!builtin_dlls[i].nt) continue;
415         if (!strcmp( builtin_dlls[i].filename, filename ))
416         {
417             const IMAGE_NT_HEADERS *nt = builtin_dlls[i].nt;
418             builtin_dlls[i].nt = NULL;
419             load_dll_callback( map_dll(nt), builtin_dlls[i].filename );
420             *file_exists = 1;
421             return (void *)1;
422         }
423     }
424     return dlopen_dll( filename, error, errorsize, 0, file_exists );
425 }
426
427
428 /***********************************************************************
429  *           wine_dll_unload
430  *
431  * Unload a builtin dll.
432  */
433 void wine_dll_unload( void *handle )
434 {
435     if (handle != (void *)1)
436         wine_dlclose( handle, NULL, 0 );
437 }
438
439
440 /***********************************************************************
441  *           wine_dll_load_main_exe
442  *
443  * Try to load the .so for the main exe.
444  */
445 void *wine_dll_load_main_exe( const char *name, char *error, int errorsize,
446                               int test_only, int *file_exists )
447 {
448     return dlopen_dll( name, error, errorsize, test_only, file_exists );
449 }
450
451
452 /***********************************************************************
453  *           wine_dll_get_owner
454  *
455  * Retrieve the name of the 32-bit owner dll for a 16-bit dll.
456  * Return 0 if OK, -1 on error.
457  */
458 int wine_dll_get_owner( const char *name, char *buffer, int size, int *exists )
459 {
460     int ret = -1;
461     char *path;
462     struct dll_path_context context;
463
464     *exists = 0;
465     for (path = first_dll_path( name, ".so", &context ); path; path = next_dll_path( &context ))
466     {
467         int res = readlink( path, buffer, size );
468         if (res != -1) /* got a symlink */
469         {
470             *exists = 1;
471             if (res < 4 || res >= size) break;
472             buffer[res] = 0;
473             if (strchr( buffer, '/' )) break;  /* contains a path, not valid */
474             if (strcmp( buffer + res - 3, ".so" )) break;  /* does not end in .so, not valid */
475             buffer[res - 3] = 0;  /* remove .so */
476             ret = 0;
477             break;
478         }
479         if ((*exists = file_exists( path ))) break; /* exists but not a symlink, return the error */
480     }
481     free_dll_path( &context );
482     return ret;
483 }
484
485
486 /***********************************************************************
487  *           debug_usage
488  */
489 static void debug_usage(void)
490 {
491     static const char usage[] =
492         "Syntax of the WINEDEBUG variable:\n"
493         "  WINEDEBUG=[class]+xxx,[class]-yyy,...\n\n"
494         "Example: WINEDEBUG=+all,warn-heap\n"
495         "    turns on all messages except warning heap messages\n"
496         "Available message classes: err, warn, fixme, trace\n";
497     write( 2, usage, sizeof(usage) - 1 );
498     exit(1);
499 }
500
501
502 /***********************************************************************
503  *           wine_init
504  *
505  * Main Wine initialisation.
506  */
507 void wine_init( int argc, char *argv[], char *error, int error_size )
508 {
509     char *wine_debug;
510     int file_exists;
511     void *ntdll;
512     void (*init_func)(void);
513
514     build_dll_path();
515     wine_init_argv0_path( argv[0] );
516     __wine_main_argc = argc;
517     __wine_main_argv = argv;
518     __wine_main_environ = environ;
519     mmap_init();
520
521     if ((wine_debug = getenv("WINEDEBUG")))
522     {
523         if (!strcmp( wine_debug, "help" )) debug_usage();
524         wine_dbg_parse_options( wine_debug );
525     }
526
527     if (!(ntdll = dlopen_dll( "ntdll.dll", error, error_size, 0, &file_exists ))) return;
528     if (!(init_func = wine_dlsym( ntdll, "__wine_process_init", error, error_size ))) return;
529     init_func();
530 }
531
532
533 /*
534  * These functions provide wrappers around dlopen() and associated
535  * functions.  They work around a bug in glibc 2.1.x where calling
536  * a dl*() function after a previous dl*() function has failed
537  * without a dlerror() call between the two will cause a crash.
538  * They all take a pointer to a buffer that
539  * will receive the error description (from dlerror()).  This
540  * parameter may be NULL if the error description is not required.
541  */
542
543 /***********************************************************************
544  *              wine_dlopen
545  */
546 void *wine_dlopen( const char *filename, int flag, char *error, int errorsize )
547 {
548 #ifdef HAVE_DLOPEN
549     void *ret;
550     const char *s;
551     dlerror(); dlerror();
552     ret = dlopen( filename, flag );
553     s = dlerror();
554     if (error)
555     {
556         strncpy( error, s ? s : "", errorsize );
557         error[errorsize - 1] = '\0';
558     }
559     dlerror();
560     return ret;
561 #else
562     if (error)
563     {
564         strncpy( error, "dlopen interface not detected by configure", errorsize );
565         error[errorsize - 1] = '\0';
566     }
567     return NULL;
568 #endif
569 }
570
571 /***********************************************************************
572  *              wine_dlsym
573  */
574 void *wine_dlsym( void *handle, const char *symbol, char *error, int errorsize )
575 {
576 #ifdef HAVE_DLOPEN
577     void *ret;
578     const char *s;
579     dlerror(); dlerror();
580     ret = dlsym( handle, symbol );
581     s = dlerror();
582     if (error)
583     {
584         strncpy( error, s ? s : "", errorsize );
585         error[errorsize - 1] = '\0';
586     }
587     dlerror();
588     return ret;
589 #else
590     if (error)
591     {
592         strncpy( error, "dlopen interface not detected by configure", errorsize );
593         error[errorsize - 1] = '\0';
594     }
595     return NULL;
596 #endif
597 }
598
599 /***********************************************************************
600  *              wine_dlclose
601  */
602 int wine_dlclose( void *handle, char *error, int errorsize )
603 {
604 #ifdef HAVE_DLOPEN
605     int ret;
606     const char *s;
607     dlerror(); dlerror();
608     ret = dlclose( handle );
609     s = dlerror();
610     if (error)
611     {
612         strncpy( error, s ? s : "", errorsize );
613         error[errorsize - 1] = '\0';
614     }
615     dlerror();
616     return ret;
617 #else
618     if (error)
619     {
620         strncpy( error, "dlopen interface not detected by configure", errorsize );
621         error[errorsize - 1] = '\0';
622     }
623     return 1;
624 #endif
625 }