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