msi: Add some registry reading macro functions.
[wine/hacks.git] / libs / wine / loader.c
blobadbadd59783a1afaaea6ebd2ae6cba1dde82f20c
1 /*
2 * Win32 builtin dlls support
4 * Copyright 2000 Alexandre Julliard
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.
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.
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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21 #include "config.h"
22 #include "wine/port.h"
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_SYS_RESOURCE_H
35 # include <sys/resource.h>
36 #endif
37 #ifdef HAVE_UNISTD_H
38 # include <unistd.h>
39 #endif
41 #define NONAMELESSUNION
42 #define NONAMELESSSTRUCT
43 #include "windef.h"
44 #include "winbase.h"
45 #include "wine/library.h"
47 #ifdef __APPLE__
48 #include <crt_externs.h>
49 #define environ (*_NSGetEnviron())
50 #else
51 extern char **environ;
52 #endif
54 /* argc/argv for the Windows application */
55 int __wine_main_argc = 0;
56 char **__wine_main_argv = NULL;
57 WCHAR **__wine_main_wargv = NULL;
58 char **__wine_main_environ = NULL;
60 struct dll_path_context
62 int index; /* current index in the dll path list */
63 char *buffer; /* buffer used for storing path names */
64 char *name; /* start of file name part in buffer (including leading slash) */
65 int namelen; /* length of file name without .so extension */
68 #define MAX_DLLS 100
70 static struct
72 const IMAGE_NT_HEADERS *nt; /* NT header */
73 const char *filename; /* DLL file name */
74 } builtin_dlls[MAX_DLLS];
76 static int nb_dlls;
78 static const IMAGE_NT_HEADERS *main_exe;
80 static load_dll_callback_t load_dll_callback;
82 static const char *build_dir;
83 static const char *default_dlldir;
84 static const char **dll_paths;
85 static int nb_dll_paths;
86 static int dll_path_maxlen;
88 extern void mmap_init(void);
89 extern void debug_init(void);
90 extern const char *get_dlldir( const char **default_dlldir );
92 /* build the dll load path from the WINEDLLPATH variable */
93 static void build_dll_path(void)
95 int len, count = 0;
96 char *p, *path = getenv( "WINEDLLPATH" );
97 const char *dlldir = get_dlldir( &default_dlldir );
99 if (path)
101 /* count how many path elements we need */
102 path = strdup(path);
103 p = path;
104 while (*p)
106 while (*p == ':') p++;
107 if (!*p) break;
108 count++;
109 while (*p && *p != ':') p++;
113 dll_paths = malloc( (count+2) * sizeof(*dll_paths) );
114 nb_dll_paths = 0;
116 if (dlldir)
118 dll_path_maxlen = strlen(dlldir);
119 dll_paths[nb_dll_paths++] = dlldir;
121 else if ((build_dir = wine_get_build_dir()))
123 dll_path_maxlen = strlen(build_dir) + sizeof("/programs");
126 if (count)
128 p = path;
129 while (*p)
131 while (*p == ':') *p++ = 0;
132 if (!*p) break;
133 dll_paths[nb_dll_paths] = p;
134 while (*p && *p != ':') p++;
135 if (p - dll_paths[nb_dll_paths] > dll_path_maxlen)
136 dll_path_maxlen = p - dll_paths[nb_dll_paths];
137 nb_dll_paths++;
141 /* append default dll dir (if not empty) to path */
142 if ((len = strlen(default_dlldir)) > 0)
144 if (len > dll_path_maxlen) dll_path_maxlen = len;
145 dll_paths[nb_dll_paths++] = default_dlldir;
149 /* check if a given file can be opened */
150 inline static int file_exists( const char *name )
152 int fd = open( name, O_RDONLY );
153 if (fd != -1) close( fd );
154 return (fd != -1);
157 inline static char *prepend( char *buffer, const char *str, size_t len )
159 return memcpy( buffer - len, str, len );
162 /* get a filename from the next entry in the dll path */
163 static char *next_dll_path( struct dll_path_context *context )
165 int index = context->index++;
166 int namelen = context->namelen;
167 char *path = context->name;
169 switch(index)
171 case 0: /* try programs dir for .exe files */
172 if (namelen > 4 && !memcmp( context->name + namelen - 4, ".exe", 4 ))
174 path = prepend( path, context->name, namelen - 4 );
175 path = prepend( path, "/programs", sizeof("/programs") - 1 );
176 path = prepend( path, build_dir, strlen(build_dir) );
177 return path;
179 context->index++;
180 /* fall through */
181 case 1: /* try dlls dir with subdir prefix */
182 if (namelen > 4 && !memcmp( context->name + namelen - 4, ".dll", 4 )) namelen -= 4;
183 path = prepend( path, context->name, namelen );
184 /* fall through */
185 case 2: /* try dlls dir without prefix */
186 path = prepend( path, "/dlls", sizeof("/dlls") - 1 );
187 path = prepend( path, build_dir, strlen(build_dir) );
188 return path;
189 default:
190 index -= 3;
191 if (index < nb_dll_paths)
192 return prepend( context->name, dll_paths[index], strlen( dll_paths[index] ));
193 break;
195 return NULL;
199 /* get a filename from the first entry in the dll path */
200 static char *first_dll_path( const char *name, const char *ext, struct dll_path_context *context )
202 char *p;
203 int namelen = strlen( name );
205 context->buffer = malloc( dll_path_maxlen + 2 * namelen + strlen(ext) + 3 );
206 context->index = build_dir ? 0 : 3; /* if no build dir skip all the build dir magic cases */
207 context->name = context->buffer + dll_path_maxlen + namelen + 1;
208 context->namelen = namelen + 1;
210 /* store the name at the end of the buffer, followed by extension */
211 p = context->name;
212 *p++ = '/';
213 memcpy( p, name, namelen );
214 strcpy( p + namelen, ext );
215 return next_dll_path( context );
219 /* free the dll path context created by first_dll_path */
220 inline static void free_dll_path( struct dll_path_context *context )
222 free( context->buffer );
226 /* open a library for a given dll, searching in the dll path
227 * 'name' must be the Windows dll name (e.g. "kernel32.dll") */
228 static void *dlopen_dll( const char *name, char *error, int errorsize,
229 int test_only, int *exists )
231 struct dll_path_context context;
232 char *path;
233 void *ret = NULL;
235 *exists = 0;
236 for (path = first_dll_path( name, ".so", &context ); path; path = next_dll_path( &context ))
238 if (!test_only && (ret = wine_dlopen( path, RTLD_NOW, error, errorsize ))) break;
239 if ((*exists = file_exists( path ))) break; /* exists but cannot be loaded, return the error */
241 free_dll_path( &context );
242 return ret;
246 /* adjust an array of pointers to make them into RVAs */
247 static inline void fixup_rva_ptrs( void *array, BYTE *base, unsigned int count )
249 void **src = (void **)array;
250 DWORD *dst = (DWORD *)array;
251 while (count--)
253 *dst++ = *src ? (BYTE *)*src - base : 0;
254 src++;
258 /* fixup an array of RVAs by adding the specified delta */
259 static inline void fixup_rva_dwords( DWORD *ptr, int delta, unsigned int count )
261 while (count--)
263 if (*ptr) *ptr += delta;
264 ptr++;
269 /* fixup RVAs in the import directory */
270 static void fixup_imports( IMAGE_IMPORT_DESCRIPTOR *dir, BYTE *base, int delta )
272 UINT_PTR *ptr;
274 while (dir->Name)
276 fixup_rva_dwords( &dir->u.OriginalFirstThunk, delta, 1 );
277 fixup_rva_dwords( &dir->Name, delta, 1 );
278 fixup_rva_dwords( &dir->FirstThunk, delta, 1 );
279 ptr = (UINT_PTR *)(base + dir->FirstThunk);
280 while (*ptr)
282 if (!(*ptr & IMAGE_ORDINAL_FLAG)) *ptr += delta;
283 ptr++;
285 dir++;
290 /* fixup RVAs in the export directory */
291 static void fixup_exports( IMAGE_EXPORT_DIRECTORY *dir, BYTE *base, int delta )
293 fixup_rva_dwords( &dir->Name, delta, 1 );
294 fixup_rva_dwords( &dir->AddressOfFunctions, delta, 1 );
295 fixup_rva_dwords( &dir->AddressOfNames, delta, 1 );
296 fixup_rva_dwords( &dir->AddressOfNameOrdinals, delta, 1 );
297 fixup_rva_dwords( (DWORD *)(base + dir->AddressOfNames), delta, dir->NumberOfNames );
298 fixup_rva_ptrs( (base + dir->AddressOfFunctions), base, dir->NumberOfFunctions );
302 /* fixup RVAs in the resource directory */
303 static void fixup_resources( IMAGE_RESOURCE_DIRECTORY *dir, BYTE *root, int delta )
305 IMAGE_RESOURCE_DIRECTORY_ENTRY *entry;
306 int i;
308 entry = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(dir + 1);
309 for (i = 0; i < dir->NumberOfNamedEntries + dir->NumberOfIdEntries; i++, entry++)
311 void *ptr = root + entry->u2.s3.OffsetToDirectory;
312 if (entry->u2.s3.DataIsDirectory) fixup_resources( ptr, root, delta );
313 else
315 IMAGE_RESOURCE_DATA_ENTRY *data = ptr;
316 fixup_rva_dwords( &data->OffsetToData, delta, 1 );
322 /* map a builtin dll in memory and fixup RVAs */
323 static void *map_dll( const IMAGE_NT_HEADERS *nt_descr )
325 #ifdef HAVE_MMAP
326 IMAGE_DATA_DIRECTORY *dir;
327 IMAGE_DOS_HEADER *dos;
328 IMAGE_NT_HEADERS *nt;
329 IMAGE_SECTION_HEADER *sec;
330 BYTE *addr;
331 DWORD code_start, data_start, data_end;
332 const size_t page_size = getpagesize();
333 const size_t page_mask = page_size - 1;
334 int i, delta, nb_sections = 2; /* code + data */
336 size_t size = (sizeof(IMAGE_DOS_HEADER)
337 + sizeof(IMAGE_NT_HEADERS)
338 + nb_sections * sizeof(IMAGE_SECTION_HEADER));
340 assert( size <= page_size );
342 /* module address must be aligned on 64K boundary */
343 addr = (BYTE *)((nt_descr->OptionalHeader.ImageBase + 0xffff) & ~0xffff);
344 if (wine_anon_mmap( addr, page_size, PROT_READ|PROT_WRITE, MAP_FIXED ) != addr) return NULL;
346 dos = (IMAGE_DOS_HEADER *)addr;
347 nt = (IMAGE_NT_HEADERS *)(dos + 1);
348 sec = (IMAGE_SECTION_HEADER *)(nt + 1);
350 /* Build the DOS and NT headers */
352 dos->e_magic = IMAGE_DOS_SIGNATURE;
353 dos->e_cblp = sizeof(*dos);
354 dos->e_cp = 1;
355 dos->e_cparhdr = (sizeof(*dos)+0xf)/0x10;
356 dos->e_minalloc = 0;
357 dos->e_maxalloc = 0xffff;
358 dos->e_ss = 0x0000;
359 dos->e_sp = 0x00b8;
360 dos->e_lfarlc = sizeof(*dos);
361 dos->e_lfanew = sizeof(*dos);
363 *nt = *nt_descr;
365 delta = (BYTE *)nt_descr - addr;
366 code_start = page_size;
367 data_start = delta & ~page_mask;
368 data_end = (nt->OptionalHeader.SizeOfImage + delta + page_mask) & ~page_mask;
370 fixup_rva_ptrs( &nt->OptionalHeader.AddressOfEntryPoint, addr, 1 );
372 nt->FileHeader.NumberOfSections = nb_sections;
373 nt->OptionalHeader.BaseOfCode = code_start;
374 #ifndef _WIN64
375 nt->OptionalHeader.BaseOfData = data_start;
376 #endif
377 nt->OptionalHeader.SizeOfCode = data_start - code_start;
378 nt->OptionalHeader.SizeOfInitializedData = data_end - data_start;
379 nt->OptionalHeader.SizeOfUninitializedData = 0;
380 nt->OptionalHeader.SizeOfImage = data_end;
381 nt->OptionalHeader.ImageBase = (ULONG_PTR)addr;
383 /* Build the code section */
385 memcpy( sec->Name, ".text", sizeof(".text") );
386 sec->SizeOfRawData = data_start - code_start;
387 sec->Misc.VirtualSize = sec->SizeOfRawData;
388 sec->VirtualAddress = code_start;
389 sec->PointerToRawData = code_start;
390 sec->Characteristics = (IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ);
391 sec++;
393 /* Build the data section */
395 memcpy( sec->Name, ".data", sizeof(".data") );
396 sec->SizeOfRawData = data_end - data_start;
397 sec->Misc.VirtualSize = sec->SizeOfRawData;
398 sec->VirtualAddress = data_start;
399 sec->PointerToRawData = data_start;
400 sec->Characteristics = (IMAGE_SCN_CNT_INITIALIZED_DATA |
401 IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_READ);
402 sec++;
404 for (i = 0; i < nt->OptionalHeader.NumberOfRvaAndSizes; i++)
405 fixup_rva_dwords( &nt->OptionalHeader.DataDirectory[i].VirtualAddress, delta, 1 );
407 /* Build the import directory */
409 dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_IMPORT_DIRECTORY];
410 if (dir->Size)
412 IMAGE_IMPORT_DESCRIPTOR *imports = (void *)(addr + dir->VirtualAddress);
413 fixup_imports( imports, addr, delta );
416 /* Build the resource directory */
418 dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_RESOURCE_DIRECTORY];
419 if (dir->Size)
421 void *ptr = (void *)(addr + dir->VirtualAddress);
422 fixup_resources( ptr, ptr, delta );
425 /* Build the export directory */
427 dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_EXPORT_DIRECTORY];
428 if (dir->Size)
430 IMAGE_EXPORT_DIRECTORY *exports = (void *)(addr + dir->VirtualAddress);
431 fixup_exports( exports, addr, delta );
433 return addr;
434 #else /* HAVE_MMAP */
435 return NULL;
436 #endif /* HAVE_MMAP */
440 /***********************************************************************
441 * __wine_dll_register
443 * Register a built-in DLL descriptor.
445 void __wine_dll_register( const IMAGE_NT_HEADERS *header, const char *filename )
447 if (load_dll_callback) load_dll_callback( map_dll(header), filename );
448 else
450 if (!(header->FileHeader.Characteristics & IMAGE_FILE_DLL))
451 main_exe = header;
452 else
454 assert( nb_dlls < MAX_DLLS );
455 builtin_dlls[nb_dlls].nt = header;
456 builtin_dlls[nb_dlls].filename = filename;
457 nb_dlls++;
463 /***********************************************************************
464 * wine_dll_set_callback
466 * Set the callback function for dll loading, and call it
467 * for all dlls that were implicitly loaded already.
469 void wine_dll_set_callback( load_dll_callback_t load )
471 int i;
472 load_dll_callback = load;
473 for (i = 0; i < nb_dlls; i++)
475 const IMAGE_NT_HEADERS *nt = builtin_dlls[i].nt;
476 if (!nt) continue;
477 builtin_dlls[i].nt = NULL;
478 load_dll_callback( map_dll(nt), builtin_dlls[i].filename );
480 nb_dlls = 0;
481 if (main_exe) load_dll_callback( map_dll(main_exe), "" );
485 /***********************************************************************
486 * wine_dll_load
488 * Load a builtin dll.
490 void *wine_dll_load( const char *filename, char *error, int errorsize, int *file_exists )
492 int i;
494 /* callback must have been set already */
495 assert( load_dll_callback );
497 /* check if we have it in the list */
498 /* this can happen when initializing pre-loaded dlls in wine_dll_set_callback */
499 for (i = 0; i < nb_dlls; i++)
501 if (!builtin_dlls[i].nt) continue;
502 if (!strcmp( builtin_dlls[i].filename, filename ))
504 const IMAGE_NT_HEADERS *nt = builtin_dlls[i].nt;
505 builtin_dlls[i].nt = NULL;
506 load_dll_callback( map_dll(nt), builtin_dlls[i].filename );
507 *file_exists = 1;
508 return (void *)1;
511 return dlopen_dll( filename, error, errorsize, 0, file_exists );
515 /***********************************************************************
516 * wine_dll_unload
518 * Unload a builtin dll.
520 void wine_dll_unload( void *handle )
522 if (handle != (void *)1)
523 wine_dlclose( handle, NULL, 0 );
527 /***********************************************************************
528 * wine_dll_load_main_exe
530 * Try to load the .so for the main exe.
532 void *wine_dll_load_main_exe( const char *name, char *error, int errorsize,
533 int test_only, int *file_exists )
535 return dlopen_dll( name, error, errorsize, test_only, file_exists );
539 /***********************************************************************
540 * wine_dll_enum_load_path
542 * Enumerate the dll load path.
544 const char *wine_dll_enum_load_path( unsigned int index )
546 if (index >= nb_dll_paths) return NULL;
547 return dll_paths[index];
551 /***********************************************************************
552 * wine_dll_get_owner
554 * Retrieve the name of the 32-bit owner dll for a 16-bit dll.
555 * Return 0 if OK, -1 on error.
557 int wine_dll_get_owner( const char *name, char *buffer, int size, int *exists )
559 int ret = -1;
560 char *path;
561 struct dll_path_context context;
563 *exists = 0;
565 for (path = first_dll_path( name, "16", &context ); path; path = next_dll_path( &context ))
567 int fd = open( path, O_RDONLY );
568 if (fd != -1)
570 int res = read( fd, buffer, size - 1 );
571 while (res > 0 && (buffer[res-1] == '\n' || buffer[res-1] == '\r')) res--;
572 buffer[res] = 0;
573 close( fd );
574 *exists = 1;
575 ret = 0;
576 break;
579 free_dll_path( &context );
580 if (ret != -1) return ret;
582 /* try old method too for backwards compatibility; will be removed later on */
583 for (path = first_dll_path( name, ".so", &context ); path; path = next_dll_path( &context ))
585 int res = readlink( path, buffer, size );
586 if (res != -1) /* got a symlink */
588 *exists = 1;
589 if (res < 4 || res >= size) break;
590 buffer[res] = 0;
591 if (strchr( buffer, '/' )) break; /* contains a path, not valid */
592 if (strcmp( buffer + res - 3, ".so" )) break; /* does not end in .so, not valid */
593 buffer[res - 3] = 0; /* remove .so */
594 ret = 0;
595 break;
597 if ((*exists = file_exists( path ))) break; /* exists but not a symlink, return the error */
599 free_dll_path( &context );
600 return ret;
604 /***********************************************************************
605 * set_max_limit
607 * Set a user limit to the maximum allowed value.
609 static void set_max_limit( int limit )
611 struct rlimit rlimit;
613 if (!getrlimit( limit, &rlimit ))
615 rlimit.rlim_cur = rlimit.rlim_max;
616 setrlimit( limit, &rlimit );
621 /***********************************************************************
622 * wine_init
624 * Main Wine initialisation.
626 void wine_init( int argc, char *argv[], char *error, int error_size )
628 struct dll_path_context context;
629 char *path;
630 void *ntdll = NULL;
631 void (*init_func)(void);
633 /* force a few limits that are set too low on some platforms */
634 set_max_limit( RLIMIT_NOFILE );
635 set_max_limit( RLIMIT_AS );
637 wine_init_argv0_path( argv[0] );
638 build_dll_path();
639 __wine_main_argc = argc;
640 __wine_main_argv = argv;
641 __wine_main_environ = environ;
642 mmap_init();
643 debug_init();
645 for (path = first_dll_path( "ntdll.dll", ".so", &context ); path; path = next_dll_path( &context ))
647 if ((ntdll = wine_dlopen( path, RTLD_NOW, error, error_size )))
649 /* if we didn't use the default dll dir, remove it from the search path */
650 if (default_dlldir[0] && context.index < nb_dll_paths) nb_dll_paths--;
651 break;
654 free_dll_path( &context );
656 if (!ntdll) return;
657 if (!(init_func = wine_dlsym( ntdll, "__wine_process_init", error, error_size ))) return;
658 init_func();
663 * These functions provide wrappers around dlopen() and associated
664 * functions. They work around a bug in glibc 2.1.x where calling
665 * a dl*() function after a previous dl*() function has failed
666 * without a dlerror() call between the two will cause a crash.
667 * They all take a pointer to a buffer that
668 * will receive the error description (from dlerror()). This
669 * parameter may be NULL if the error description is not required.
672 #ifndef RTLD_FIRST
673 #define RTLD_FIRST 0
674 #endif
676 /***********************************************************************
677 * wine_dlopen
679 void *wine_dlopen( const char *filename, int flag, char *error, size_t errorsize )
681 #ifdef HAVE_DLOPEN
682 void *ret;
683 const char *s;
684 dlerror(); dlerror();
685 ret = dlopen( filename, flag | RTLD_FIRST );
686 s = dlerror();
687 if (error && errorsize)
689 if (s)
691 size_t len = strlen(s);
692 if (len >= errorsize) len = errorsize - 1;
693 memcpy( error, s, len );
694 error[len] = 0;
696 else error[0] = 0;
698 dlerror();
699 return ret;
700 #else
701 if (error)
703 static const char msg[] = "dlopen interface not detected by configure";
704 size_t len = min( errorsize, sizeof(msg) );
705 memcpy( error, msg, len );
706 error[len - 1] = 0;
708 return NULL;
709 #endif
712 /***********************************************************************
713 * wine_dlsym
715 void *wine_dlsym( void *handle, const char *symbol, char *error, size_t errorsize )
717 #ifdef HAVE_DLOPEN
718 void *ret;
719 const char *s;
720 dlerror(); dlerror();
721 ret = dlsym( handle, symbol );
722 s = dlerror();
723 if (error && errorsize)
725 if (s)
727 size_t len = strlen(s);
728 if (len >= errorsize) len = errorsize - 1;
729 memcpy( error, s, len );
730 error[len] = 0;
732 else error[0] = 0;
734 dlerror();
735 return ret;
736 #else
737 if (error)
739 static const char msg[] = "dlopen interface not detected by configure";
740 size_t len = min( errorsize, sizeof(msg) );
741 memcpy( error, msg, len );
742 error[len - 1] = 0;
744 return NULL;
745 #endif
748 /***********************************************************************
749 * wine_dlclose
751 int wine_dlclose( void *handle, char *error, size_t errorsize )
753 #ifdef HAVE_DLOPEN
754 int ret;
755 const char *s;
756 dlerror(); dlerror();
757 ret = dlclose( handle );
758 s = dlerror();
759 if (error && errorsize)
761 if (s)
763 size_t len = strlen(s);
764 if (len >= errorsize) len = errorsize - 1;
765 memcpy( error, s, len );
766 error[len] = 0;
768 else error[0] = 0;
770 dlerror();
771 return ret;
772 #else
773 if (error)
775 static const char msg[] = "dlopen interface not detected by configure";
776 size_t len = min( errorsize, sizeof(msg) );
777 memcpy( error, msg, len );
778 error[len - 1] = 0;
780 return 1;
781 #endif