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