valgrind prevent crash hack
[wine/multimedia.git] / libs / wine / loader.c
blobbc06920327207424a24b8c6f2adce0b8f0c00fe6
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 #ifdef __ANDROID__
57 #include <jni.h>
58 #endif
60 #define NONAMELESSUNION
61 #define NONAMELESSSTRUCT
62 #include "windef.h"
63 #include "winbase.h"
64 #include "wine/library.h"
66 #ifdef HAVE_VALGRIND_MEMCHECK_H
67 #include <valgrind/memcheck.h>
68 #endif
70 /* argc/argv for the Windows application */
71 int __wine_main_argc = 0;
72 char **__wine_main_argv = NULL;
73 WCHAR **__wine_main_wargv = NULL;
74 char **__wine_main_environ = NULL;
76 struct dll_path_context
78 unsigned int index; /* current index in the dll path list */
79 char *buffer; /* buffer used for storing path names */
80 char *name; /* start of file name part in buffer (including leading slash) */
81 int namelen; /* length of file name without .so extension */
82 int win16; /* 16-bit dll search */
85 #define MAX_DLLS 100
87 static struct
89 const IMAGE_NT_HEADERS *nt; /* NT header */
90 const char *filename; /* DLL file name */
91 } builtin_dlls[MAX_DLLS];
93 static int nb_dlls;
95 static const IMAGE_NT_HEADERS *main_exe;
97 static load_dll_callback_t load_dll_callback;
99 static const char *build_dir;
100 static const char *default_dlldir;
101 static const char **dll_paths;
102 static unsigned int nb_dll_paths;
103 static int dll_path_maxlen;
105 extern void mmap_init(void);
106 extern const char *get_dlldir( const char **default_dlldir );
108 /* build the dll load path from the WINEDLLPATH variable */
109 static void build_dll_path(void)
111 int len, count = 0;
112 char *p, *path = getenv( "WINEDLLPATH" );
113 const char *dlldir = get_dlldir( &default_dlldir );
115 if (path)
117 /* count how many path elements we need */
118 path = strdup(path);
119 p = path;
120 while (*p)
122 while (*p == ':') p++;
123 if (!*p) break;
124 count++;
125 while (*p && *p != ':') p++;
129 dll_paths = malloc( (count+2) * sizeof(*dll_paths) );
130 nb_dll_paths = 0;
132 if (dlldir)
134 dll_path_maxlen = strlen(dlldir);
135 dll_paths[nb_dll_paths++] = dlldir;
137 else if ((build_dir = wine_get_build_dir()))
139 dll_path_maxlen = strlen(build_dir) + sizeof("/programs");
142 if (count)
144 p = path;
145 while (*p)
147 while (*p == ':') *p++ = 0;
148 if (!*p) break;
149 dll_paths[nb_dll_paths] = p;
150 while (*p && *p != ':') p++;
151 if (p - dll_paths[nb_dll_paths] > dll_path_maxlen)
152 dll_path_maxlen = p - dll_paths[nb_dll_paths];
153 nb_dll_paths++;
157 /* append default dll dir (if not empty) to path */
158 if ((len = strlen(default_dlldir)) > 0)
160 if (len > dll_path_maxlen) dll_path_maxlen = len;
161 dll_paths[nb_dll_paths++] = default_dlldir;
165 /* check if the library is the correct architecture */
166 /* only returns false for a valid library of the wrong arch */
167 static int check_library_arch( int fd )
169 #ifdef __APPLE__
170 struct /* Mach-O header */
172 unsigned int magic;
173 unsigned int cputype;
174 } header;
176 if (read( fd, &header, sizeof(header) ) != sizeof(header)) return 1;
177 if (header.magic != 0xfeedface) return 1;
178 if (sizeof(void *) == sizeof(int)) return !(header.cputype >> 24);
179 else return (header.cputype >> 24) == 1; /* CPU_ARCH_ABI64 */
180 #else
181 struct /* ELF header */
183 unsigned char magic[4];
184 unsigned char class;
185 unsigned char data;
186 unsigned char version;
187 } header;
189 if (read( fd, &header, sizeof(header) ) != sizeof(header)) return 1;
190 if (memcmp( header.magic, "\177ELF", 4 )) return 1;
191 if (header.version != 1 /* EV_CURRENT */) return 1;
192 #ifdef WORDS_BIGENDIAN
193 if (header.data != 2 /* ELFDATA2MSB */) return 1;
194 #else
195 if (header.data != 1 /* ELFDATA2LSB */) return 1;
196 #endif
197 if (sizeof(void *) == sizeof(int)) return header.class == 1; /* ELFCLASS32 */
198 else return header.class == 2; /* ELFCLASS64 */
199 #endif
202 /* check if a given file can be opened */
203 static inline int file_exists( const char *name )
205 int ret = 0;
206 int fd = open( name, O_RDONLY );
207 if (fd != -1)
209 ret = check_library_arch( fd );
210 close( fd );
212 return ret;
215 static inline char *prepend( char *buffer, const char *str, size_t len )
217 return memcpy( buffer - len, str, len );
220 /* get a filename from the next entry in the dll path */
221 static char *next_dll_path( struct dll_path_context *context )
223 unsigned int index = context->index++;
224 int namelen = context->namelen;
225 char *path = context->name;
227 switch(index)
229 case 0: /* try dlls dir with subdir prefix */
230 if (namelen > 4 && !memcmp( context->name + namelen - 4, ".dll", 4 )) namelen -= 4;
231 if (!context->win16) path = prepend( path, context->name, namelen );
232 path = prepend( path, "/dlls", sizeof("/dlls") - 1 );
233 path = prepend( path, build_dir, strlen(build_dir) );
234 return path;
235 case 1: /* try programs dir with subdir prefix */
236 if (!context->win16)
238 if (namelen > 4 && !memcmp( context->name + namelen - 4, ".exe", 4 )) namelen -= 4;
239 path = prepend( path, context->name, namelen );
240 path = prepend( path, "/programs", sizeof("/programs") - 1 );
241 path = prepend( path, build_dir, strlen(build_dir) );
242 return path;
244 context->index++;
245 /* fall through */
246 default:
247 index -= 2;
248 if (index >= nb_dll_paths) return NULL;
249 path = prepend( path, dll_paths[index], strlen( dll_paths[index] ));
250 return path;
255 /* get a filename from the first entry in the dll path */
256 static char *first_dll_path( const char *name, int win16, struct dll_path_context *context )
258 char *p;
259 int namelen = strlen( name );
260 const char *ext = win16 ? "16" : ".so";
262 context->buffer = malloc( dll_path_maxlen + 2 * namelen + strlen(ext) + 3 );
263 context->index = build_dir ? 0 : 2; /* if no build dir skip all the build dir magic cases */
264 context->name = context->buffer + dll_path_maxlen + namelen + 1;
265 context->namelen = namelen + 1;
266 context->win16 = win16;
268 /* store the name at the end of the buffer, followed by extension */
269 p = context->name;
270 *p++ = '/';
271 memcpy( p, name, namelen );
272 strcpy( p + namelen, ext );
273 return next_dll_path( context );
277 /* free the dll path context created by first_dll_path */
278 static inline void free_dll_path( struct dll_path_context *context )
280 free( context->buffer );
284 /* open a library for a given dll, searching in the dll path
285 * 'name' must be the Windows dll name (e.g. "kernel32.dll") */
286 static void *dlopen_dll( const char *name, char *error, int errorsize,
287 int test_only, int *exists )
289 struct dll_path_context context;
290 char *path;
291 void *ret = NULL;
293 *exists = 0;
294 for (path = first_dll_path( name, 0, &context ); path; path = next_dll_path( &context ))
296 if (!test_only && (ret = wine_dlopen( path, RTLD_NOW, error, errorsize ))) break;
297 if ((*exists = file_exists( path ))) break; /* exists but cannot be loaded, return the error */
299 free_dll_path( &context );
300 return ret;
304 /* adjust an array of pointers to make them into RVAs */
305 static inline void fixup_rva_ptrs( void *array, BYTE *base, unsigned int count )
307 void **src = (void **)array;
308 DWORD *dst = (DWORD *)array;
309 while (count--)
311 *dst++ = *src ? (BYTE *)*src - base : 0;
312 src++;
316 /* fixup an array of RVAs by adding the specified delta */
317 static inline void fixup_rva_dwords( DWORD *ptr, int delta, unsigned int count )
319 while (count--)
321 if (*ptr) *ptr += delta;
322 ptr++;
327 /* fixup RVAs in the import directory */
328 static void fixup_imports( IMAGE_IMPORT_DESCRIPTOR *dir, BYTE *base, int delta )
330 UINT_PTR *ptr;
332 while (dir->Name)
334 fixup_rva_dwords( &dir->u.OriginalFirstThunk, delta, 1 );
335 fixup_rva_dwords( &dir->Name, delta, 1 );
336 fixup_rva_dwords( &dir->FirstThunk, delta, 1 );
337 ptr = (UINT_PTR *)(base + (dir->u.OriginalFirstThunk ? dir->u.OriginalFirstThunk : dir->FirstThunk));
338 while (*ptr)
340 if (!(*ptr & IMAGE_ORDINAL_FLAG)) *ptr += delta;
341 ptr++;
343 dir++;
348 /* fixup RVAs in the export directory */
349 static void fixup_exports( IMAGE_EXPORT_DIRECTORY *dir, BYTE *base, int delta )
351 fixup_rva_dwords( &dir->Name, delta, 1 );
352 fixup_rva_dwords( &dir->AddressOfFunctions, delta, 1 );
353 fixup_rva_dwords( &dir->AddressOfNames, delta, 1 );
354 fixup_rva_dwords( &dir->AddressOfNameOrdinals, delta, 1 );
355 fixup_rva_dwords( (DWORD *)(base + dir->AddressOfNames), delta, dir->NumberOfNames );
356 fixup_rva_ptrs( (base + dir->AddressOfFunctions), base, dir->NumberOfFunctions );
360 /* fixup RVAs in the resource directory */
361 static void fixup_resources( IMAGE_RESOURCE_DIRECTORY *dir, BYTE *root, int delta )
363 IMAGE_RESOURCE_DIRECTORY_ENTRY *entry;
364 int i;
366 entry = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(dir + 1);
367 for (i = 0; i < dir->NumberOfNamedEntries + dir->NumberOfIdEntries; i++, entry++)
369 void *ptr = root + entry->u2.s2.OffsetToDirectory;
370 if (entry->u2.s2.DataIsDirectory) fixup_resources( ptr, root, delta );
371 else
373 IMAGE_RESOURCE_DATA_ENTRY *data = ptr;
374 fixup_rva_dwords( &data->OffsetToData, delta, 1 );
380 /* map a builtin dll in memory and fixup RVAs */
381 static void *map_dll( const IMAGE_NT_HEADERS *nt_descr )
383 #ifdef HAVE_MMAP
384 IMAGE_DATA_DIRECTORY *dir;
385 IMAGE_DOS_HEADER *dos;
386 IMAGE_NT_HEADERS *nt;
387 IMAGE_SECTION_HEADER *sec;
388 BYTE *addr;
389 DWORD code_start, data_start, data_end;
390 const size_t page_size = sysconf( _SC_PAGESIZE );
391 const size_t page_mask = page_size - 1;
392 int delta, nb_sections = 2; /* code + data */
393 unsigned int i;
395 size_t size = (sizeof(IMAGE_DOS_HEADER)
396 + sizeof(IMAGE_NT_HEADERS)
397 + nb_sections * sizeof(IMAGE_SECTION_HEADER));
399 assert( size <= page_size );
401 /* module address must be aligned on 64K boundary */
402 addr = (BYTE *)((nt_descr->OptionalHeader.ImageBase + 0xffff) & ~0xffff);
403 if (wine_anon_mmap( addr, page_size, PROT_READ|PROT_WRITE, MAP_FIXED ) != addr) return NULL;
405 dos = (IMAGE_DOS_HEADER *)addr;
406 nt = (IMAGE_NT_HEADERS *)(dos + 1);
407 sec = (IMAGE_SECTION_HEADER *)(nt + 1);
409 /* Build the DOS and NT headers */
411 dos->e_magic = IMAGE_DOS_SIGNATURE;
412 dos->e_cblp = 0x90;
413 dos->e_cp = 3;
414 dos->e_cparhdr = (sizeof(*dos)+0xf)/0x10;
415 dos->e_minalloc = 0;
416 dos->e_maxalloc = 0xffff;
417 dos->e_ss = 0x0000;
418 dos->e_sp = 0x00b8;
419 dos->e_lfarlc = sizeof(*dos);
420 dos->e_lfanew = sizeof(*dos);
422 *nt = *nt_descr;
424 delta = (const BYTE *)nt_descr - addr;
425 code_start = page_size;
426 data_start = delta & ~page_mask;
427 data_end = (nt->OptionalHeader.SizeOfImage + delta + page_mask) & ~page_mask;
429 fixup_rva_ptrs( &nt->OptionalHeader.AddressOfEntryPoint, addr, 1 );
431 nt->FileHeader.NumberOfSections = nb_sections;
432 nt->OptionalHeader.BaseOfCode = code_start;
433 #ifndef _WIN64
434 nt->OptionalHeader.BaseOfData = data_start;
435 #endif
436 nt->OptionalHeader.SizeOfCode = data_start - code_start;
437 nt->OptionalHeader.SizeOfInitializedData = data_end - data_start;
438 nt->OptionalHeader.SizeOfUninitializedData = 0;
439 nt->OptionalHeader.SizeOfImage = data_end;
440 nt->OptionalHeader.ImageBase = (ULONG_PTR)addr;
442 /* Build the code section */
444 memcpy( sec->Name, ".text", sizeof(".text") );
445 sec->SizeOfRawData = data_start - code_start;
446 sec->Misc.VirtualSize = sec->SizeOfRawData;
447 sec->VirtualAddress = code_start;
448 sec->PointerToRawData = code_start;
449 sec->Characteristics = (IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ);
450 sec++;
452 /* Build the data section */
454 memcpy( sec->Name, ".data", sizeof(".data") );
455 sec->SizeOfRawData = data_end - data_start;
456 sec->Misc.VirtualSize = sec->SizeOfRawData;
457 sec->VirtualAddress = data_start;
458 sec->PointerToRawData = data_start;
459 sec->Characteristics = (IMAGE_SCN_CNT_INITIALIZED_DATA |
460 IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_READ);
461 sec++;
463 for (i = 0; i < nt->OptionalHeader.NumberOfRvaAndSizes; i++)
464 fixup_rva_dwords( &nt->OptionalHeader.DataDirectory[i].VirtualAddress, delta, 1 );
466 /* Build the import directory */
468 dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_IMPORT_DIRECTORY];
469 if (dir->Size)
471 IMAGE_IMPORT_DESCRIPTOR *imports = (void *)(addr + dir->VirtualAddress);
472 fixup_imports( imports, addr, delta );
475 /* Build the resource directory */
477 dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_RESOURCE_DIRECTORY];
478 if (dir->Size)
480 void *ptr = (void *)(addr + dir->VirtualAddress);
481 fixup_resources( ptr, ptr, delta );
484 /* Build the export directory */
486 dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_EXPORT_DIRECTORY];
487 if (dir->Size)
489 IMAGE_EXPORT_DIRECTORY *exports = (void *)(addr + dir->VirtualAddress);
490 fixup_exports( exports, addr, delta );
492 return addr;
493 #else /* HAVE_MMAP */
494 return NULL;
495 #endif /* HAVE_MMAP */
499 /***********************************************************************
500 * __wine_get_main_environment
502 * Return an environment pointer to work around lack of environ variable.
503 * Only exported on Mac OS.
505 char **__wine_get_main_environment(void)
507 return environ;
511 /***********************************************************************
512 * __wine_dll_register
514 * Register a built-in DLL descriptor.
516 void __wine_dll_register( const IMAGE_NT_HEADERS *header, const char *filename )
518 if (load_dll_callback) load_dll_callback( map_dll(header), filename );
519 else
521 if (!(header->FileHeader.Characteristics & IMAGE_FILE_DLL))
522 main_exe = header;
523 else
525 assert( nb_dlls < MAX_DLLS );
526 builtin_dlls[nb_dlls].nt = header;
527 builtin_dlls[nb_dlls].filename = filename;
528 nb_dlls++;
534 /***********************************************************************
535 * wine_dll_set_callback
537 * Set the callback function for dll loading, and call it
538 * for all dlls that were implicitly loaded already.
540 void wine_dll_set_callback( load_dll_callback_t load )
542 int i;
543 load_dll_callback = load;
544 for (i = 0; i < nb_dlls; i++)
546 const IMAGE_NT_HEADERS *nt = builtin_dlls[i].nt;
547 if (!nt) continue;
548 builtin_dlls[i].nt = NULL;
549 load_dll_callback( map_dll(nt), builtin_dlls[i].filename );
551 nb_dlls = 0;
552 if (main_exe) load_dll_callback( map_dll(main_exe), "" );
556 /***********************************************************************
557 * wine_dll_load
559 * Load a builtin dll.
561 void *wine_dll_load( const char *filename, char *error, int errorsize, int *file_exists )
563 int i;
565 /* callback must have been set already */
566 assert( load_dll_callback );
568 /* check if we have it in the list */
569 /* this can happen when initializing pre-loaded dlls in wine_dll_set_callback */
570 for (i = 0; i < nb_dlls; i++)
572 if (!builtin_dlls[i].nt) continue;
573 if (!strcmp( builtin_dlls[i].filename, filename ))
575 const IMAGE_NT_HEADERS *nt = builtin_dlls[i].nt;
576 builtin_dlls[i].nt = NULL;
577 load_dll_callback( map_dll(nt), builtin_dlls[i].filename );
578 *file_exists = 1;
579 return (void *)1;
582 return dlopen_dll( filename, error, errorsize, 0, file_exists );
586 /***********************************************************************
587 * wine_dll_unload
589 * Unload a builtin dll.
591 void wine_dll_unload( void *handle )
593 if (handle != (void *)1)
594 wine_dlclose( handle, NULL, 0 );
598 /***********************************************************************
599 * wine_dll_load_main_exe
601 * Try to load the .so for the main exe.
603 void *wine_dll_load_main_exe( const char *name, char *error, int errorsize,
604 int test_only, int *file_exists )
606 return dlopen_dll( name, error, errorsize, test_only, file_exists );
610 /***********************************************************************
611 * wine_dll_enum_load_path
613 * Enumerate the dll load path.
615 const char *wine_dll_enum_load_path( unsigned int index )
617 if (index >= nb_dll_paths) return NULL;
618 return dll_paths[index];
622 /***********************************************************************
623 * wine_dll_get_owner
625 * Retrieve the name of the 32-bit owner dll for a 16-bit dll.
626 * Return 0 if OK, -1 on error.
628 int wine_dll_get_owner( const char *name, char *buffer, int size, int *exists )
630 int ret = -1;
631 char *path;
632 struct dll_path_context context;
634 *exists = 0;
636 for (path = first_dll_path( name, 1, &context ); path; path = next_dll_path( &context ))
638 int fd = open( path, O_RDONLY );
639 if (fd != -1)
641 int res = read( fd, buffer, size - 1 );
642 while (res > 0 && (buffer[res-1] == '\n' || buffer[res-1] == '\r')) res--;
643 buffer[res] = 0;
644 close( fd );
645 *exists = 1;
646 ret = 0;
647 break;
650 free_dll_path( &context );
651 return ret;
654 /***********************************************************************
655 * set_max_limit
657 * Set a user limit to the maximum allowed value.
659 static void set_max_limit( int limit )
661 #ifdef HAVE_SETRLIMIT
662 struct rlimit rlimit;
664 #if defined(RLIMIT_NOFILE) && defined(RUNNING_ON_VALGRIND)
665 if (limit == RLIMIT_NOFILE && RUNNING_ON_VALGRIND)
666 return;
667 #endif
669 if (!getrlimit( limit, &rlimit ))
671 rlimit.rlim_cur = rlimit.rlim_max;
672 if (setrlimit( limit, &rlimit ) != 0)
674 #if defined(__APPLE__) && defined(RLIMIT_NOFILE) && defined(OPEN_MAX)
675 /* On Leopard, setrlimit(RLIMIT_NOFILE, ...) fails on attempts to set
676 * rlim_cur above OPEN_MAX (even if rlim_max > OPEN_MAX). */
677 if (limit == RLIMIT_NOFILE && rlimit.rlim_cur > OPEN_MAX)
679 rlimit.rlim_cur = OPEN_MAX;
680 setrlimit( limit, &rlimit );
682 #endif
685 #endif
689 #ifdef __APPLE__
690 struct apple_stack_info
692 void *stack;
693 size_t desired_size;
696 /***********************************************************************
697 * apple_alloc_thread_stack
699 * Callback for wine_mmap_enum_reserved_areas to allocate space for
700 * the secondary thread's stack.
702 static int apple_alloc_thread_stack( void *base, size_t size, void *arg )
704 struct apple_stack_info *info = arg;
706 /* For mysterious reasons, putting the thread stack at the very top
707 * of the address space causes subsequent execs to fail, even on the
708 * child side of a fork. Avoid the top 16MB. */
709 char * const limit = (char*)0xff000000;
710 if ((char *)base >= limit) return 0;
711 if (size > limit - (char*)base)
712 size = limit - (char*)base;
713 if (size < info->desired_size) return 0;
714 info->stack = wine_anon_mmap( (char *)base + size - info->desired_size,
715 info->desired_size, PROT_READ|PROT_WRITE, MAP_FIXED );
716 return (info->stack != (void *)-1);
719 /***********************************************************************
720 * apple_create_wine_thread
722 * Spin off a secondary thread to complete Wine initialization, leaving
723 * the original thread for the Mac frameworks.
725 * Invoked as a CFRunLoopSource perform callback.
727 static void apple_create_wine_thread( void *init_func )
729 int success = 0;
730 pthread_t thread;
731 pthread_attr_t attr;
733 if (!pthread_attr_init( &attr ))
735 struct apple_stack_info info;
737 /* Try to put the new thread's stack in the reserved area. If this
738 * fails, just let it go wherever. It'll be a waste of space, but we
739 * can go on. */
740 if (!pthread_attr_getstacksize( &attr, &info.desired_size ) &&
741 wine_mmap_enum_reserved_areas( apple_alloc_thread_stack, &info, 1 ))
743 wine_mmap_remove_reserved_area( info.stack, info.desired_size, 0 );
744 pthread_attr_setstackaddr( &attr, (char*)info.stack + info.desired_size );
747 if (!pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE ) &&
748 !pthread_create( &thread, &attr, init_func, NULL ))
749 success = 1;
751 pthread_attr_destroy( &attr );
754 /* Failure is indicated by returning from wine_init(). Stopping
755 * the run loop allows apple_main_thread() and thus wine_init() to
756 * return. */
757 if (!success)
758 CFRunLoopStop( CFRunLoopGetCurrent() );
762 /***********************************************************************
763 * apple_main_thread
765 * Park the process's original thread in a Core Foundation run loop for
766 * use by the Mac frameworks, especially receiving and handling
767 * distributed notifications. Spin off a new thread for the rest of the
768 * Wine initialization.
770 static void apple_main_thread( void (*init_func)(void) )
772 CFRunLoopSourceContext source_context = { 0 };
773 CFRunLoopSourceRef source;
775 if (!pthread_main_np())
777 init_func();
778 return;
781 /* Multi-processing Services can get confused about the main thread if the
782 * first time it's used is on a secondary thread. Use it here to make sure
783 * that doesn't happen. */
784 MPTaskIsPreemptive(MPCurrentTaskID());
786 /* Give ourselves the best chance of having the distributed notification
787 * center scheduled on this thread's run loop. In theory, it's scheduled
788 * in the first thread to ask for it. */
789 CFNotificationCenterGetDistributedCenter();
791 /* We use this run loop source for two purposes. First, a run loop exits
792 * if it has no more sources scheduled. So, we need at least one source
793 * to keep the run loop running. Second, although it's not critical, it's
794 * preferable for the Wine initialization to not proceed until we know
795 * the run loop is running. So, we signal our source immediately after
796 * adding it and have its callback spin off the Wine thread. */
797 source_context.info = init_func;
798 source_context.perform = apple_create_wine_thread;
799 source = CFRunLoopSourceCreate( NULL, 0, &source_context );
801 if (source)
803 CFRunLoopAddSource( CFRunLoopGetCurrent(), source, kCFRunLoopCommonModes );
804 CFRunLoopSourceSignal( source );
805 CFRelease( source );
807 CFRunLoopRun(); /* Should never return, except on error. */
810 /* If we get here (i.e. return), that indicates failure to our caller. */
812 #endif
815 #ifdef __ANDROID__
817 #ifndef WINE_JAVA_CLASS
818 #define WINE_JAVA_CLASS "org/winehq/wine/WineActivity"
819 #endif
821 static JavaVM *java_vm;
822 static jobject java_object;
824 /* return the Java VM that was used for JNI initialisation */
825 JavaVM *wine_get_java_vm(void)
827 return java_vm;
830 /* return the Java object that called the wine_init method */
831 jobject wine_get_java_object(void)
833 return java_object;
836 /* main Wine initialisation */
837 static jstring wine_init_jni( JNIEnv *env, jobject obj, jobjectArray cmdline, jobjectArray environment )
839 char **argv;
840 char *str;
841 char error[1024];
842 int i, argc, length;
844 /* get the command line array */
846 argc = (*env)->GetArrayLength( env, cmdline );
847 for (i = length = 0; i < argc; i++)
849 jobject str_obj = (*env)->GetObjectArrayElement( env, cmdline, i );
850 length += (*env)->GetStringUTFLength( env, str_obj ) + 1;
853 argv = malloc( (argc + 1) * sizeof(*argv) + length );
854 str = (char *)(argv + argc + 1);
855 for (i = 0; i < argc; i++)
857 jobject str_obj = (*env)->GetObjectArrayElement( env, cmdline, i );
858 length = (*env)->GetStringUTFLength( env, str_obj );
859 (*env)->GetStringUTFRegion( env, str_obj, 0,
860 (*env)->GetStringLength( env, str_obj ), str );
861 argv[i] = str;
862 str[length] = 0;
863 str += length + 1;
865 argv[argc] = NULL;
867 /* set the environment variables */
869 if (environment)
871 int count = (*env)->GetArrayLength( env, environment );
872 for (i = 0; i < count - 1; i += 2)
874 jobject var_obj = (*env)->GetObjectArrayElement( env, environment, i );
875 jobject val_obj = (*env)->GetObjectArrayElement( env, environment, i + 1 );
876 const char *var = (*env)->GetStringUTFChars( env, var_obj, NULL );
878 if (val_obj)
880 const char *val = (*env)->GetStringUTFChars( env, val_obj, NULL );
881 setenv( var, val, 1 );
882 if (!strcmp( var, "LD_LIBRARY_PATH" ))
884 void (*update_func)( const char * ) = dlsym( RTLD_DEFAULT,
885 "android_update_LD_LIBRARY_PATH" );
886 if (update_func) update_func( val );
888 (*env)->ReleaseStringUTFChars( env, val_obj, val );
890 else unsetenv( var );
892 (*env)->ReleaseStringUTFChars( env, var_obj, var );
896 java_object = (*env)->NewGlobalRef( env, obj );
898 wine_init( argc, argv, error, sizeof(error) );
899 return (*env)->NewStringUTF( env, error );
902 jint JNI_OnLoad( JavaVM *vm, void *reserved )
904 static const JNINativeMethod method =
906 "wine_init", "([Ljava/lang/String;[Ljava/lang/String;)Ljava/lang/String;", wine_init_jni
909 JNIEnv *env;
910 jclass class;
912 java_vm = vm;
913 if ((*vm)->AttachCurrentThread( vm, &env, NULL ) != JNI_OK) return JNI_ERR;
914 if (!(class = (*env)->FindClass( env, WINE_JAVA_CLASS ))) return JNI_ERR;
915 (*env)->RegisterNatives( env, class, &method, 1 );
916 return JNI_VERSION_1_6;
919 #endif /* __ANDROID__ */
921 /***********************************************************************
922 * wine_init
924 * Main Wine initialisation.
926 void wine_init( int argc, char *argv[], char *error, int error_size )
928 struct dll_path_context context;
929 char *path;
930 void *ntdll = NULL;
931 void (*init_func)(void);
933 /* force a few limits that are set too low on some platforms */
934 #ifdef RLIMIT_NOFILE
935 set_max_limit( RLIMIT_NOFILE );
936 #endif
937 #ifdef RLIMIT_AS
938 set_max_limit( RLIMIT_AS );
939 #endif
941 wine_init_argv0_path( argv[0] );
942 build_dll_path();
943 __wine_main_argc = argc;
944 __wine_main_argv = argv;
945 __wine_main_environ = __wine_get_main_environment();
946 mmap_init();
948 for (path = first_dll_path( "ntdll.dll", 0, &context ); path; path = next_dll_path( &context ))
950 if ((ntdll = wine_dlopen( path, RTLD_NOW, error, error_size )))
952 /* if we didn't use the default dll dir, remove it from the search path */
953 if (default_dlldir[0] && context.index < nb_dll_paths + 2) nb_dll_paths--;
954 break;
957 free_dll_path( &context );
959 if (!ntdll) return;
960 if (!(init_func = wine_dlsym( ntdll, "__wine_process_init", error, error_size ))) return;
961 #ifdef __APPLE__
962 apple_main_thread( init_func );
963 #else
964 init_func();
965 #endif
970 * These functions provide wrappers around dlopen() and associated
971 * functions. They work around a bug in glibc 2.1.x where calling
972 * a dl*() function after a previous dl*() function has failed
973 * without a dlerror() call between the two will cause a crash.
974 * They all take a pointer to a buffer that
975 * will receive the error description (from dlerror()). This
976 * parameter may be NULL if the error description is not required.
979 #ifndef RTLD_FIRST
980 #define RTLD_FIRST 0
981 #endif
983 /***********************************************************************
984 * wine_dlopen
986 void *wine_dlopen( const char *filename, int flag, char *error, size_t errorsize )
988 #ifdef HAVE_DLOPEN
989 void *ret;
990 const char *s;
992 #ifdef __APPLE__
993 /* the Mac OS loader pretends to be able to load PE files, so avoid them here */
994 unsigned char magic[2];
995 int fd = open( filename, O_RDONLY );
996 if (fd != -1)
998 if (pread( fd, magic, 2, 0 ) == 2 && magic[0] == 'M' && magic[1] == 'Z')
1000 if (error && errorsize)
1002 static const char msg[] = "MZ format";
1003 size_t len = min( errorsize, sizeof(msg) );
1004 memcpy( error, msg, len );
1005 error[len - 1] = 0;
1007 close( fd );
1008 return NULL;
1010 close( fd );
1012 #endif
1013 dlerror(); dlerror();
1014 #ifdef __sun
1015 if (strchr( filename, ':' ))
1017 char path[PATH_MAX];
1018 /* Solaris' brain damaged dlopen() treats ':' as a path separator */
1019 realpath( filename, path );
1020 ret = dlopen( path, flag | RTLD_FIRST );
1022 else
1023 #endif
1024 ret = dlopen( filename, flag | RTLD_FIRST );
1025 s = dlerror();
1026 if (error && errorsize)
1028 if (s)
1030 size_t len = strlen(s);
1031 if (len >= errorsize) len = errorsize - 1;
1032 memcpy( error, s, len );
1033 error[len] = 0;
1035 else error[0] = 0;
1037 dlerror();
1038 return ret;
1039 #else
1040 if (error)
1042 static const char msg[] = "dlopen interface not detected by configure";
1043 size_t len = min( errorsize, sizeof(msg) );
1044 memcpy( error, msg, len );
1045 error[len - 1] = 0;
1047 return NULL;
1048 #endif
1051 /***********************************************************************
1052 * wine_dlsym
1054 void *wine_dlsym( void *handle, const char *symbol, char *error, size_t errorsize )
1056 #ifdef HAVE_DLOPEN
1057 void *ret;
1058 const char *s;
1059 dlerror(); dlerror();
1060 ret = dlsym( handle, symbol );
1061 s = dlerror();
1062 if (error && errorsize)
1064 if (s)
1066 size_t len = strlen(s);
1067 if (len >= errorsize) len = errorsize - 1;
1068 memcpy( error, s, len );
1069 error[len] = 0;
1071 else error[0] = 0;
1073 dlerror();
1074 return ret;
1075 #else
1076 if (error)
1078 static const char msg[] = "dlopen interface not detected by configure";
1079 size_t len = min( errorsize, sizeof(msg) );
1080 memcpy( error, msg, len );
1081 error[len - 1] = 0;
1083 return NULL;
1084 #endif
1087 /***********************************************************************
1088 * wine_dlclose
1090 int wine_dlclose( void *handle, char *error, size_t errorsize )
1092 #ifdef HAVE_DLOPEN
1093 int ret;
1094 const char *s;
1095 dlerror(); dlerror();
1096 ret = dlclose( handle );
1097 s = dlerror();
1098 if (error && errorsize)
1100 if (s)
1102 size_t len = strlen(s);
1103 if (len >= errorsize) len = errorsize - 1;
1104 memcpy( error, s, len );
1105 error[len] = 0;
1107 else error[0] = 0;
1109 dlerror();
1110 return ret;
1111 #else
1112 if (error)
1114 static const char msg[] = "dlopen interface not detected by configure";
1115 size_t len = min( errorsize, sizeof(msg) );
1116 memcpy( error, msg, len );
1117 error[len - 1] = 0;
1119 return 1;
1120 #endif