Stub implementations for AddMonitorW, DeletePrinterDriverW,
[wine/multimedia.git] / libs / wine / loader.c
bloba7200b7abb0a22db5408942c4e7ce2cd57512536
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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 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_UNISTD_H
35 # include <unistd.h>
36 #endif
38 #define NONAMELESSUNION
39 #define NONAMELESSSTRUCT
40 #include "windef.h"
41 #include "winbase.h"
42 #include "wine/library.h"
44 #ifdef __APPLE__
45 #include <crt_externs.h>
46 #define environ (*_NSGetEnviron())
47 #else
48 extern char **environ;
49 #endif
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;
57 struct dll_path_context
59 int index;
60 char *buffer;
63 #define MAX_DLLS 100
65 static struct
67 const IMAGE_NT_HEADERS *nt; /* NT header */
68 const char *filename; /* DLL file name */
69 } builtin_dlls[MAX_DLLS];
71 static int nb_dlls;
73 static const IMAGE_NT_HEADERS *main_exe;
75 static load_dll_callback_t load_dll_callback;
77 static const char **dll_paths;
78 static int nb_dll_paths;
79 static int dll_path_maxlen;
81 extern void mmap_init(void);
83 /* build the dll load path from the WINEDLLPATH variable */
84 static void build_dll_path(void)
86 static const char * const dlldir = DLLDIR;
87 int len, count = 0;
88 char *p, *path = getenv( "WINEDLLPATH" );
90 if (path)
92 /* count how many path elements we need */
93 path = strdup(path);
94 p = path;
95 while (*p)
97 while (*p == ':') p++;
98 if (!*p) break;
99 count++;
100 while (*p && *p != ':') p++;
104 dll_paths = malloc( (count+1) * sizeof(*dll_paths) );
106 if (count)
108 p = path;
109 nb_dll_paths = 0;
110 while (*p)
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++;
122 /* append default dll dir (if not empty) to path */
123 if ((len = strlen(dlldir)))
125 if (len > dll_path_maxlen) dll_path_maxlen = len;
126 dll_paths[nb_dll_paths++] = dlldir;
130 /* check if a given file can be opened */
131 inline static int file_exists( const char *name )
133 int fd = open( name, O_RDONLY );
134 if (fd != -1) close( fd );
135 return (fd != -1);
139 /* get a filename from the next entry in the dll path */
140 static char *next_dll_path( struct dll_path_context *context )
142 int index = context->index++;
144 if (index < nb_dll_paths)
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;
151 return NULL;
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 )
158 char *p;
159 int namelen = strlen( name );
161 context->buffer = p = malloc( dll_path_maxlen + namelen + strlen(ext) + 2 );
162 context->index = 0;
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 );
173 /* free the dll path context created by first_dll_path */
174 inline static void free_dll_path( struct dll_path_context *context )
176 free( context->buffer );
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 )
185 struct dll_path_context context;
186 char *path;
187 void *ret = NULL;
189 *exists = 0;
190 for (path = first_dll_path( name, ".so", &context ); path; path = next_dll_path( &context ))
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 */
195 free_dll_path( &context );
196 return ret;
200 /* adjust an array of pointers to make them into RVAs */
201 static inline void fixup_rva_ptrs( void *array, void *base, int count )
203 void **ptr = (void **)array;
204 while (count--)
206 if (*ptr) *ptr = (void *)((char *)*ptr - (char *)base);
207 ptr++;
212 /* fixup RVAs in the import directory */
213 static void fixup_imports( IMAGE_IMPORT_DESCRIPTOR *dir, DWORD size, void *base )
215 int count = size / sizeof(void *);
216 void **ptr = (void **)dir;
218 /* everything is either a pointer or a ordinal value below 0x10000 */
219 while (count--)
221 if (*ptr >= (void *)0x10000) *ptr = (void *)((char *)*ptr - (char *)base);
222 else if (*ptr) *ptr = (void *)(0x80000000 | (unsigned int)*ptr);
223 ptr++;
228 /* fixup RVAs in the resource directory */
229 static void fixup_resources( IMAGE_RESOURCE_DIRECTORY *dir, char *root, void *base )
231 IMAGE_RESOURCE_DIRECTORY_ENTRY *entry;
232 int i;
234 entry = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(dir + 1);
235 for (i = 0; i < dir->NumberOfNamedEntries + dir->NumberOfIdEntries; i++, entry++)
237 void *ptr = root + entry->u2.s3.OffsetToDirectory;
238 if (entry->u2.s3.DataIsDirectory) fixup_resources( ptr, root, base );
239 else
241 IMAGE_RESOURCE_DATA_ENTRY *data = ptr;
242 fixup_rva_ptrs( &data->OffsetToData, base, 1 );
248 /* map a builtin dll in memory and fixup RVAs */
249 static void *map_dll( const IMAGE_NT_HEADERS *nt_descr )
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 */
262 size_t size = (sizeof(IMAGE_DOS_HEADER)
263 + sizeof(IMAGE_NT_HEADERS)
264 + nb_sections * sizeof(IMAGE_SECTION_HEADER));
266 assert( size <= page_size );
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;
272 dos = (IMAGE_DOS_HEADER *)addr;
273 nt = (IMAGE_NT_HEADERS *)(dos + 1);
274 sec = (IMAGE_SECTION_HEADER *)(nt + 1);
276 /* Build the DOS and NT headers */
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);
289 *nt = *nt_descr;
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;
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;
304 fixup_rva_ptrs( &nt->OptionalHeader.AddressOfEntryPoint, addr, 1 );
306 /* Build the code section */
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++;
316 /* Build the data section */
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++;
327 /* Build the import directory */
329 dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_IMPORT_DIRECTORY];
330 if (dir->Size)
332 IMAGE_IMPORT_DESCRIPTOR *imports = (void *)dir->VirtualAddress;
333 fixup_rva_ptrs( &dir->VirtualAddress, addr, 1 );
334 fixup_imports( imports, dir->Size, addr );
337 /* Build the resource directory */
339 dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_RESOURCE_DIRECTORY];
340 if (dir->Size)
342 void *ptr = (void *)dir->VirtualAddress;
343 fixup_rva_ptrs( &dir->VirtualAddress, addr, 1 );
344 fixup_resources( ptr, ptr, addr );
347 /* Build the export directory */
349 dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_EXPORT_DIRECTORY];
350 if (dir->Size)
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 );
361 return addr;
362 #else /* HAVE_MMAP */
363 return NULL;
364 #endif /* HAVE_MMAP */
368 /***********************************************************************
369 * __wine_dll_register
371 * Register a built-in DLL descriptor.
373 void __wine_dll_register( const IMAGE_NT_HEADERS *header, const char *filename )
375 if (load_dll_callback) load_dll_callback( map_dll(header), filename );
376 else
378 if (!(header->FileHeader.Characteristics & IMAGE_FILE_DLL))
379 main_exe = header;
380 else
382 assert( nb_dlls < MAX_DLLS );
383 builtin_dlls[nb_dlls].nt = header;
384 builtin_dlls[nb_dlls].filename = filename;
385 nb_dlls++;
391 /***********************************************************************
392 * wine_dll_set_callback
394 * Set the callback function for dll loading, and call it
395 * for all dlls that were implicitly loaded already.
397 void wine_dll_set_callback( load_dll_callback_t load )
399 int i;
400 load_dll_callback = load;
401 for (i = 0; i < nb_dlls; i++)
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 );
408 nb_dlls = 0;
409 if (main_exe) load_dll_callback( map_dll(main_exe), "" );
413 /***********************************************************************
414 * wine_dll_load
416 * Load a builtin dll.
418 void *wine_dll_load( const char *filename, char *error, int errorsize, int *file_exists )
420 int i;
422 /* callback must have been set already */
423 assert( load_dll_callback );
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++)
429 if (!builtin_dlls[i].nt) continue;
430 if (!strcmp( builtin_dlls[i].filename, filename ))
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;
439 return dlopen_dll( filename, error, errorsize, 0, file_exists );
443 /***********************************************************************
444 * wine_dll_unload
446 * Unload a builtin dll.
448 void wine_dll_unload( void *handle )
450 if (handle != (void *)1)
451 wine_dlclose( handle, NULL, 0 );
455 /***********************************************************************
456 * wine_dll_load_main_exe
458 * Try to load the .so for the main exe.
460 void *wine_dll_load_main_exe( const char *name, char *error, int errorsize,
461 int test_only, int *file_exists )
463 return dlopen_dll( name, error, errorsize, test_only, file_exists );
467 /***********************************************************************
468 * wine_dll_get_owner
470 * Retrieve the name of the 32-bit owner dll for a 16-bit dll.
471 * Return 0 if OK, -1 on error.
473 int wine_dll_get_owner( const char *name, char *buffer, int size, int *exists )
475 int ret = -1;
476 char *path;
477 struct dll_path_context context;
479 *exists = 0;
480 for (path = first_dll_path( name, ".so", &context ); path; path = next_dll_path( &context ))
482 int res = readlink( path, buffer, size );
483 if (res != -1) /* got a symlink */
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;
494 if ((*exists = file_exists( path ))) break; /* exists but not a symlink, return the error */
496 free_dll_path( &context );
497 return ret;
501 /***********************************************************************
502 * debug_usage
504 static void debug_usage(void)
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);
517 /***********************************************************************
518 * wine_init
520 * Main Wine initialisation.
522 void wine_init( int argc, char *argv[], char *error, int error_size )
524 char *wine_debug;
525 int file_exists;
526 void *ntdll;
527 void (*init_func)(void);
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();
536 if ((wine_debug = getenv("WINEDEBUG")))
538 if (!strcmp( wine_debug, "help" )) debug_usage();
539 wine_dbg_parse_options( wine_debug );
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();
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.
558 /***********************************************************************
559 * wine_dlopen
561 void *wine_dlopen( const char *filename, int flag, char *error, int errorsize )
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)
571 strncpy( error, s ? s : "", errorsize );
572 error[errorsize - 1] = '\0';
574 dlerror();
575 return ret;
576 #else
577 if (error)
579 strncpy( error, "dlopen interface not detected by configure", errorsize );
580 error[errorsize - 1] = '\0';
582 return NULL;
583 #endif
586 /***********************************************************************
587 * wine_dlsym
589 void *wine_dlsym( void *handle, const char *symbol, char *error, int errorsize )
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)
599 strncpy( error, s ? s : "", errorsize );
600 error[errorsize - 1] = '\0';
602 dlerror();
603 return ret;
604 #else
605 if (error)
607 strncpy( error, "dlopen interface not detected by configure", errorsize );
608 error[errorsize - 1] = '\0';
610 return NULL;
611 #endif
614 /***********************************************************************
615 * wine_dlclose
617 int wine_dlclose( void *handle, char *error, int errorsize )
619 #ifdef HAVE_DLOPEN
620 int ret;
621 const char *s;
622 dlerror(); dlerror();
623 ret = dlclose( handle );
624 s = dlerror();
625 if (error)
627 strncpy( error, s ? s : "", errorsize );
628 error[errorsize - 1] = '\0';
630 dlerror();
631 return ret;
632 #else
633 if (error)
635 strncpy( error, "dlopen interface not detected by configure", errorsize );
636 error[errorsize - 1] = '\0';
638 return 1;
639 #endif