jscript: Use helpers to access string buffer in object.c.
[wine.git] / libs / wine / loader.c
blob302e9c1a69c61575bfd770bff0e7f8ad108b9527
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 #ifdef __APPLE__
43 #include <crt_externs.h>
44 #define environ (*_NSGetEnviron())
45 #include <CoreFoundation/CoreFoundation.h>
46 #define LoadResource MacLoadResource
47 #define GetCurrentThread MacGetCurrentThread
48 #include <CoreServices/CoreServices.h>
49 #undef LoadResource
50 #undef GetCurrentThread
51 #include <pthread.h>
52 #else
53 extern char **environ;
54 #endif
56 #define NONAMELESSUNION
57 #define NONAMELESSSTRUCT
58 #include "windef.h"
59 #include "winbase.h"
60 #include "wine/library.h"
62 /* argc/argv for the Windows application */
63 int __wine_main_argc = 0;
64 char **__wine_main_argv = NULL;
65 WCHAR **__wine_main_wargv = NULL;
66 char **__wine_main_environ = NULL;
68 struct dll_path_context
70 unsigned int index; /* current index in the dll path list */
71 char *buffer; /* buffer used for storing path names */
72 char *name; /* start of file name part in buffer (including leading slash) */
73 int namelen; /* length of file name without .so extension */
74 int win16; /* 16-bit dll search */
77 #define MAX_DLLS 100
79 static struct
81 const IMAGE_NT_HEADERS *nt; /* NT header */
82 const char *filename; /* DLL file name */
83 } builtin_dlls[MAX_DLLS];
85 static int nb_dlls;
87 static const IMAGE_NT_HEADERS *main_exe;
89 static load_dll_callback_t load_dll_callback;
91 static const char *build_dir;
92 static const char *default_dlldir;
93 static const char **dll_paths;
94 static unsigned int nb_dll_paths;
95 static int dll_path_maxlen;
97 extern void mmap_init(void);
98 extern const char *get_dlldir( const char **default_dlldir );
100 /* build the dll load path from the WINEDLLPATH variable */
101 static void build_dll_path(void)
103 int len, count = 0;
104 char *p, *path = getenv( "WINEDLLPATH" );
105 const char *dlldir = get_dlldir( &default_dlldir );
107 if (path)
109 /* count how many path elements we need */
110 path = strdup(path);
111 p = path;
112 while (*p)
114 while (*p == ':') p++;
115 if (!*p) break;
116 count++;
117 while (*p && *p != ':') p++;
121 dll_paths = malloc( (count+2) * sizeof(*dll_paths) );
122 nb_dll_paths = 0;
124 if (dlldir)
126 dll_path_maxlen = strlen(dlldir);
127 dll_paths[nb_dll_paths++] = dlldir;
129 else if ((build_dir = wine_get_build_dir()))
131 dll_path_maxlen = strlen(build_dir) + sizeof("/programs");
134 if (count)
136 p = path;
137 while (*p)
139 while (*p == ':') *p++ = 0;
140 if (!*p) break;
141 dll_paths[nb_dll_paths] = p;
142 while (*p && *p != ':') p++;
143 if (p - dll_paths[nb_dll_paths] > dll_path_maxlen)
144 dll_path_maxlen = p - dll_paths[nb_dll_paths];
145 nb_dll_paths++;
149 /* append default dll dir (if not empty) to path */
150 if ((len = strlen(default_dlldir)) > 0)
152 if (len > dll_path_maxlen) dll_path_maxlen = len;
153 dll_paths[nb_dll_paths++] = default_dlldir;
157 /* check if the library is the correct architecture */
158 /* only returns false for a valid library of the wrong arch */
159 static int check_library_arch( int fd )
161 #ifdef __APPLE__
162 struct /* Mach-O header */
164 unsigned int magic;
165 unsigned int cputype;
166 } header;
168 if (read( fd, &header, sizeof(header) ) != sizeof(header)) return 1;
169 if (header.magic != 0xfeedface) return 1;
170 if (sizeof(void *) == sizeof(int)) return !(header.cputype >> 24);
171 else return (header.cputype >> 24) == 1; /* CPU_ARCH_ABI64 */
172 #else
173 struct /* ELF header */
175 unsigned char magic[4];
176 unsigned char class;
177 unsigned char data;
178 unsigned char version;
179 } header;
181 if (read( fd, &header, sizeof(header) ) != sizeof(header)) return 1;
182 if (memcmp( header.magic, "\177ELF", 4 )) return 1;
183 if (header.version != 1 /* EV_CURRENT */) return 1;
184 #ifdef WORDS_BIGENDIAN
185 if (header.data != 2 /* ELFDATA2MSB */) return 1;
186 #else
187 if (header.data != 1 /* ELFDATA2LSB */) return 1;
188 #endif
189 if (sizeof(void *) == sizeof(int)) return header.class == 1; /* ELFCLASS32 */
190 else return header.class == 2; /* ELFCLASS64 */
191 #endif
194 /* check if a given file can be opened */
195 static inline int file_exists( const char *name )
197 int ret = 0;
198 int fd = open( name, O_RDONLY );
199 if (fd != -1)
201 ret = check_library_arch( fd );
202 close( fd );
204 return ret;
207 static inline char *prepend( char *buffer, const char *str, size_t len )
209 return memcpy( buffer - len, str, len );
212 /* get a filename from the next entry in the dll path */
213 static char *next_dll_path( struct dll_path_context *context )
215 unsigned int index = context->index++;
216 int namelen = context->namelen;
217 char *path = context->name;
219 switch(index)
221 case 0: /* try dlls dir with subdir prefix */
222 if (namelen > 4 && !memcmp( context->name + namelen - 4, ".dll", 4 )) namelen -= 4;
223 if (!context->win16) path = prepend( path, context->name, namelen );
224 path = prepend( path, "/dlls", sizeof("/dlls") - 1 );
225 path = prepend( path, build_dir, strlen(build_dir) );
226 return path;
227 case 1: /* try programs dir with subdir prefix */
228 if (!context->win16)
230 if (namelen > 4 && !memcmp( context->name + namelen - 4, ".exe", 4 )) namelen -= 4;
231 path = prepend( path, context->name, namelen );
232 path = prepend( path, "/programs", sizeof("/programs") - 1 );
233 path = prepend( path, build_dir, strlen(build_dir) );
234 return path;
236 context->index++;
237 /* fall through */
238 default:
239 index -= 2;
240 if (index < nb_dll_paths)
241 return prepend( context->name, dll_paths[index], strlen( dll_paths[index] ));
242 break;
244 return NULL;
248 /* get a filename from the first entry in the dll path */
249 static char *first_dll_path( const char *name, int win16, struct dll_path_context *context )
251 char *p;
252 int namelen = strlen( name );
253 const char *ext = win16 ? "16" : ".so";
255 context->buffer = malloc( dll_path_maxlen + 2 * namelen + strlen(ext) + 3 );
256 context->index = build_dir ? 0 : 2; /* if no build dir skip all the build dir magic cases */
257 context->name = context->buffer + dll_path_maxlen + namelen + 1;
258 context->namelen = namelen + 1;
259 context->win16 = win16;
261 /* store the name at the end of the buffer, followed by extension */
262 p = context->name;
263 *p++ = '/';
264 memcpy( p, name, namelen );
265 strcpy( p + namelen, ext );
266 return next_dll_path( context );
270 /* free the dll path context created by first_dll_path */
271 static inline void free_dll_path( struct dll_path_context *context )
273 free( context->buffer );
277 /* open a library for a given dll, searching in the dll path
278 * 'name' must be the Windows dll name (e.g. "kernel32.dll") */
279 static void *dlopen_dll( const char *name, char *error, int errorsize,
280 int test_only, int *exists )
282 struct dll_path_context context;
283 char *path;
284 void *ret = NULL;
286 *exists = 0;
287 for (path = first_dll_path( name, 0, &context ); path; path = next_dll_path( &context ))
289 if (!test_only && (ret = wine_dlopen( path, RTLD_NOW, error, errorsize ))) break;
290 if ((*exists = file_exists( path ))) break; /* exists but cannot be loaded, return the error */
292 free_dll_path( &context );
293 return ret;
297 /* adjust an array of pointers to make them into RVAs */
298 static inline void fixup_rva_ptrs( void *array, BYTE *base, unsigned int count )
300 void **src = (void **)array;
301 DWORD *dst = (DWORD *)array;
302 while (count--)
304 *dst++ = *src ? (BYTE *)*src - base : 0;
305 src++;
309 /* fixup an array of RVAs by adding the specified delta */
310 static inline void fixup_rva_dwords( DWORD *ptr, int delta, unsigned int count )
312 while (count--)
314 if (*ptr) *ptr += delta;
315 ptr++;
320 /* fixup RVAs in the import directory */
321 static void fixup_imports( IMAGE_IMPORT_DESCRIPTOR *dir, BYTE *base, int delta )
323 UINT_PTR *ptr;
325 while (dir->Name)
327 fixup_rva_dwords( &dir->u.OriginalFirstThunk, delta, 1 );
328 fixup_rva_dwords( &dir->Name, delta, 1 );
329 fixup_rva_dwords( &dir->FirstThunk, delta, 1 );
330 ptr = (UINT_PTR *)(base + (dir->u.OriginalFirstThunk ? dir->u.OriginalFirstThunk : dir->FirstThunk));
331 while (*ptr)
333 if (!(*ptr & IMAGE_ORDINAL_FLAG)) *ptr += delta;
334 ptr++;
336 dir++;
341 /* fixup RVAs in the export directory */
342 static void fixup_exports( IMAGE_EXPORT_DIRECTORY *dir, BYTE *base, int delta )
344 fixup_rva_dwords( &dir->Name, delta, 1 );
345 fixup_rva_dwords( &dir->AddressOfFunctions, delta, 1 );
346 fixup_rva_dwords( &dir->AddressOfNames, delta, 1 );
347 fixup_rva_dwords( &dir->AddressOfNameOrdinals, delta, 1 );
348 fixup_rva_dwords( (DWORD *)(base + dir->AddressOfNames), delta, dir->NumberOfNames );
349 fixup_rva_ptrs( (base + dir->AddressOfFunctions), base, dir->NumberOfFunctions );
353 /* fixup RVAs in the resource directory */
354 static void fixup_resources( IMAGE_RESOURCE_DIRECTORY *dir, BYTE *root, int delta )
356 IMAGE_RESOURCE_DIRECTORY_ENTRY *entry;
357 int i;
359 entry = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(dir + 1);
360 for (i = 0; i < dir->NumberOfNamedEntries + dir->NumberOfIdEntries; i++, entry++)
362 void *ptr = root + entry->u2.s3.OffsetToDirectory;
363 if (entry->u2.s3.DataIsDirectory) fixup_resources( ptr, root, delta );
364 else
366 IMAGE_RESOURCE_DATA_ENTRY *data = ptr;
367 fixup_rva_dwords( &data->OffsetToData, delta, 1 );
373 /* map a builtin dll in memory and fixup RVAs */
374 static void *map_dll( const IMAGE_NT_HEADERS *nt_descr )
376 #ifdef HAVE_MMAP
377 IMAGE_DATA_DIRECTORY *dir;
378 IMAGE_DOS_HEADER *dos;
379 IMAGE_NT_HEADERS *nt;
380 IMAGE_SECTION_HEADER *sec;
381 BYTE *addr;
382 DWORD code_start, data_start, data_end;
383 const size_t page_size = sysconf( _SC_PAGESIZE );
384 const size_t page_mask = page_size - 1;
385 int delta, nb_sections = 2; /* code + data */
386 unsigned int i;
388 size_t size = (sizeof(IMAGE_DOS_HEADER)
389 + sizeof(IMAGE_NT_HEADERS)
390 + nb_sections * sizeof(IMAGE_SECTION_HEADER));
392 assert( size <= page_size );
394 /* module address must be aligned on 64K boundary */
395 addr = (BYTE *)((nt_descr->OptionalHeader.ImageBase + 0xffff) & ~0xffff);
396 if (wine_anon_mmap( addr, page_size, PROT_READ|PROT_WRITE, MAP_FIXED ) != addr) return NULL;
398 dos = (IMAGE_DOS_HEADER *)addr;
399 nt = (IMAGE_NT_HEADERS *)(dos + 1);
400 sec = (IMAGE_SECTION_HEADER *)(nt + 1);
402 /* Build the DOS and NT headers */
404 dos->e_magic = IMAGE_DOS_SIGNATURE;
405 dos->e_cblp = 0x90;
406 dos->e_cp = 3;
407 dos->e_cparhdr = (sizeof(*dos)+0xf)/0x10;
408 dos->e_minalloc = 0;
409 dos->e_maxalloc = 0xffff;
410 dos->e_ss = 0x0000;
411 dos->e_sp = 0x00b8;
412 dos->e_lfarlc = sizeof(*dos);
413 dos->e_lfanew = sizeof(*dos);
415 *nt = *nt_descr;
417 delta = (const BYTE *)nt_descr - addr;
418 code_start = page_size;
419 data_start = delta & ~page_mask;
420 data_end = (nt->OptionalHeader.SizeOfImage + delta + page_mask) & ~page_mask;
422 fixup_rva_ptrs( &nt->OptionalHeader.AddressOfEntryPoint, addr, 1 );
424 nt->FileHeader.NumberOfSections = nb_sections;
425 nt->OptionalHeader.BaseOfCode = code_start;
426 #ifndef _WIN64
427 nt->OptionalHeader.BaseOfData = data_start;
428 #endif
429 nt->OptionalHeader.SizeOfCode = data_start - code_start;
430 nt->OptionalHeader.SizeOfInitializedData = data_end - data_start;
431 nt->OptionalHeader.SizeOfUninitializedData = 0;
432 nt->OptionalHeader.SizeOfImage = data_end;
433 nt->OptionalHeader.ImageBase = (ULONG_PTR)addr;
435 /* Build the code section */
437 memcpy( sec->Name, ".text", sizeof(".text") );
438 sec->SizeOfRawData = data_start - code_start;
439 sec->Misc.VirtualSize = sec->SizeOfRawData;
440 sec->VirtualAddress = code_start;
441 sec->PointerToRawData = code_start;
442 sec->Characteristics = (IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ);
443 sec++;
445 /* Build the data section */
447 memcpy( sec->Name, ".data", sizeof(".data") );
448 sec->SizeOfRawData = data_end - data_start;
449 sec->Misc.VirtualSize = sec->SizeOfRawData;
450 sec->VirtualAddress = data_start;
451 sec->PointerToRawData = data_start;
452 sec->Characteristics = (IMAGE_SCN_CNT_INITIALIZED_DATA |
453 IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_READ);
454 sec++;
456 for (i = 0; i < nt->OptionalHeader.NumberOfRvaAndSizes; i++)
457 fixup_rva_dwords( &nt->OptionalHeader.DataDirectory[i].VirtualAddress, delta, 1 );
459 /* Build the import directory */
461 dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_IMPORT_DIRECTORY];
462 if (dir->Size)
464 IMAGE_IMPORT_DESCRIPTOR *imports = (void *)(addr + dir->VirtualAddress);
465 fixup_imports( imports, addr, delta );
468 /* Build the resource directory */
470 dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_RESOURCE_DIRECTORY];
471 if (dir->Size)
473 void *ptr = (void *)(addr + dir->VirtualAddress);
474 fixup_resources( ptr, ptr, delta );
477 /* Build the export directory */
479 dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_EXPORT_DIRECTORY];
480 if (dir->Size)
482 IMAGE_EXPORT_DIRECTORY *exports = (void *)(addr + dir->VirtualAddress);
483 fixup_exports( exports, addr, delta );
485 return addr;
486 #else /* HAVE_MMAP */
487 return NULL;
488 #endif /* HAVE_MMAP */
492 /***********************************************************************
493 * __wine_get_main_environment
495 * Return an environment pointer to work around lack of environ variable.
496 * Only exported on Mac OS.
498 char **__wine_get_main_environment(void)
500 return environ;
504 /***********************************************************************
505 * __wine_dll_register
507 * Register a built-in DLL descriptor.
509 void __wine_dll_register( const IMAGE_NT_HEADERS *header, const char *filename )
511 if (load_dll_callback) load_dll_callback( map_dll(header), filename );
512 else
514 if (!(header->FileHeader.Characteristics & IMAGE_FILE_DLL))
515 main_exe = header;
516 else
518 assert( nb_dlls < MAX_DLLS );
519 builtin_dlls[nb_dlls].nt = header;
520 builtin_dlls[nb_dlls].filename = filename;
521 nb_dlls++;
527 /***********************************************************************
528 * wine_dll_set_callback
530 * Set the callback function for dll loading, and call it
531 * for all dlls that were implicitly loaded already.
533 void wine_dll_set_callback( load_dll_callback_t load )
535 int i;
536 load_dll_callback = load;
537 for (i = 0; i < nb_dlls; i++)
539 const IMAGE_NT_HEADERS *nt = builtin_dlls[i].nt;
540 if (!nt) continue;
541 builtin_dlls[i].nt = NULL;
542 load_dll_callback( map_dll(nt), builtin_dlls[i].filename );
544 nb_dlls = 0;
545 if (main_exe) load_dll_callback( map_dll(main_exe), "" );
549 /***********************************************************************
550 * wine_dll_load
552 * Load a builtin dll.
554 void *wine_dll_load( const char *filename, char *error, int errorsize, int *file_exists )
556 int i;
558 /* callback must have been set already */
559 assert( load_dll_callback );
561 /* check if we have it in the list */
562 /* this can happen when initializing pre-loaded dlls in wine_dll_set_callback */
563 for (i = 0; i < nb_dlls; i++)
565 if (!builtin_dlls[i].nt) continue;
566 if (!strcmp( builtin_dlls[i].filename, filename ))
568 const IMAGE_NT_HEADERS *nt = builtin_dlls[i].nt;
569 builtin_dlls[i].nt = NULL;
570 load_dll_callback( map_dll(nt), builtin_dlls[i].filename );
571 *file_exists = 1;
572 return (void *)1;
575 return dlopen_dll( filename, error, errorsize, 0, file_exists );
579 /***********************************************************************
580 * wine_dll_unload
582 * Unload a builtin dll.
584 void wine_dll_unload( void *handle )
586 if (handle != (void *)1)
587 wine_dlclose( handle, NULL, 0 );
591 /***********************************************************************
592 * wine_dll_load_main_exe
594 * Try to load the .so for the main exe.
596 void *wine_dll_load_main_exe( const char *name, char *error, int errorsize,
597 int test_only, int *file_exists )
599 return dlopen_dll( name, error, errorsize, test_only, file_exists );
603 /***********************************************************************
604 * wine_dll_enum_load_path
606 * Enumerate the dll load path.
608 const char *wine_dll_enum_load_path( unsigned int index )
610 if (index >= nb_dll_paths) return NULL;
611 return dll_paths[index];
615 /***********************************************************************
616 * wine_dll_get_owner
618 * Retrieve the name of the 32-bit owner dll for a 16-bit dll.
619 * Return 0 if OK, -1 on error.
621 int wine_dll_get_owner( const char *name, char *buffer, int size, int *exists )
623 int ret = -1;
624 char *path;
625 struct dll_path_context context;
627 *exists = 0;
629 for (path = first_dll_path( name, 1, &context ); path; path = next_dll_path( &context ))
631 int fd = open( path, O_RDONLY );
632 if (fd != -1)
634 int res = read( fd, buffer, size - 1 );
635 while (res > 0 && (buffer[res-1] == '\n' || buffer[res-1] == '\r')) res--;
636 buffer[res] = 0;
637 close( fd );
638 *exists = 1;
639 ret = 0;
640 break;
643 free_dll_path( &context );
644 return ret;
648 /***********************************************************************
649 * set_max_limit
651 * Set a user limit to the maximum allowed value.
653 static void set_max_limit( int limit )
655 #ifdef HAVE_SETRLIMIT
656 struct rlimit rlimit;
658 if (!getrlimit( limit, &rlimit ))
660 rlimit.rlim_cur = rlimit.rlim_max;
661 if (setrlimit( limit, &rlimit ) != 0)
663 #if defined(__APPLE__) && defined(RLIMIT_NOFILE) && defined(OPEN_MAX)
664 /* On Leopard, setrlimit(RLIMIT_NOFILE, ...) fails on attempts to set
665 * rlim_cur above OPEN_MAX (even if rlim_max > OPEN_MAX). */
666 if (limit == RLIMIT_NOFILE && rlimit.rlim_cur > OPEN_MAX)
668 rlimit.rlim_cur = OPEN_MAX;
669 setrlimit( limit, &rlimit );
671 #endif
674 #endif
678 #ifdef __APPLE__
679 struct apple_stack_info
681 void *stack;
682 size_t desired_size;
685 /***********************************************************************
686 * apple_alloc_thread_stack
688 * Callback for wine_mmap_enum_reserved_areas to allocate space for
689 * the secondary thread's stack.
691 static int apple_alloc_thread_stack( void *base, size_t size, void *arg )
693 struct apple_stack_info *info = arg;
695 /* For mysterious reasons, putting the thread stack at the very top
696 * of the address space causes subsequent execs to fail, even on the
697 * child side of a fork. Avoid the top 16MB. */
698 char * const limit = (char*)0xff000000;
699 if ((char *)base >= limit) return 0;
700 if (size > limit - (char*)base)
701 size = limit - (char*)base;
702 if (size < info->desired_size) return 0;
703 info->stack = wine_anon_mmap( (char *)base + size - info->desired_size,
704 info->desired_size, PROT_READ|PROT_WRITE, MAP_FIXED );
705 return (info->stack != (void *)-1);
708 /***********************************************************************
709 * apple_create_wine_thread
711 * Spin off a secondary thread to complete Wine initialization, leaving
712 * the original thread for the Mac frameworks.
714 * Invoked as a CFRunLoopSource perform callback.
716 static void apple_create_wine_thread( void *init_func )
718 int success = 0;
719 pthread_t thread;
720 pthread_attr_t attr;
722 if (!pthread_attr_init( &attr ))
724 struct apple_stack_info info;
726 /* Try to put the new thread's stack in the reserved area. If this
727 * fails, just let it go wherever. It'll be a waste of space, but we
728 * can go on. */
729 if (!pthread_attr_getstacksize( &attr, &info.desired_size ) &&
730 wine_mmap_enum_reserved_areas( apple_alloc_thread_stack, &info, 1 ))
732 wine_mmap_remove_reserved_area( info.stack, info.desired_size, 0 );
733 pthread_attr_setstackaddr( &attr, (char*)info.stack + info.desired_size );
736 if (!pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE ) &&
737 !pthread_create( &thread, &attr, init_func, NULL ))
738 success = 1;
740 pthread_attr_destroy( &attr );
743 /* Failure is indicated by returning from wine_init(). Stopping
744 * the run loop allows apple_main_thread() and thus wine_init() to
745 * return. */
746 if (!success)
747 CFRunLoopStop( CFRunLoopGetCurrent() );
751 /***********************************************************************
752 * apple_main_thread
754 * Park the process's original thread in a Core Foundation run loop for
755 * use by the Mac frameworks, especially receiving and handling
756 * distributed notifications. Spin off a new thread for the rest of the
757 * Wine initialization.
759 static void apple_main_thread( void (*init_func)(void) )
761 CFRunLoopSourceContext source_context = { 0 };
762 CFRunLoopSourceRef source;
764 /* Multi-processing Services can get confused about the main thread if the
765 * first time it's used is on a secondary thread. Use it here to make sure
766 * that doesn't happen. */
767 MPTaskIsPreemptive(MPCurrentTaskID());
769 /* Give ourselves the best chance of having the distributed notification
770 * center scheduled on this thread's run loop. In theory, it's scheduled
771 * in the first thread to ask for it. */
772 CFNotificationCenterGetDistributedCenter();
774 /* We use this run loop source for two purposes. First, a run loop exits
775 * if it has no more sources scheduled. So, we need at least one source
776 * to keep the run loop running. Second, although it's not critical, it's
777 * preferable for the Wine initialization to not proceed until we know
778 * the run loop is running. So, we signal our source immediately after
779 * adding it and have its callback spin off the Wine thread. */
780 source_context.info = init_func;
781 source_context.perform = apple_create_wine_thread;
782 source = CFRunLoopSourceCreate( NULL, 0, &source_context );
784 if (source)
786 CFRunLoopAddSource( CFRunLoopGetCurrent(), source, kCFRunLoopCommonModes );
787 CFRunLoopSourceSignal( source );
788 CFRelease( source );
790 CFRunLoopRun(); /* Should never return, except on error. */
793 /* If we get here (i.e. return), that indicates failure to our caller. */
795 #endif
798 /***********************************************************************
799 * wine_init
801 * Main Wine initialisation.
803 void wine_init( int argc, char *argv[], char *error, int error_size )
805 struct dll_path_context context;
806 char *path;
807 void *ntdll = NULL;
808 void (*init_func)(void);
810 /* force a few limits that are set too low on some platforms */
811 #ifdef RLIMIT_NOFILE
812 set_max_limit( RLIMIT_NOFILE );
813 #endif
814 #ifdef RLIMIT_AS
815 set_max_limit( RLIMIT_AS );
816 #endif
818 wine_init_argv0_path( argv[0] );
819 build_dll_path();
820 __wine_main_argc = argc;
821 __wine_main_argv = argv;
822 __wine_main_environ = __wine_get_main_environment();
823 mmap_init();
825 for (path = first_dll_path( "ntdll.dll", 0, &context ); path; path = next_dll_path( &context ))
827 if ((ntdll = wine_dlopen( path, RTLD_NOW, error, error_size )))
829 /* if we didn't use the default dll dir, remove it from the search path */
830 if (default_dlldir[0] && context.index < nb_dll_paths + 2) nb_dll_paths--;
831 break;
834 free_dll_path( &context );
836 if (!ntdll) return;
837 if (!(init_func = wine_dlsym( ntdll, "__wine_process_init", error, error_size ))) return;
838 #ifdef __APPLE__
839 apple_main_thread( init_func );
840 #else
841 init_func();
842 #endif
847 * These functions provide wrappers around dlopen() and associated
848 * functions. They work around a bug in glibc 2.1.x where calling
849 * a dl*() function after a previous dl*() function has failed
850 * without a dlerror() call between the two will cause a crash.
851 * They all take a pointer to a buffer that
852 * will receive the error description (from dlerror()). This
853 * parameter may be NULL if the error description is not required.
856 #ifndef RTLD_FIRST
857 #define RTLD_FIRST 0
858 #endif
860 /***********************************************************************
861 * wine_dlopen
863 void *wine_dlopen( const char *filename, int flag, char *error, size_t errorsize )
865 #ifdef HAVE_DLOPEN
866 void *ret;
867 const char *s;
869 #ifdef __APPLE__
870 /* the Mac OS loader pretends to be able to load PE files, so avoid them here */
871 unsigned char magic[2];
872 int fd = open( filename, O_RDONLY );
873 if (fd != -1)
875 if (pread( fd, magic, 2, 0 ) == 2 && magic[0] == 'M' && magic[1] == 'Z')
877 static const char msg[] = "MZ format";
878 size_t len = min( errorsize, sizeof(msg) );
879 memcpy( error, msg, len );
880 error[len - 1] = 0;
881 close( fd );
882 return NULL;
884 close( fd );
886 #endif
887 dlerror(); dlerror();
888 #ifdef __sun
889 if (strchr( filename, ':' ))
891 char path[PATH_MAX];
892 /* Solaris' brain damaged dlopen() treats ':' as a path separator */
893 realpath( filename, path );
894 ret = dlopen( path, flag | RTLD_FIRST );
896 else
897 #endif
898 ret = dlopen( filename, flag | RTLD_FIRST );
899 s = dlerror();
900 if (error && errorsize)
902 if (s)
904 size_t len = strlen(s);
905 if (len >= errorsize) len = errorsize - 1;
906 memcpy( error, s, len );
907 error[len] = 0;
909 else error[0] = 0;
911 dlerror();
912 return ret;
913 #else
914 if (error)
916 static const char msg[] = "dlopen interface not detected by configure";
917 size_t len = min( errorsize, sizeof(msg) );
918 memcpy( error, msg, len );
919 error[len - 1] = 0;
921 return NULL;
922 #endif
925 /***********************************************************************
926 * wine_dlsym
928 void *wine_dlsym( void *handle, const char *symbol, char *error, size_t errorsize )
930 #ifdef HAVE_DLOPEN
931 void *ret;
932 const char *s;
933 dlerror(); dlerror();
934 ret = dlsym( handle, symbol );
935 s = dlerror();
936 if (error && errorsize)
938 if (s)
940 size_t len = strlen(s);
941 if (len >= errorsize) len = errorsize - 1;
942 memcpy( error, s, len );
943 error[len] = 0;
945 else error[0] = 0;
947 dlerror();
948 return ret;
949 #else
950 if (error)
952 static const char msg[] = "dlopen interface not detected by configure";
953 size_t len = min( errorsize, sizeof(msg) );
954 memcpy( error, msg, len );
955 error[len - 1] = 0;
957 return NULL;
958 #endif
961 /***********************************************************************
962 * wine_dlclose
964 int wine_dlclose( void *handle, char *error, size_t errorsize )
966 #ifdef HAVE_DLOPEN
967 int ret;
968 const char *s;
969 dlerror(); dlerror();
970 ret = dlclose( handle );
971 s = dlerror();
972 if (error && errorsize)
974 if (s)
976 size_t len = strlen(s);
977 if (len >= errorsize) len = errorsize - 1;
978 memcpy( error, s, len );
979 error[len] = 0;
981 else error[0] = 0;
983 dlerror();
984 return ret;
985 #else
986 if (error)
988 static const char msg[] = "dlopen interface not detected by configure";
989 size_t len = min( errorsize, sizeof(msg) );
990 memcpy( error, msg, len );
991 error[len - 1] = 0;
993 return 1;
994 #endif