d3dx9/tests: Add basic tests for ID3DXRenderToEnvMap.
[wine/multimedia.git] / libs / wine / loader.c
blobdf0a6b5b6d7ad4741d6de3aab6bd91840775c002
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 __APPLE__
49 #include <crt_externs.h>
50 #define environ (*_NSGetEnviron())
51 #include <CoreFoundation/CoreFoundation.h>
52 #include <pthread.h>
53 #else
54 extern char **environ;
55 #endif
57 /* argc/argv for the Windows application */
58 int __wine_main_argc = 0;
59 char **__wine_main_argv = NULL;
60 WCHAR **__wine_main_wargv = NULL;
61 char **__wine_main_environ = NULL;
63 struct dll_path_context
65 unsigned int index; /* current index in the dll path list */
66 char *buffer; /* buffer used for storing path names */
67 char *name; /* start of file name part in buffer (including leading slash) */
68 int namelen; /* length of file name without .so extension */
69 int win16; /* 16-bit dll search */
72 #define MAX_DLLS 100
74 static struct
76 const IMAGE_NT_HEADERS *nt; /* NT header */
77 const char *filename; /* DLL file name */
78 } builtin_dlls[MAX_DLLS];
80 static int nb_dlls;
82 static const IMAGE_NT_HEADERS *main_exe;
84 static load_dll_callback_t load_dll_callback;
86 static const char *build_dir;
87 static const char *default_dlldir;
88 static const char **dll_paths;
89 static unsigned int nb_dll_paths;
90 static int dll_path_maxlen;
92 extern void mmap_init(void);
93 extern const char *get_dlldir( const char **default_dlldir );
95 /* build the dll load path from the WINEDLLPATH variable */
96 static void build_dll_path(void)
98 int len, count = 0;
99 char *p, *path = getenv( "WINEDLLPATH" );
100 const char *dlldir = get_dlldir( &default_dlldir );
102 if (path)
104 /* count how many path elements we need */
105 path = strdup(path);
106 p = path;
107 while (*p)
109 while (*p == ':') p++;
110 if (!*p) break;
111 count++;
112 while (*p && *p != ':') p++;
116 dll_paths = malloc( (count+2) * sizeof(*dll_paths) );
117 nb_dll_paths = 0;
119 if (dlldir)
121 dll_path_maxlen = strlen(dlldir);
122 dll_paths[nb_dll_paths++] = dlldir;
124 else if ((build_dir = wine_get_build_dir()))
126 dll_path_maxlen = strlen(build_dir) + sizeof("/programs");
129 if (count)
131 p = path;
132 while (*p)
134 while (*p == ':') *p++ = 0;
135 if (!*p) break;
136 dll_paths[nb_dll_paths] = p;
137 while (*p && *p != ':') p++;
138 if (p - dll_paths[nb_dll_paths] > dll_path_maxlen)
139 dll_path_maxlen = p - dll_paths[nb_dll_paths];
140 nb_dll_paths++;
144 /* append default dll dir (if not empty) to path */
145 if ((len = strlen(default_dlldir)) > 0)
147 if (len > dll_path_maxlen) dll_path_maxlen = len;
148 dll_paths[nb_dll_paths++] = default_dlldir;
152 /* check if the library is the correct architecture */
153 /* only returns false for a valid library of the wrong arch */
154 static int check_library_arch( int fd )
156 #ifdef __APPLE__
157 struct /* Mach-O header */
159 unsigned int magic;
160 unsigned int cputype;
161 } header;
163 if (read( fd, &header, sizeof(header) ) != sizeof(header)) return 1;
164 if (header.magic != 0xfeedface) return 1;
165 if (sizeof(void *) == sizeof(int)) return !(header.cputype >> 24);
166 else return (header.cputype >> 24) == 1; /* CPU_ARCH_ABI64 */
167 #else
168 struct /* ELF header */
170 unsigned char magic[4];
171 unsigned char class;
172 unsigned char data;
173 unsigned char version;
174 } header;
176 if (read( fd, &header, sizeof(header) ) != sizeof(header)) return 1;
177 if (memcmp( header.magic, "\177ELF", 4 )) return 1;
178 if (header.version != 1 /* EV_CURRENT */) return 1;
179 #ifdef WORDS_BIGENDIAN
180 if (header.data != 2 /* ELFDATA2MSB */) return 1;
181 #else
182 if (header.data != 1 /* ELFDATA2LSB */) return 1;
183 #endif
184 if (sizeof(void *) == sizeof(int)) return header.class == 1; /* ELFCLASS32 */
185 else return header.class == 2; /* ELFCLASS64 */
186 #endif
189 /* check if a given file can be opened */
190 static inline int file_exists( const char *name )
192 int ret = 0;
193 int fd = open( name, O_RDONLY );
194 if (fd != -1)
196 ret = check_library_arch( fd );
197 close( fd );
199 return ret;
202 static inline char *prepend( char *buffer, const char *str, size_t len )
204 return memcpy( buffer - len, str, len );
207 /* get a filename from the next entry in the dll path */
208 static char *next_dll_path( struct dll_path_context *context )
210 unsigned int index = context->index++;
211 int namelen = context->namelen;
212 char *path = context->name;
214 switch(index)
216 case 0: /* try dlls dir with subdir prefix */
217 if (namelen > 4 && !memcmp( context->name + namelen - 4, ".dll", 4 )) namelen -= 4;
218 if (!context->win16) path = prepend( path, context->name, namelen );
219 path = prepend( path, "/dlls", sizeof("/dlls") - 1 );
220 path = prepend( path, build_dir, strlen(build_dir) );
221 return path;
222 case 1: /* try programs dir with subdir prefix */
223 if (!context->win16)
225 if (namelen > 4 && !memcmp( context->name + namelen - 4, ".exe", 4 )) namelen -= 4;
226 path = prepend( path, context->name, namelen );
227 path = prepend( path, "/programs", sizeof("/programs") - 1 );
228 path = prepend( path, build_dir, strlen(build_dir) );
229 return path;
231 context->index++;
232 /* fall through */
233 default:
234 index -= 2;
235 if (index < nb_dll_paths)
236 return prepend( context->name, dll_paths[index], strlen( dll_paths[index] ));
237 break;
239 return NULL;
243 /* get a filename from the first entry in the dll path */
244 static char *first_dll_path( const char *name, int win16, struct dll_path_context *context )
246 char *p;
247 int namelen = strlen( name );
248 const char *ext = win16 ? "16" : ".so";
250 context->buffer = malloc( dll_path_maxlen + 2 * namelen + strlen(ext) + 3 );
251 context->index = build_dir ? 0 : 2; /* if no build dir skip all the build dir magic cases */
252 context->name = context->buffer + dll_path_maxlen + namelen + 1;
253 context->namelen = namelen + 1;
254 context->win16 = win16;
256 /* store the name at the end of the buffer, followed by extension */
257 p = context->name;
258 *p++ = '/';
259 memcpy( p, name, namelen );
260 strcpy( p + namelen, ext );
261 return next_dll_path( context );
265 /* free the dll path context created by first_dll_path */
266 static inline void free_dll_path( struct dll_path_context *context )
268 free( context->buffer );
272 /* open a library for a given dll, searching in the dll path
273 * 'name' must be the Windows dll name (e.g. "kernel32.dll") */
274 static void *dlopen_dll( const char *name, char *error, int errorsize,
275 int test_only, int *exists )
277 struct dll_path_context context;
278 char *path;
279 void *ret = NULL;
281 *exists = 0;
282 for (path = first_dll_path( name, 0, &context ); path; path = next_dll_path( &context ))
284 if (!test_only && (ret = wine_dlopen( path, RTLD_NOW, error, errorsize ))) break;
285 if ((*exists = file_exists( path ))) break; /* exists but cannot be loaded, return the error */
287 free_dll_path( &context );
288 return ret;
292 /* adjust an array of pointers to make them into RVAs */
293 static inline void fixup_rva_ptrs( void *array, BYTE *base, unsigned int count )
295 void **src = (void **)array;
296 DWORD *dst = (DWORD *)array;
297 while (count--)
299 *dst++ = *src ? (BYTE *)*src - base : 0;
300 src++;
304 /* fixup an array of RVAs by adding the specified delta */
305 static inline void fixup_rva_dwords( DWORD *ptr, int delta, unsigned int count )
307 while (count--)
309 if (*ptr) *ptr += delta;
310 ptr++;
315 /* fixup RVAs in the import directory */
316 static void fixup_imports( IMAGE_IMPORT_DESCRIPTOR *dir, BYTE *base, int delta )
318 UINT_PTR *ptr;
320 while (dir->Name)
322 fixup_rva_dwords( &dir->u.OriginalFirstThunk, delta, 1 );
323 fixup_rva_dwords( &dir->Name, delta, 1 );
324 fixup_rva_dwords( &dir->FirstThunk, delta, 1 );
325 ptr = (UINT_PTR *)(base + (dir->u.OriginalFirstThunk ? dir->u.OriginalFirstThunk : dir->FirstThunk));
326 while (*ptr)
328 if (!(*ptr & IMAGE_ORDINAL_FLAG)) *ptr += delta;
329 ptr++;
331 dir++;
336 /* fixup RVAs in the export directory */
337 static void fixup_exports( IMAGE_EXPORT_DIRECTORY *dir, BYTE *base, int delta )
339 fixup_rva_dwords( &dir->Name, delta, 1 );
340 fixup_rva_dwords( &dir->AddressOfFunctions, delta, 1 );
341 fixup_rva_dwords( &dir->AddressOfNames, delta, 1 );
342 fixup_rva_dwords( &dir->AddressOfNameOrdinals, delta, 1 );
343 fixup_rva_dwords( (DWORD *)(base + dir->AddressOfNames), delta, dir->NumberOfNames );
344 fixup_rva_ptrs( (base + dir->AddressOfFunctions), base, dir->NumberOfFunctions );
348 /* fixup RVAs in the resource directory */
349 static void fixup_resources( IMAGE_RESOURCE_DIRECTORY *dir, BYTE *root, int delta )
351 IMAGE_RESOURCE_DIRECTORY_ENTRY *entry;
352 int i;
354 entry = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(dir + 1);
355 for (i = 0; i < dir->NumberOfNamedEntries + dir->NumberOfIdEntries; i++, entry++)
357 void *ptr = root + entry->u2.s3.OffsetToDirectory;
358 if (entry->u2.s3.DataIsDirectory) fixup_resources( ptr, root, delta );
359 else
361 IMAGE_RESOURCE_DATA_ENTRY *data = ptr;
362 fixup_rva_dwords( &data->OffsetToData, delta, 1 );
368 /* map a builtin dll in memory and fixup RVAs */
369 static void *map_dll( const IMAGE_NT_HEADERS *nt_descr )
371 #ifdef HAVE_MMAP
372 IMAGE_DATA_DIRECTORY *dir;
373 IMAGE_DOS_HEADER *dos;
374 IMAGE_NT_HEADERS *nt;
375 IMAGE_SECTION_HEADER *sec;
376 BYTE *addr;
377 DWORD code_start, data_start, data_end;
378 const size_t page_size = getpagesize();
379 const size_t page_mask = page_size - 1;
380 int delta, nb_sections = 2; /* code + data */
381 unsigned int i;
383 size_t size = (sizeof(IMAGE_DOS_HEADER)
384 + sizeof(IMAGE_NT_HEADERS)
385 + nb_sections * sizeof(IMAGE_SECTION_HEADER));
387 assert( size <= page_size );
389 /* module address must be aligned on 64K boundary */
390 addr = (BYTE *)((nt_descr->OptionalHeader.ImageBase + 0xffff) & ~0xffff);
391 if (wine_anon_mmap( addr, page_size, PROT_READ|PROT_WRITE, MAP_FIXED ) != addr) return NULL;
393 dos = (IMAGE_DOS_HEADER *)addr;
394 nt = (IMAGE_NT_HEADERS *)(dos + 1);
395 sec = (IMAGE_SECTION_HEADER *)(nt + 1);
397 /* Build the DOS and NT headers */
399 dos->e_magic = IMAGE_DOS_SIGNATURE;
400 dos->e_cblp = 0x90;
401 dos->e_cp = 3;
402 dos->e_cparhdr = (sizeof(*dos)+0xf)/0x10;
403 dos->e_minalloc = 0;
404 dos->e_maxalloc = 0xffff;
405 dos->e_ss = 0x0000;
406 dos->e_sp = 0x00b8;
407 dos->e_lfarlc = sizeof(*dos);
408 dos->e_lfanew = sizeof(*dos);
410 *nt = *nt_descr;
412 delta = (const BYTE *)nt_descr - addr;
413 code_start = page_size;
414 data_start = delta & ~page_mask;
415 data_end = (nt->OptionalHeader.SizeOfImage + delta + page_mask) & ~page_mask;
417 fixup_rva_ptrs( &nt->OptionalHeader.AddressOfEntryPoint, addr, 1 );
419 nt->FileHeader.NumberOfSections = nb_sections;
420 nt->OptionalHeader.BaseOfCode = code_start;
421 #ifndef _WIN64
422 nt->OptionalHeader.BaseOfData = data_start;
423 #endif
424 nt->OptionalHeader.SizeOfCode = data_start - code_start;
425 nt->OptionalHeader.SizeOfInitializedData = data_end - data_start;
426 nt->OptionalHeader.SizeOfUninitializedData = 0;
427 nt->OptionalHeader.SizeOfImage = data_end;
428 nt->OptionalHeader.ImageBase = (ULONG_PTR)addr;
430 /* Build the code section */
432 memcpy( sec->Name, ".text", sizeof(".text") );
433 sec->SizeOfRawData = data_start - code_start;
434 sec->Misc.VirtualSize = sec->SizeOfRawData;
435 sec->VirtualAddress = code_start;
436 sec->PointerToRawData = code_start;
437 sec->Characteristics = (IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ);
438 sec++;
440 /* Build the data section */
442 memcpy( sec->Name, ".data", sizeof(".data") );
443 sec->SizeOfRawData = data_end - data_start;
444 sec->Misc.VirtualSize = sec->SizeOfRawData;
445 sec->VirtualAddress = data_start;
446 sec->PointerToRawData = data_start;
447 sec->Characteristics = (IMAGE_SCN_CNT_INITIALIZED_DATA |
448 IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_READ);
449 sec++;
451 for (i = 0; i < nt->OptionalHeader.NumberOfRvaAndSizes; i++)
452 fixup_rva_dwords( &nt->OptionalHeader.DataDirectory[i].VirtualAddress, delta, 1 );
454 /* Build the import directory */
456 dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_IMPORT_DIRECTORY];
457 if (dir->Size)
459 IMAGE_IMPORT_DESCRIPTOR *imports = (void *)(addr + dir->VirtualAddress);
460 fixup_imports( imports, addr, delta );
463 /* Build the resource directory */
465 dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_RESOURCE_DIRECTORY];
466 if (dir->Size)
468 void *ptr = (void *)(addr + dir->VirtualAddress);
469 fixup_resources( ptr, ptr, delta );
472 /* Build the export directory */
474 dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_EXPORT_DIRECTORY];
475 if (dir->Size)
477 IMAGE_EXPORT_DIRECTORY *exports = (void *)(addr + dir->VirtualAddress);
478 fixup_exports( exports, addr, delta );
480 return addr;
481 #else /* HAVE_MMAP */
482 return NULL;
483 #endif /* HAVE_MMAP */
487 /***********************************************************************
488 * __wine_get_main_environment
490 * Return an environment pointer to work around lack of environ variable.
491 * Only exported on Mac OS.
493 char **__wine_get_main_environment(void)
495 return environ;
499 /***********************************************************************
500 * __wine_dll_register
502 * Register a built-in DLL descriptor.
504 void __wine_dll_register( const IMAGE_NT_HEADERS *header, const char *filename )
506 if (load_dll_callback) load_dll_callback( map_dll(header), filename );
507 else
509 if (!(header->FileHeader.Characteristics & IMAGE_FILE_DLL))
510 main_exe = header;
511 else
513 assert( nb_dlls < MAX_DLLS );
514 builtin_dlls[nb_dlls].nt = header;
515 builtin_dlls[nb_dlls].filename = filename;
516 nb_dlls++;
522 /***********************************************************************
523 * wine_dll_set_callback
525 * Set the callback function for dll loading, and call it
526 * for all dlls that were implicitly loaded already.
528 void wine_dll_set_callback( load_dll_callback_t load )
530 int i;
531 load_dll_callback = load;
532 for (i = 0; i < nb_dlls; i++)
534 const IMAGE_NT_HEADERS *nt = builtin_dlls[i].nt;
535 if (!nt) continue;
536 builtin_dlls[i].nt = NULL;
537 load_dll_callback( map_dll(nt), builtin_dlls[i].filename );
539 nb_dlls = 0;
540 if (main_exe) load_dll_callback( map_dll(main_exe), "" );
544 /***********************************************************************
545 * wine_dll_load
547 * Load a builtin dll.
549 void *wine_dll_load( const char *filename, char *error, int errorsize, int *file_exists )
551 int i;
553 /* callback must have been set already */
554 assert( load_dll_callback );
556 /* check if we have it in the list */
557 /* this can happen when initializing pre-loaded dlls in wine_dll_set_callback */
558 for (i = 0; i < nb_dlls; i++)
560 if (!builtin_dlls[i].nt) continue;
561 if (!strcmp( builtin_dlls[i].filename, filename ))
563 const IMAGE_NT_HEADERS *nt = builtin_dlls[i].nt;
564 builtin_dlls[i].nt = NULL;
565 load_dll_callback( map_dll(nt), builtin_dlls[i].filename );
566 *file_exists = 1;
567 return (void *)1;
570 return dlopen_dll( filename, error, errorsize, 0, file_exists );
574 /***********************************************************************
575 * wine_dll_unload
577 * Unload a builtin dll.
579 void wine_dll_unload( void *handle )
581 if (handle != (void *)1)
582 wine_dlclose( handle, NULL, 0 );
586 /***********************************************************************
587 * wine_dll_load_main_exe
589 * Try to load the .so for the main exe.
591 void *wine_dll_load_main_exe( const char *name, char *error, int errorsize,
592 int test_only, int *file_exists )
594 return dlopen_dll( name, error, errorsize, test_only, file_exists );
598 /***********************************************************************
599 * wine_dll_enum_load_path
601 * Enumerate the dll load path.
603 const char *wine_dll_enum_load_path( unsigned int index )
605 if (index >= nb_dll_paths) return NULL;
606 return dll_paths[index];
610 /***********************************************************************
611 * wine_dll_get_owner
613 * Retrieve the name of the 32-bit owner dll for a 16-bit dll.
614 * Return 0 if OK, -1 on error.
616 int wine_dll_get_owner( const char *name, char *buffer, int size, int *exists )
618 int ret = -1;
619 char *path;
620 struct dll_path_context context;
622 *exists = 0;
624 for (path = first_dll_path( name, 1, &context ); path; path = next_dll_path( &context ))
626 int fd = open( path, O_RDONLY );
627 if (fd != -1)
629 int res = read( fd, buffer, size - 1 );
630 while (res > 0 && (buffer[res-1] == '\n' || buffer[res-1] == '\r')) res--;
631 buffer[res] = 0;
632 close( fd );
633 *exists = 1;
634 ret = 0;
635 break;
638 free_dll_path( &context );
639 return ret;
643 /***********************************************************************
644 * set_max_limit
646 * Set a user limit to the maximum allowed value.
648 static void set_max_limit( int limit )
650 #ifdef HAVE_SETRLIMIT
651 struct rlimit rlimit;
653 if (!getrlimit( limit, &rlimit ))
655 rlimit.rlim_cur = rlimit.rlim_max;
656 if (setrlimit( limit, &rlimit ) != 0)
658 #if defined(__APPLE__) && defined(RLIMIT_NOFILE) && defined(OPEN_MAX)
659 /* On Leopard, setrlimit(RLIMIT_NOFILE, ...) fails on attempts to set
660 * rlim_cur above OPEN_MAX (even if rlim_max > OPEN_MAX). */
661 if (limit == RLIMIT_NOFILE && rlimit.rlim_cur > OPEN_MAX)
663 rlimit.rlim_cur = OPEN_MAX;
664 setrlimit( limit, &rlimit );
666 #endif
669 #endif
673 #ifdef __APPLE__
674 struct apple_stack_info
676 void *stack;
677 size_t desired_size;
680 /***********************************************************************
681 * apple_alloc_thread_stack
683 * Callback for wine_mmap_enum_reserved_areas to allocate space for
684 * the secondary thread's stack.
686 static int apple_alloc_thread_stack( void *base, size_t size, void *arg )
688 struct apple_stack_info *info = arg;
690 /* For mysterious reasons, putting the thread stack at the very top
691 * of the address space causes subsequent execs to fail, even on the
692 * child side of a fork. Avoid the top 16MB. */
693 char * const limit = (char*)0xff000000;
694 if ((char *)base >= limit) return 0;
695 if (size > limit - (char*)base)
696 size = limit - (char*)base;
697 if (size < info->desired_size) return 0;
698 info->stack = wine_anon_mmap( (char *)base + size - info->desired_size,
699 info->desired_size, PROT_READ|PROT_WRITE, MAP_FIXED );
700 return (info->stack != (void *)-1);
703 /***********************************************************************
704 * apple_create_wine_thread
706 * Spin off a secondary thread to complete Wine initialization, leaving
707 * the original thread for the Mac frameworks.
709 * Invoked as a CFRunLoopSource perform callback.
711 static void apple_create_wine_thread( void *init_func )
713 int success = 0;
714 pthread_t thread;
715 pthread_attr_t attr;
717 if (!pthread_attr_init( &attr ))
719 struct apple_stack_info info;
721 /* Try to put the new thread's stack in the reserved area. If this
722 * fails, just let it go wherever. It'll be a waste of space, but we
723 * can go on. */
724 if (!pthread_attr_getstacksize( &attr, &info.desired_size ) &&
725 wine_mmap_enum_reserved_areas( apple_alloc_thread_stack, &info, 1 ))
727 wine_mmap_remove_reserved_area( info.stack, info.desired_size, 0 );
728 pthread_attr_setstackaddr( &attr, (char*)info.stack + info.desired_size );
731 if (!pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE ) &&
732 !pthread_create( &thread, &attr, init_func, NULL ))
733 success = 1;
735 pthread_attr_destroy( &attr );
738 /* Failure is indicated by returning from wine_init(). Stopping
739 * the run loop allows apple_main_thread() and thus wine_init() to
740 * return. */
741 if (!success)
742 CFRunLoopStop( CFRunLoopGetCurrent() );
746 /***********************************************************************
747 * apple_main_thread
749 * Park the process's original thread in a Core Foundation run loop for
750 * use by the Mac frameworks, especially receiving and handling
751 * distributed notifications. Spin off a new thread for the rest of the
752 * Wine initialization.
754 static void apple_main_thread( void (*init_func)(void) )
756 CFRunLoopSourceContext source_context = { 0 };
757 CFRunLoopSourceRef source;
759 /* Give ourselves the best chance of having the distributed notification
760 * center scheduled on this thread's run loop. In theory, it's scheduled
761 * in the first thread to ask for it. */
762 CFNotificationCenterGetDistributedCenter();
764 /* We use this run loop source for two purposes. First, a run loop exits
765 * if it has no more sources scheduled. So, we need at least one source
766 * to keep the run loop running. Second, although it's not critical, it's
767 * preferable for the Wine initialization to not proceed until we know
768 * the run loop is running. So, we signal our source immediately after
769 * adding it and have its callback spin off the Wine thread. */
770 source_context.info = init_func;
771 source_context.perform = apple_create_wine_thread;
772 source = CFRunLoopSourceCreate( NULL, 0, &source_context );
774 if (source)
776 CFRunLoopAddSource( CFRunLoopGetCurrent(), source, kCFRunLoopCommonModes );
777 CFRunLoopSourceSignal( source );
778 CFRelease( source );
780 CFRunLoopRun(); /* Should never return, except on error. */
783 /* If we get here (i.e. return), that indicates failure to our caller. */
785 #endif
788 /***********************************************************************
789 * wine_init
791 * Main Wine initialisation.
793 void wine_init( int argc, char *argv[], char *error, int error_size )
795 struct dll_path_context context;
796 char *path;
797 void *ntdll = NULL;
798 void (*init_func)(void);
800 /* force a few limits that are set too low on some platforms */
801 #ifdef RLIMIT_NOFILE
802 set_max_limit( RLIMIT_NOFILE );
803 #endif
804 #ifdef RLIMIT_AS
805 set_max_limit( RLIMIT_AS );
806 #endif
808 wine_init_argv0_path( argv[0] );
809 build_dll_path();
810 __wine_main_argc = argc;
811 __wine_main_argv = argv;
812 __wine_main_environ = __wine_get_main_environment();
813 mmap_init();
815 for (path = first_dll_path( "ntdll.dll", 0, &context ); path; path = next_dll_path( &context ))
817 if ((ntdll = wine_dlopen( path, RTLD_NOW, error, error_size )))
819 /* if we didn't use the default dll dir, remove it from the search path */
820 if (default_dlldir[0] && context.index < nb_dll_paths + 2) nb_dll_paths--;
821 break;
824 free_dll_path( &context );
826 if (!ntdll) return;
827 if (!(init_func = wine_dlsym( ntdll, "__wine_process_init", error, error_size ))) return;
828 #ifdef __APPLE__
829 apple_main_thread( init_func );
830 #else
831 init_func();
832 #endif
837 * These functions provide wrappers around dlopen() and associated
838 * functions. They work around a bug in glibc 2.1.x where calling
839 * a dl*() function after a previous dl*() function has failed
840 * without a dlerror() call between the two will cause a crash.
841 * They all take a pointer to a buffer that
842 * will receive the error description (from dlerror()). This
843 * parameter may be NULL if the error description is not required.
846 #ifndef RTLD_FIRST
847 #define RTLD_FIRST 0
848 #endif
850 /***********************************************************************
851 * wine_dlopen
853 void *wine_dlopen( const char *filename, int flag, char *error, size_t errorsize )
855 #ifdef HAVE_DLOPEN
856 void *ret;
857 const char *s;
859 #ifdef __APPLE__
860 /* the Mac OS loader pretends to be able to load PE files, so avoid them here */
861 unsigned char magic[2];
862 int fd = open( filename, O_RDONLY );
863 if (fd != -1)
865 if (pread( fd, magic, 2, 0 ) == 2 && magic[0] == 'M' && magic[1] == 'Z')
867 static const char msg[] = "MZ format";
868 size_t len = min( errorsize, sizeof(msg) );
869 memcpy( error, msg, len );
870 error[len - 1] = 0;
871 close( fd );
872 return NULL;
874 close( fd );
876 #endif
877 dlerror(); dlerror();
878 #ifdef __sun
879 if (strchr( filename, ':' ))
881 char path[PATH_MAX];
882 /* Solaris' brain damaged dlopen() treats ':' as a path separator */
883 realpath( filename, path );
884 ret = dlopen( path, flag | RTLD_FIRST );
886 else
887 #endif
888 ret = dlopen( filename, flag | RTLD_FIRST );
889 s = dlerror();
890 if (error && errorsize)
892 if (s)
894 size_t len = strlen(s);
895 if (len >= errorsize) len = errorsize - 1;
896 memcpy( error, s, len );
897 error[len] = 0;
899 else error[0] = 0;
901 dlerror();
902 return ret;
903 #else
904 if (error)
906 static const char msg[] = "dlopen interface not detected by configure";
907 size_t len = min( errorsize, sizeof(msg) );
908 memcpy( error, msg, len );
909 error[len - 1] = 0;
911 return NULL;
912 #endif
915 /***********************************************************************
916 * wine_dlsym
918 void *wine_dlsym( void *handle, const char *symbol, char *error, size_t errorsize )
920 #ifdef HAVE_DLOPEN
921 void *ret;
922 const char *s;
923 dlerror(); dlerror();
924 ret = dlsym( handle, symbol );
925 s = dlerror();
926 if (error && errorsize)
928 if (s)
930 size_t len = strlen(s);
931 if (len >= errorsize) len = errorsize - 1;
932 memcpy( error, s, len );
933 error[len] = 0;
935 else error[0] = 0;
937 dlerror();
938 return ret;
939 #else
940 if (error)
942 static const char msg[] = "dlopen interface not detected by configure";
943 size_t len = min( errorsize, sizeof(msg) );
944 memcpy( error, msg, len );
945 error[len - 1] = 0;
947 return NULL;
948 #endif
951 /***********************************************************************
952 * wine_dlclose
954 int wine_dlclose( void *handle, char *error, size_t errorsize )
956 #ifdef HAVE_DLOPEN
957 int ret;
958 const char *s;
959 dlerror(); dlerror();
960 ret = dlclose( handle );
961 s = dlerror();
962 if (error && errorsize)
964 if (s)
966 size_t len = strlen(s);
967 if (len >= errorsize) len = errorsize - 1;
968 memcpy( error, s, len );
969 error[len] = 0;
971 else error[0] = 0;
973 dlerror();
974 return ret;
975 #else
976 if (error)
978 static const char msg[] = "dlopen interface not detected by configure";
979 size_t len = min( errorsize, sizeof(msg) );
980 memcpy( error, msg, len );
981 error[len - 1] = 0;
983 return 1;
984 #endif