valgrind prevent crash hack
[wine/multimedia.git] / libs / wine / loader.c
blobc59f26215d17de64f137011de0e921c6367662b2
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 <limits.h>
28 #include <stdarg.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <sys/types.h>
32 #ifdef HAVE_SYS_MMAN_H
33 #include <sys/mman.h>
34 #endif
35 #ifdef HAVE_SYS_RESOURCE_H
36 # include <sys/resource.h>
37 #endif
38 #ifdef HAVE_UNISTD_H
39 # include <unistd.h>
40 #endif
42 #define NONAMELESSUNION
43 #define NONAMELESSSTRUCT
44 #include "windef.h"
45 #include "winbase.h"
46 #include "wine/library.h"
48 #ifdef HAVE_VALGRIND_MEMCHECK_H
49 #include <valgrind/memcheck.h>
50 #endif
52 #ifdef __APPLE__
53 #include <crt_externs.h>
54 #define environ (*_NSGetEnviron())
55 #include <CoreFoundation/CoreFoundation.h>
56 #include <pthread.h>
57 #else
58 extern char **environ;
59 #endif
61 /* argc/argv for the Windows application */
62 int __wine_main_argc = 0;
63 char **__wine_main_argv = NULL;
64 WCHAR **__wine_main_wargv = NULL;
65 char **__wine_main_environ = NULL;
67 struct dll_path_context
69 unsigned int index; /* current index in the dll path list */
70 char *buffer; /* buffer used for storing path names */
71 char *name; /* start of file name part in buffer (including leading slash) */
72 int namelen; /* length of file name without .so extension */
73 int win16; /* 16-bit dll search */
76 #define MAX_DLLS 100
78 static struct
80 const IMAGE_NT_HEADERS *nt; /* NT header */
81 const char *filename; /* DLL file name */
82 } builtin_dlls[MAX_DLLS];
84 static int nb_dlls;
86 static const IMAGE_NT_HEADERS *main_exe;
88 static load_dll_callback_t load_dll_callback;
90 static const char *build_dir;
91 static const char *default_dlldir;
92 static const char **dll_paths;
93 static unsigned int nb_dll_paths;
94 static int dll_path_maxlen;
96 extern void mmap_init(void);
97 extern const char *get_dlldir( const char **default_dlldir );
99 /* build the dll load path from the WINEDLLPATH variable */
100 static void build_dll_path(void)
102 int len, count = 0;
103 char *p, *path = getenv( "WINEDLLPATH" );
104 const char *dlldir = get_dlldir( &default_dlldir );
106 if (path)
108 /* count how many path elements we need */
109 path = strdup(path);
110 p = path;
111 while (*p)
113 while (*p == ':') p++;
114 if (!*p) break;
115 count++;
116 while (*p && *p != ':') p++;
120 dll_paths = malloc( (count+2) * sizeof(*dll_paths) );
121 nb_dll_paths = 0;
123 if (dlldir)
125 dll_path_maxlen = strlen(dlldir);
126 dll_paths[nb_dll_paths++] = dlldir;
128 else if ((build_dir = wine_get_build_dir()))
130 dll_path_maxlen = strlen(build_dir) + sizeof("/programs");
133 if (count)
135 p = path;
136 while (*p)
138 while (*p == ':') *p++ = 0;
139 if (!*p) break;
140 dll_paths[nb_dll_paths] = p;
141 while (*p && *p != ':') p++;
142 if (p - dll_paths[nb_dll_paths] > dll_path_maxlen)
143 dll_path_maxlen = p - dll_paths[nb_dll_paths];
144 nb_dll_paths++;
148 /* append default dll dir (if not empty) to path */
149 if ((len = strlen(default_dlldir)) > 0)
151 if (len > dll_path_maxlen) dll_path_maxlen = len;
152 dll_paths[nb_dll_paths++] = default_dlldir;
156 /* check if the library is the correct architecture */
157 /* only returns false for a valid library of the wrong arch */
158 static int check_library_arch( int fd )
160 #ifdef __APPLE__
161 struct /* Mach-O header */
163 unsigned int magic;
164 unsigned int cputype;
165 } header;
167 if (read( fd, &header, sizeof(header) ) != sizeof(header)) return 1;
168 if (header.magic != 0xfeedface) return 1;
169 if (sizeof(void *) == sizeof(int)) return !(header.cputype >> 24);
170 else return (header.cputype >> 24) == 1; /* CPU_ARCH_ABI64 */
171 #else
172 struct /* ELF header */
174 unsigned char magic[4];
175 unsigned char class;
176 unsigned char data;
177 unsigned char version;
178 } header;
180 if (read( fd, &header, sizeof(header) ) != sizeof(header)) return 1;
181 if (memcmp( header.magic, "\177ELF", 4 )) return 1;
182 if (header.version != 1 /* EV_CURRENT */) return 1;
183 #ifdef WORDS_BIGENDIAN
184 if (header.data != 2 /* ELFDATA2MSB */) return 1;
185 #else
186 if (header.data != 1 /* ELFDATA2LSB */) return 1;
187 #endif
188 if (sizeof(void *) == sizeof(int)) return header.class == 1; /* ELFCLASS32 */
189 else return header.class == 2; /* ELFCLASS64 */
190 #endif
193 /* check if a given file can be opened */
194 static inline int file_exists( const char *name )
196 int ret = 0;
197 int fd = open( name, O_RDONLY );
198 if (fd != -1)
200 ret = check_library_arch( fd );
201 close( fd );
203 return ret;
206 static inline char *prepend( char *buffer, const char *str, size_t len )
208 return memcpy( buffer - len, str, len );
211 /* get a filename from the next entry in the dll path */
212 static char *next_dll_path( struct dll_path_context *context )
214 unsigned int index = context->index++;
215 int namelen = context->namelen;
216 char *path = context->name;
218 switch(index)
220 case 0: /* try dlls dir with subdir prefix */
221 if (namelen > 4 && !memcmp( context->name + namelen - 4, ".dll", 4 )) namelen -= 4;
222 if (!context->win16) path = prepend( path, context->name, namelen );
223 path = prepend( path, "/dlls", sizeof("/dlls") - 1 );
224 path = prepend( path, build_dir, strlen(build_dir) );
225 return path;
226 case 1: /* try programs dir with subdir prefix */
227 if (!context->win16)
229 if (namelen > 4 && !memcmp( context->name + namelen - 4, ".exe", 4 )) namelen -= 4;
230 path = prepend( path, context->name, namelen );
231 path = prepend( path, "/programs", sizeof("/programs") - 1 );
232 path = prepend( path, build_dir, strlen(build_dir) );
233 return path;
235 context->index++;
236 /* fall through */
237 default:
238 index -= 2;
239 if (index < nb_dll_paths)
240 return prepend( context->name, dll_paths[index], strlen( dll_paths[index] ));
241 break;
243 return NULL;
247 /* get a filename from the first entry in the dll path */
248 static char *first_dll_path( const char *name, int win16, struct dll_path_context *context )
250 char *p;
251 int namelen = strlen( name );
252 const char *ext = win16 ? "16" : ".so";
254 context->buffer = malloc( dll_path_maxlen + 2 * namelen + strlen(ext) + 3 );
255 context->index = build_dir ? 0 : 2; /* if no build dir skip all the build dir magic cases */
256 context->name = context->buffer + dll_path_maxlen + namelen + 1;
257 context->namelen = namelen + 1;
258 context->win16 = win16;
260 /* store the name at the end of the buffer, followed by extension */
261 p = context->name;
262 *p++ = '/';
263 memcpy( p, name, namelen );
264 strcpy( p + namelen, ext );
265 return next_dll_path( context );
269 /* free the dll path context created by first_dll_path */
270 static inline void free_dll_path( struct dll_path_context *context )
272 free( context->buffer );
276 /* open a library for a given dll, searching in the dll path
277 * 'name' must be the Windows dll name (e.g. "kernel32.dll") */
278 static void *dlopen_dll( const char *name, char *error, int errorsize,
279 int test_only, int *exists )
281 struct dll_path_context context;
282 char *path;
283 void *ret = NULL;
285 *exists = 0;
286 for (path = first_dll_path( name, 0, &context ); path; path = next_dll_path( &context ))
288 if (!test_only && (ret = wine_dlopen( path, RTLD_NOW, error, errorsize ))) break;
289 if ((*exists = file_exists( path ))) break; /* exists but cannot be loaded, return the error */
291 free_dll_path( &context );
292 return ret;
296 /* adjust an array of pointers to make them into RVAs */
297 static inline void fixup_rva_ptrs( void *array, BYTE *base, unsigned int count )
299 void **src = (void **)array;
300 DWORD *dst = (DWORD *)array;
301 while (count--)
303 *dst++ = *src ? (BYTE *)*src - base : 0;
304 src++;
308 /* fixup an array of RVAs by adding the specified delta */
309 static inline void fixup_rva_dwords( DWORD *ptr, int delta, unsigned int count )
311 while (count--)
313 if (*ptr) *ptr += delta;
314 ptr++;
319 /* fixup RVAs in the import directory */
320 static void fixup_imports( IMAGE_IMPORT_DESCRIPTOR *dir, BYTE *base, int delta )
322 UINT_PTR *ptr;
324 while (dir->Name)
326 fixup_rva_dwords( &dir->u.OriginalFirstThunk, delta, 1 );
327 fixup_rva_dwords( &dir->Name, delta, 1 );
328 fixup_rva_dwords( &dir->FirstThunk, delta, 1 );
329 ptr = (UINT_PTR *)(base + (dir->u.OriginalFirstThunk ? dir->u.OriginalFirstThunk : dir->FirstThunk));
330 while (*ptr)
332 if (!(*ptr & IMAGE_ORDINAL_FLAG)) *ptr += delta;
333 ptr++;
335 dir++;
340 /* fixup RVAs in the export directory */
341 static void fixup_exports( IMAGE_EXPORT_DIRECTORY *dir, BYTE *base, int delta )
343 fixup_rva_dwords( &dir->Name, delta, 1 );
344 fixup_rva_dwords( &dir->AddressOfFunctions, delta, 1 );
345 fixup_rva_dwords( &dir->AddressOfNames, delta, 1 );
346 fixup_rva_dwords( &dir->AddressOfNameOrdinals, delta, 1 );
347 fixup_rva_dwords( (DWORD *)(base + dir->AddressOfNames), delta, dir->NumberOfNames );
348 fixup_rva_ptrs( (base + dir->AddressOfFunctions), base, dir->NumberOfFunctions );
352 /* fixup RVAs in the resource directory */
353 static void fixup_resources( IMAGE_RESOURCE_DIRECTORY *dir, BYTE *root, int delta )
355 IMAGE_RESOURCE_DIRECTORY_ENTRY *entry;
356 int i;
358 entry = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(dir + 1);
359 for (i = 0; i < dir->NumberOfNamedEntries + dir->NumberOfIdEntries; i++, entry++)
361 void *ptr = root + entry->u2.s3.OffsetToDirectory;
362 if (entry->u2.s3.DataIsDirectory) fixup_resources( ptr, root, delta );
363 else
365 IMAGE_RESOURCE_DATA_ENTRY *data = ptr;
366 fixup_rva_dwords( &data->OffsetToData, delta, 1 );
372 /* map a builtin dll in memory and fixup RVAs */
373 static void *map_dll( const IMAGE_NT_HEADERS *nt_descr )
375 #ifdef HAVE_MMAP
376 IMAGE_DATA_DIRECTORY *dir;
377 IMAGE_DOS_HEADER *dos;
378 IMAGE_NT_HEADERS *nt;
379 IMAGE_SECTION_HEADER *sec;
380 BYTE *addr;
381 DWORD code_start, data_start, data_end;
382 const size_t page_size = getpagesize();
383 const size_t page_mask = page_size - 1;
384 int delta, nb_sections = 2; /* code + data */
385 unsigned int i;
387 size_t size = (sizeof(IMAGE_DOS_HEADER)
388 + sizeof(IMAGE_NT_HEADERS)
389 + nb_sections * sizeof(IMAGE_SECTION_HEADER));
391 assert( size <= page_size );
393 /* module address must be aligned on 64K boundary */
394 addr = (BYTE *)((nt_descr->OptionalHeader.ImageBase + 0xffff) & ~0xffff);
395 if (wine_anon_mmap( addr, page_size, PROT_READ|PROT_WRITE, MAP_FIXED ) != addr) return NULL;
397 dos = (IMAGE_DOS_HEADER *)addr;
398 nt = (IMAGE_NT_HEADERS *)(dos + 1);
399 sec = (IMAGE_SECTION_HEADER *)(nt + 1);
401 /* Build the DOS and NT headers */
403 dos->e_magic = IMAGE_DOS_SIGNATURE;
404 dos->e_cblp = 0x90;
405 dos->e_cp = 3;
406 dos->e_cparhdr = (sizeof(*dos)+0xf)/0x10;
407 dos->e_minalloc = 0;
408 dos->e_maxalloc = 0xffff;
409 dos->e_ss = 0x0000;
410 dos->e_sp = 0x00b8;
411 dos->e_lfarlc = sizeof(*dos);
412 dos->e_lfanew = sizeof(*dos);
414 *nt = *nt_descr;
416 delta = (const BYTE *)nt_descr - addr;
417 code_start = page_size;
418 data_start = delta & ~page_mask;
419 data_end = (nt->OptionalHeader.SizeOfImage + delta + page_mask) & ~page_mask;
421 fixup_rva_ptrs( &nt->OptionalHeader.AddressOfEntryPoint, addr, 1 );
423 nt->FileHeader.NumberOfSections = nb_sections;
424 nt->OptionalHeader.BaseOfCode = code_start;
425 #ifndef _WIN64
426 nt->OptionalHeader.BaseOfData = data_start;
427 #endif
428 nt->OptionalHeader.SizeOfCode = data_start - code_start;
429 nt->OptionalHeader.SizeOfInitializedData = data_end - data_start;
430 nt->OptionalHeader.SizeOfUninitializedData = 0;
431 nt->OptionalHeader.SizeOfImage = data_end;
432 nt->OptionalHeader.ImageBase = (ULONG_PTR)addr;
434 /* Build the code section */
436 memcpy( sec->Name, ".text", sizeof(".text") );
437 sec->SizeOfRawData = data_start - code_start;
438 sec->Misc.VirtualSize = sec->SizeOfRawData;
439 sec->VirtualAddress = code_start;
440 sec->PointerToRawData = code_start;
441 sec->Characteristics = (IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ);
442 sec++;
444 /* Build the data section */
446 memcpy( sec->Name, ".data", sizeof(".data") );
447 sec->SizeOfRawData = data_end - data_start;
448 sec->Misc.VirtualSize = sec->SizeOfRawData;
449 sec->VirtualAddress = data_start;
450 sec->PointerToRawData = data_start;
451 sec->Characteristics = (IMAGE_SCN_CNT_INITIALIZED_DATA |
452 IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_READ);
453 sec++;
455 for (i = 0; i < nt->OptionalHeader.NumberOfRvaAndSizes; i++)
456 fixup_rva_dwords( &nt->OptionalHeader.DataDirectory[i].VirtualAddress, delta, 1 );
458 /* Build the import directory */
460 dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_IMPORT_DIRECTORY];
461 if (dir->Size)
463 IMAGE_IMPORT_DESCRIPTOR *imports = (void *)(addr + dir->VirtualAddress);
464 fixup_imports( imports, addr, delta );
467 /* Build the resource directory */
469 dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_RESOURCE_DIRECTORY];
470 if (dir->Size)
472 void *ptr = (void *)(addr + dir->VirtualAddress);
473 fixup_resources( ptr, ptr, delta );
476 /* Build the export directory */
478 dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_EXPORT_DIRECTORY];
479 if (dir->Size)
481 IMAGE_EXPORT_DIRECTORY *exports = (void *)(addr + dir->VirtualAddress);
482 fixup_exports( exports, addr, delta );
484 return addr;
485 #else /* HAVE_MMAP */
486 return NULL;
487 #endif /* HAVE_MMAP */
491 /***********************************************************************
492 * __wine_get_main_environment
494 * Return an environment pointer to work around lack of environ variable.
495 * Only exported on Mac OS.
497 char **__wine_get_main_environment(void)
499 return environ;
503 /***********************************************************************
504 * __wine_dll_register
506 * Register a built-in DLL descriptor.
508 void __wine_dll_register( const IMAGE_NT_HEADERS *header, const char *filename )
510 if (load_dll_callback) load_dll_callback( map_dll(header), filename );
511 else
513 if (!(header->FileHeader.Characteristics & IMAGE_FILE_DLL))
514 main_exe = header;
515 else
517 assert( nb_dlls < MAX_DLLS );
518 builtin_dlls[nb_dlls].nt = header;
519 builtin_dlls[nb_dlls].filename = filename;
520 nb_dlls++;
526 /***********************************************************************
527 * wine_dll_set_callback
529 * Set the callback function for dll loading, and call it
530 * for all dlls that were implicitly loaded already.
532 void wine_dll_set_callback( load_dll_callback_t load )
534 int i;
535 load_dll_callback = load;
536 for (i = 0; i < nb_dlls; i++)
538 const IMAGE_NT_HEADERS *nt = builtin_dlls[i].nt;
539 if (!nt) continue;
540 builtin_dlls[i].nt = NULL;
541 load_dll_callback( map_dll(nt), builtin_dlls[i].filename );
543 nb_dlls = 0;
544 if (main_exe) load_dll_callback( map_dll(main_exe), "" );
548 /***********************************************************************
549 * wine_dll_load
551 * Load a builtin dll.
553 void *wine_dll_load( const char *filename, char *error, int errorsize, int *file_exists )
555 int i;
557 /* callback must have been set already */
558 assert( load_dll_callback );
560 /* check if we have it in the list */
561 /* this can happen when initializing pre-loaded dlls in wine_dll_set_callback */
562 for (i = 0; i < nb_dlls; i++)
564 if (!builtin_dlls[i].nt) continue;
565 if (!strcmp( builtin_dlls[i].filename, filename ))
567 const IMAGE_NT_HEADERS *nt = builtin_dlls[i].nt;
568 builtin_dlls[i].nt = NULL;
569 load_dll_callback( map_dll(nt), builtin_dlls[i].filename );
570 *file_exists = 1;
571 return (void *)1;
574 return dlopen_dll( filename, error, errorsize, 0, file_exists );
578 /***********************************************************************
579 * wine_dll_unload
581 * Unload a builtin dll.
583 void wine_dll_unload( void *handle )
585 if (handle != (void *)1)
586 wine_dlclose( handle, NULL, 0 );
590 /***********************************************************************
591 * wine_dll_load_main_exe
593 * Try to load the .so for the main exe.
595 void *wine_dll_load_main_exe( const char *name, char *error, int errorsize,
596 int test_only, int *file_exists )
598 return dlopen_dll( name, error, errorsize, test_only, file_exists );
602 /***********************************************************************
603 * wine_dll_enum_load_path
605 * Enumerate the dll load path.
607 const char *wine_dll_enum_load_path( unsigned int index )
609 if (index >= nb_dll_paths) return NULL;
610 return dll_paths[index];
614 /***********************************************************************
615 * wine_dll_get_owner
617 * Retrieve the name of the 32-bit owner dll for a 16-bit dll.
618 * Return 0 if OK, -1 on error.
620 int wine_dll_get_owner( const char *name, char *buffer, int size, int *exists )
622 int ret = -1;
623 char *path;
624 struct dll_path_context context;
626 *exists = 0;
628 for (path = first_dll_path( name, 1, &context ); path; path = next_dll_path( &context ))
630 int fd = open( path, O_RDONLY );
631 if (fd != -1)
633 int res = read( fd, buffer, size - 1 );
634 while (res > 0 && (buffer[res-1] == '\n' || buffer[res-1] == '\r')) res--;
635 buffer[res] = 0;
636 close( fd );
637 *exists = 1;
638 ret = 0;
639 break;
642 free_dll_path( &context );
643 return ret;
646 /***********************************************************************
647 * set_max_limit
649 * Set a user limit to the maximum allowed value.
651 static void set_max_limit( int limit )
653 #ifdef HAVE_SETRLIMIT
654 struct rlimit rlimit;
656 #if defined(RLIMIT_NOFILE) && defined(RUNNING_ON_VALGRIND)
657 if (limit == RLIMIT_NOFILE && RUNNING_ON_VALGRIND)
658 return;
659 #endif
661 if (!getrlimit( limit, &rlimit ))
663 rlimit.rlim_cur = rlimit.rlim_max;
664 if (setrlimit( limit, &rlimit ) != 0)
666 #if defined(__APPLE__) && defined(RLIMIT_NOFILE) && defined(OPEN_MAX)
667 /* On Leopard, setrlimit(RLIMIT_NOFILE, ...) fails on attempts to set
668 * rlim_cur above OPEN_MAX (even if rlim_max > OPEN_MAX). */
669 if (limit == RLIMIT_NOFILE && rlimit.rlim_cur > OPEN_MAX)
671 rlimit.rlim_cur = OPEN_MAX;
672 setrlimit( limit, &rlimit );
674 #endif
677 #endif
681 #ifdef __APPLE__
682 struct apple_stack_info
684 void *stack;
685 size_t desired_size;
688 /***********************************************************************
689 * apple_alloc_thread_stack
691 * Callback for wine_mmap_enum_reserved_areas to allocate space for
692 * the secondary thread's stack.
694 static int apple_alloc_thread_stack( void *base, size_t size, void *arg )
696 struct apple_stack_info *info = arg;
698 /* For mysterious reasons, putting the thread stack at the very top
699 * of the address space causes subsequent execs to fail, even on the
700 * child side of a fork. Avoid the top 16MB. */
701 char * const limit = (char*)0xff000000;
702 if ((char *)base >= limit) return 0;
703 if (size > limit - (char*)base)
704 size = limit - (char*)base;
705 if (size < info->desired_size) return 0;
706 info->stack = wine_anon_mmap( (char *)base + size - info->desired_size,
707 info->desired_size, PROT_READ|PROT_WRITE, MAP_FIXED );
708 return (info->stack != (void *)-1);
711 /***********************************************************************
712 * apple_create_wine_thread
714 * Spin off a secondary thread to complete Wine initialization, leaving
715 * the original thread for the Mac frameworks.
717 * Invoked as a CFRunLoopSource perform callback.
719 static void apple_create_wine_thread( void *init_func )
721 int success = 0;
722 pthread_t thread;
723 pthread_attr_t attr;
725 if (!pthread_attr_init( &attr ))
727 struct apple_stack_info info;
729 /* Try to put the new thread's stack in the reserved area. If this
730 * fails, just let it go wherever. It'll be a waste of space, but we
731 * can go on. */
732 if (!pthread_attr_getstacksize( &attr, &info.desired_size ) &&
733 wine_mmap_enum_reserved_areas( apple_alloc_thread_stack, &info, 1 ))
735 wine_mmap_remove_reserved_area( info.stack, info.desired_size, 0 );
736 pthread_attr_setstackaddr( &attr, (char*)info.stack + info.desired_size );
739 if (!pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE ) &&
740 !pthread_create( &thread, &attr, init_func, NULL ))
741 success = 1;
743 pthread_attr_destroy( &attr );
746 /* Failure is indicated by returning from wine_init(). Stopping
747 * the run loop allows apple_main_thread() and thus wine_init() to
748 * return. */
749 if (!success)
750 CFRunLoopStop( CFRunLoopGetCurrent() );
754 /***********************************************************************
755 * apple_main_thread
757 * Park the process's original thread in a Core Foundation run loop for
758 * use by the Mac frameworks, especially receiving and handling
759 * distributed notifications. Spin off a new thread for the rest of the
760 * Wine initialization.
762 static void apple_main_thread( void (*init_func)(void) )
764 CFRunLoopSourceContext source_context = { 0 };
765 CFRunLoopSourceRef source;
767 /* Give ourselves the best chance of having the distributed notification
768 * center scheduled on this thread's run loop. In theory, it's scheduled
769 * in the first thread to ask for it. */
770 CFNotificationCenterGetDistributedCenter();
772 /* We use this run loop source for two purposes. First, a run loop exits
773 * if it has no more sources scheduled. So, we need at least one source
774 * to keep the run loop running. Second, although it's not critical, it's
775 * preferable for the Wine initialization to not proceed until we know
776 * the run loop is running. So, we signal our source immediately after
777 * adding it and have its callback spin off the Wine thread. */
778 source_context.info = init_func;
779 source_context.perform = apple_create_wine_thread;
780 source = CFRunLoopSourceCreate( NULL, 0, &source_context );
782 if (source)
784 CFRunLoopAddSource( CFRunLoopGetCurrent(), source, kCFRunLoopCommonModes );
785 CFRunLoopSourceSignal( source );
786 CFRelease( source );
788 CFRunLoopRun(); /* Should never return, except on error. */
791 /* If we get here (i.e. return), that indicates failure to our caller. */
793 #endif
796 /***********************************************************************
797 * wine_init
799 * Main Wine initialisation.
801 void wine_init( int argc, char *argv[], char *error, int error_size )
803 struct dll_path_context context;
804 char *path;
805 void *ntdll = NULL;
806 void (*init_func)(void);
808 /* force a few limits that are set too low on some platforms */
809 #ifdef RLIMIT_NOFILE
810 set_max_limit( RLIMIT_NOFILE );
811 #endif
812 #ifdef RLIMIT_AS
813 set_max_limit( RLIMIT_AS );
814 #endif
816 wine_init_argv0_path( argv[0] );
817 build_dll_path();
818 __wine_main_argc = argc;
819 __wine_main_argv = argv;
820 __wine_main_environ = __wine_get_main_environment();
821 mmap_init();
823 for (path = first_dll_path( "ntdll.dll", 0, &context ); path; path = next_dll_path( &context ))
825 if ((ntdll = wine_dlopen( path, RTLD_NOW, error, error_size )))
827 /* if we didn't use the default dll dir, remove it from the search path */
828 if (default_dlldir[0] && context.index < nb_dll_paths + 2) nb_dll_paths--;
829 break;
832 free_dll_path( &context );
834 if (!ntdll) return;
835 if (!(init_func = wine_dlsym( ntdll, "__wine_process_init", error, error_size ))) return;
836 #ifdef __APPLE__
837 apple_main_thread( init_func );
838 #else
839 init_func();
840 #endif
845 * These functions provide wrappers around dlopen() and associated
846 * functions. They work around a bug in glibc 2.1.x where calling
847 * a dl*() function after a previous dl*() function has failed
848 * without a dlerror() call between the two will cause a crash.
849 * They all take a pointer to a buffer that
850 * will receive the error description (from dlerror()). This
851 * parameter may be NULL if the error description is not required.
854 #ifndef RTLD_FIRST
855 #define RTLD_FIRST 0
856 #endif
858 /***********************************************************************
859 * wine_dlopen
861 void *wine_dlopen( const char *filename, int flag, char *error, size_t errorsize )
863 #ifdef HAVE_DLOPEN
864 void *ret;
865 const char *s;
867 #ifdef __APPLE__
868 /* the Mac OS loader pretends to be able to load PE files, so avoid them here */
869 unsigned char magic[2];
870 int fd = open( filename, O_RDONLY );
871 if (fd != -1)
873 if (pread( fd, magic, 2, 0 ) == 2 && magic[0] == 'M' && magic[1] == 'Z')
875 static const char msg[] = "MZ format";
876 size_t len = min( errorsize, sizeof(msg) );
877 memcpy( error, msg, len );
878 error[len - 1] = 0;
879 close( fd );
880 return NULL;
882 close( fd );
884 #endif
885 dlerror(); dlerror();
886 #ifdef __sun
887 if (strchr( filename, ':' ))
889 char path[PATH_MAX];
890 /* Solaris' brain damaged dlopen() treats ':' as a path separator */
891 realpath( filename, path );
892 ret = dlopen( path, flag | RTLD_FIRST );
894 else
895 #endif
896 ret = dlopen( filename, flag | RTLD_FIRST );
897 s = dlerror();
898 if (error && errorsize)
900 if (s)
902 size_t len = strlen(s);
903 if (len >= errorsize) len = errorsize - 1;
904 memcpy( error, s, len );
905 error[len] = 0;
907 else error[0] = 0;
909 dlerror();
910 return ret;
911 #else
912 if (error)
914 static const char msg[] = "dlopen interface not detected by configure";
915 size_t len = min( errorsize, sizeof(msg) );
916 memcpy( error, msg, len );
917 error[len - 1] = 0;
919 return NULL;
920 #endif
923 /***********************************************************************
924 * wine_dlsym
926 void *wine_dlsym( void *handle, const char *symbol, char *error, size_t errorsize )
928 #ifdef HAVE_DLOPEN
929 void *ret;
930 const char *s;
931 dlerror(); dlerror();
932 ret = dlsym( handle, symbol );
933 s = dlerror();
934 if (error && errorsize)
936 if (s)
938 size_t len = strlen(s);
939 if (len >= errorsize) len = errorsize - 1;
940 memcpy( error, s, len );
941 error[len] = 0;
943 else error[0] = 0;
945 dlerror();
946 return ret;
947 #else
948 if (error)
950 static const char msg[] = "dlopen interface not detected by configure";
951 size_t len = min( errorsize, sizeof(msg) );
952 memcpy( error, msg, len );
953 error[len - 1] = 0;
955 return NULL;
956 #endif
959 /***********************************************************************
960 * wine_dlclose
962 int wine_dlclose( void *handle, char *error, size_t errorsize )
964 #ifdef HAVE_DLOPEN
965 int ret;
966 const char *s;
967 dlerror(); dlerror();
968 ret = dlclose( handle );
969 s = dlerror();
970 if (error && errorsize)
972 if (s)
974 size_t len = strlen(s);
975 if (len >= errorsize) len = errorsize - 1;
976 memcpy( error, s, len );
977 error[len] = 0;
979 else error[0] = 0;
981 dlerror();
982 return ret;
983 #else
984 if (error)
986 static const char msg[] = "dlopen interface not detected by configure";
987 size_t len = min( errorsize, sizeof(msg) );
988 memcpy( error, msg, len );
989 error[len - 1] = 0;
991 return 1;
992 #endif