Implement LBS_COMBOBOX, and make use of it.
[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_cblp     = sizeof(*dos);
280     dos->e_cp       = 1;
281     dos->e_cparhdr  = (sizeof(*dos)+0xf)/0x10;
282     dos->e_minalloc = 0;
283     dos->e_maxalloc = 0xffff;
284     dos->e_ss       = 0x0000;
285     dos->e_sp       = 0x00b8;
286     dos->e_lfarlc   = sizeof(*dos);
287     dos->e_lfanew   = sizeof(*dos);
288
289     *nt = *nt_descr;
290
291     code_start = page_size;
292     data_start = ((BYTE *)nt->OptionalHeader.BaseOfData - addr) & ~page_mask;
293     data_end   = (((BYTE *)nt->OptionalHeader.SizeOfImage - addr) + page_mask) & ~page_mask;
294
295     nt->FileHeader.NumberOfSections                = nb_sections;
296     nt->OptionalHeader.BaseOfCode                  = code_start;
297     nt->OptionalHeader.BaseOfData                  = data_start;
298     nt->OptionalHeader.SizeOfCode                  = data_start - code_start;
299     nt->OptionalHeader.SizeOfInitializedData       = data_end - data_start;
300     nt->OptionalHeader.SizeOfUninitializedData     = 0;
301     nt->OptionalHeader.SizeOfImage                 = data_end;
302     nt->OptionalHeader.ImageBase                   = (DWORD)addr;
303
304     fixup_rva_ptrs( &nt->OptionalHeader.AddressOfEntryPoint, addr, 1 );
305
306     /* Build the code section */
307
308     strcpy( sec->Name, ".text" );
309     sec->SizeOfRawData = data_start - code_start;
310     sec->Misc.VirtualSize = sec->SizeOfRawData;
311     sec->VirtualAddress   = code_start;
312     sec->PointerToRawData = code_start;
313     sec->Characteristics  = (IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ);
314     sec++;
315
316     /* Build the data section */
317
318     strcpy( sec->Name, ".data" );
319     sec->SizeOfRawData = data_end - data_start;
320     sec->Misc.VirtualSize = sec->SizeOfRawData;
321     sec->VirtualAddress   = data_start;
322     sec->PointerToRawData = data_start;
323     sec->Characteristics  = (IMAGE_SCN_CNT_INITIALIZED_DATA |
324                              IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_READ);
325     sec++;
326
327     /* Build the import directory */
328
329     dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_IMPORT_DIRECTORY];
330     if (dir->Size)
331     {
332         IMAGE_IMPORT_DESCRIPTOR *imports = (void *)dir->VirtualAddress;
333         fixup_rva_ptrs( &dir->VirtualAddress, addr, 1 );
334         fixup_imports( imports, dir->Size, addr );
335     }
336
337     /* Build the resource directory */
338
339     dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_RESOURCE_DIRECTORY];
340     if (dir->Size)
341     {
342         void *ptr = (void *)dir->VirtualAddress;
343         fixup_rva_ptrs( &dir->VirtualAddress, addr, 1 );
344         fixup_resources( ptr, ptr, addr );
345     }
346
347     /* Build the export directory */
348
349     dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_EXPORT_DIRECTORY];
350     if (dir->Size)
351     {
352         IMAGE_EXPORT_DIRECTORY *exports = (void *)dir->VirtualAddress;
353         fixup_rva_ptrs( &dir->VirtualAddress, addr, 1 );
354         fixup_rva_ptrs( (void *)exports->AddressOfFunctions, addr, exports->NumberOfFunctions );
355         fixup_rva_ptrs( (void *)exports->AddressOfNames, addr, exports->NumberOfNames );
356         fixup_rva_ptrs( &exports->Name, addr, 1 );
357         fixup_rva_ptrs( &exports->AddressOfFunctions, addr, 1 );
358         fixup_rva_ptrs( &exports->AddressOfNames, addr, 1 );
359         fixup_rva_ptrs( &exports->AddressOfNameOrdinals, addr, 1 );
360     }
361     return addr;
362 #else  /* HAVE_MMAP */
363     return NULL;
364 #endif  /* HAVE_MMAP */
365 }
366
367
368 /***********************************************************************
369  *           __wine_dll_register
370  *
371  * Register a built-in DLL descriptor.
372  */
373 void __wine_dll_register( const IMAGE_NT_HEADERS *header, const char *filename )
374 {
375     if (load_dll_callback) load_dll_callback( map_dll(header), filename );
376     else
377     {
378         if (!(header->FileHeader.Characteristics & IMAGE_FILE_DLL))
379             main_exe = header;
380         else
381         {
382             assert( nb_dlls < MAX_DLLS );
383             builtin_dlls[nb_dlls].nt = header;
384             builtin_dlls[nb_dlls].filename = filename;
385             nb_dlls++;
386         }
387     }
388 }
389
390
391 /***********************************************************************
392  *           wine_dll_set_callback
393  *
394  * Set the callback function for dll loading, and call it
395  * for all dlls that were implicitly loaded already.
396  */
397 void wine_dll_set_callback( load_dll_callback_t load )
398 {
399     int i;
400     load_dll_callback = load;
401     for (i = 0; i < nb_dlls; i++)
402     {
403         const IMAGE_NT_HEADERS *nt = builtin_dlls[i].nt;
404         if (!nt) continue;
405         builtin_dlls[i].nt = NULL;
406         load_dll_callback( map_dll(nt), builtin_dlls[i].filename );
407     }
408     nb_dlls = 0;
409     if (main_exe) load_dll_callback( map_dll(main_exe), "" );
410 }
411
412
413 /***********************************************************************
414  *           wine_dll_load
415  *
416  * Load a builtin dll.
417  */
418 void *wine_dll_load( const char *filename, char *error, int errorsize, int *file_exists )
419 {
420     int i;
421
422     /* callback must have been set already */
423     assert( load_dll_callback );
424
425     /* check if we have it in the list */
426     /* this can happen when initializing pre-loaded dlls in wine_dll_set_callback */
427     for (i = 0; i < nb_dlls; i++)
428     {
429         if (!builtin_dlls[i].nt) continue;
430         if (!strcmp( builtin_dlls[i].filename, filename ))
431         {
432             const IMAGE_NT_HEADERS *nt = builtin_dlls[i].nt;
433             builtin_dlls[i].nt = NULL;
434             load_dll_callback( map_dll(nt), builtin_dlls[i].filename );
435             *file_exists = 1;
436             return (void *)1;
437         }
438     }
439     return dlopen_dll( filename, error, errorsize, 0, file_exists );
440 }
441
442
443 /***********************************************************************
444  *           wine_dll_unload
445  *
446  * Unload a builtin dll.
447  */
448 void wine_dll_unload( void *handle )
449 {
450     if (handle != (void *)1)
451         wine_dlclose( handle, NULL, 0 );
452 }
453
454
455 /***********************************************************************
456  *           wine_dll_load_main_exe
457  *
458  * Try to load the .so for the main exe.
459  */
460 void *wine_dll_load_main_exe( const char *name, char *error, int errorsize,
461                               int test_only, int *file_exists )
462 {
463     return dlopen_dll( name, error, errorsize, test_only, file_exists );
464 }
465
466
467 /***********************************************************************
468  *           wine_dll_get_owner
469  *
470  * Retrieve the name of the 32-bit owner dll for a 16-bit dll.
471  * Return 0 if OK, -1 on error.
472  */
473 int wine_dll_get_owner( const char *name, char *buffer, int size, int *exists )
474 {
475     int ret = -1;
476     char *path;
477     struct dll_path_context context;
478
479     *exists = 0;
480     for (path = first_dll_path( name, ".so", &context ); path; path = next_dll_path( &context ))
481     {
482         int res = readlink( path, buffer, size );
483         if (res != -1) /* got a symlink */
484         {
485             *exists = 1;
486             if (res < 4 || res >= size) break;
487             buffer[res] = 0;
488             if (strchr( buffer, '/' )) break;  /* contains a path, not valid */
489             if (strcmp( buffer + res - 3, ".so" )) break;  /* does not end in .so, not valid */
490             buffer[res - 3] = 0;  /* remove .so */
491             ret = 0;
492             break;
493         }
494         if ((*exists = file_exists( path ))) break; /* exists but not a symlink, return the error */
495     }
496     free_dll_path( &context );
497     return ret;
498 }
499
500
501 /***********************************************************************
502  *           debug_usage
503  */
504 static void debug_usage(void)
505 {
506     static const char usage[] =
507         "Syntax of the WINEDEBUG variable:\n"
508         "  WINEDEBUG=[class]+xxx,[class]-yyy,...\n\n"
509         "Example: WINEDEBUG=+all,warn-heap\n"
510         "    turns on all messages except warning heap messages\n"
511         "Available message classes: err, warn, fixme, trace\n";
512     write( 2, usage, sizeof(usage) - 1 );
513     exit(1);
514 }
515
516
517 /***********************************************************************
518  *           wine_init
519  *
520  * Main Wine initialisation.
521  */
522 void wine_init( int argc, char *argv[], char *error, int error_size )
523 {
524     char *wine_debug;
525     int file_exists;
526     void *ntdll;
527     void (*init_func)(void);
528
529     build_dll_path();
530     wine_init_argv0_path( argv[0] );
531     __wine_main_argc = argc;
532     __wine_main_argv = argv;
533     __wine_main_environ = environ;
534     mmap_init();
535
536     if ((wine_debug = getenv("WINEDEBUG")))
537     {
538         if (!strcmp( wine_debug, "help" )) debug_usage();
539         wine_dbg_parse_options( wine_debug );
540     }
541
542     if (!(ntdll = dlopen_dll( "ntdll.dll", error, error_size, 0, &file_exists ))) return;
543     if (!(init_func = wine_dlsym( ntdll, "__wine_process_init", error, error_size ))) return;
544     init_func();
545 }
546
547
548 /*
549  * These functions provide wrappers around dlopen() and associated
550  * functions.  They work around a bug in glibc 2.1.x where calling
551  * a dl*() function after a previous dl*() function has failed
552  * without a dlerror() call between the two will cause a crash.
553  * They all take a pointer to a buffer that
554  * will receive the error description (from dlerror()).  This
555  * parameter may be NULL if the error description is not required.
556  */
557
558 /***********************************************************************
559  *              wine_dlopen
560  */
561 void *wine_dlopen( const char *filename, int flag, char *error, int errorsize )
562 {
563 #ifdef HAVE_DLOPEN
564     void *ret;
565     const char *s;
566     dlerror(); dlerror();
567     ret = dlopen( filename, flag );
568     s = dlerror();
569     if (error)
570     {
571         strncpy( error, s ? s : "", errorsize );
572         error[errorsize - 1] = '\0';
573     }
574     dlerror();
575     return ret;
576 #else
577     if (error)
578     {
579         strncpy( error, "dlopen interface not detected by configure", errorsize );
580         error[errorsize - 1] = '\0';
581     }
582     return NULL;
583 #endif
584 }
585
586 /***********************************************************************
587  *              wine_dlsym
588  */
589 void *wine_dlsym( void *handle, const char *symbol, char *error, int errorsize )
590 {
591 #ifdef HAVE_DLOPEN
592     void *ret;
593     const char *s;
594     dlerror(); dlerror();
595     ret = dlsym( handle, symbol );
596     s = dlerror();
597     if (error)
598     {
599         strncpy( error, s ? s : "", errorsize );
600         error[errorsize - 1] = '\0';
601     }
602     dlerror();
603     return ret;
604 #else
605     if (error)
606     {
607         strncpy( error, "dlopen interface not detected by configure", errorsize );
608         error[errorsize - 1] = '\0';
609     }
610     return NULL;
611 #endif
612 }
613
614 /***********************************************************************
615  *              wine_dlclose
616  */
617 int wine_dlclose( void *handle, char *error, int errorsize )
618 {
619 #ifdef HAVE_DLOPEN
620     int ret;
621     const char *s;
622     dlerror(); dlerror();
623     ret = dlclose( handle );
624     s = dlerror();
625     if (error)
626     {
627         strncpy( error, s ? s : "", errorsize );
628         error[errorsize - 1] = '\0';
629     }
630     dlerror();
631     return ret;
632 #else
633     if (error)
634     {
635         strncpy( error, "dlopen interface not detected by configure", errorsize );
636         error[errorsize - 1] = '\0';
637     }
638     return 1;
639 #endif
640 }