TESTING -- override pthreads to fix gstreamer v5
[wine/multimedia.git] / libs / wine / loader.c
blob82fbd740dba50ae260d67187165aa457093478f0
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 #ifdef __linux__
77 #include <pthread.h>
78 typeof(pthread_create) *call_pthread_create, *__glob_pthread_create;
79 typeof(pthread_join) *call_pthread_join, *__glob_pthread_join;
80 typeof(pthread_detach) *call_pthread_detach, *__glob_pthread_detach;
81 #endif
83 struct dll_path_context
85 unsigned int index; /* current index in the dll path list */
86 char *buffer; /* buffer used for storing path names */
87 char *name; /* start of file name part in buffer (including leading slash) */
88 int namelen; /* length of file name without .so extension */
89 int win16; /* 16-bit dll search */
92 #define MAX_DLLS 100
94 static struct
96 const IMAGE_NT_HEADERS *nt; /* NT header */
97 const char *filename; /* DLL file name */
98 } builtin_dlls[MAX_DLLS];
100 static int nb_dlls;
102 static const IMAGE_NT_HEADERS *main_exe;
104 static load_dll_callback_t load_dll_callback;
106 static const char *build_dir;
107 static const char *default_dlldir;
108 static const char **dll_paths;
109 static unsigned int nb_dll_paths;
110 static int dll_path_maxlen;
112 extern void mmap_init(void);
113 extern const char *get_dlldir( const char **default_dlldir );
115 /* build the dll load path from the WINEDLLPATH variable */
116 static void build_dll_path(void)
118 int len, count = 0;
119 char *p, *path = getenv( "WINEDLLPATH" );
120 const char *dlldir = get_dlldir( &default_dlldir );
122 if (path)
124 /* count how many path elements we need */
125 path = strdup(path);
126 p = path;
127 while (*p)
129 while (*p == ':') p++;
130 if (!*p) break;
131 count++;
132 while (*p && *p != ':') p++;
136 dll_paths = malloc( (count+2) * sizeof(*dll_paths) );
137 nb_dll_paths = 0;
139 if (dlldir)
141 dll_path_maxlen = strlen(dlldir);
142 dll_paths[nb_dll_paths++] = dlldir;
144 else if ((build_dir = wine_get_build_dir()))
146 dll_path_maxlen = strlen(build_dir) + sizeof("/programs");
149 if (count)
151 p = path;
152 while (*p)
154 while (*p == ':') *p++ = 0;
155 if (!*p) break;
156 dll_paths[nb_dll_paths] = p;
157 while (*p && *p != ':') p++;
158 if (p - dll_paths[nb_dll_paths] > dll_path_maxlen)
159 dll_path_maxlen = p - dll_paths[nb_dll_paths];
160 nb_dll_paths++;
164 /* append default dll dir (if not empty) to path */
165 if ((len = strlen(default_dlldir)) > 0)
167 if (len > dll_path_maxlen) dll_path_maxlen = len;
168 dll_paths[nb_dll_paths++] = default_dlldir;
172 /* check if the library is the correct architecture */
173 /* only returns false for a valid library of the wrong arch */
174 static int check_library_arch( int fd )
176 #ifdef __APPLE__
177 struct /* Mach-O header */
179 unsigned int magic;
180 unsigned int cputype;
181 } header;
183 if (read( fd, &header, sizeof(header) ) != sizeof(header)) return 1;
184 if (header.magic != 0xfeedface) return 1;
185 if (sizeof(void *) == sizeof(int)) return !(header.cputype >> 24);
186 else return (header.cputype >> 24) == 1; /* CPU_ARCH_ABI64 */
187 #else
188 struct /* ELF header */
190 unsigned char magic[4];
191 unsigned char class;
192 unsigned char data;
193 unsigned char version;
194 } header;
196 if (read( fd, &header, sizeof(header) ) != sizeof(header)) return 1;
197 if (memcmp( header.magic, "\177ELF", 4 )) return 1;
198 if (header.version != 1 /* EV_CURRENT */) return 1;
199 #ifdef WORDS_BIGENDIAN
200 if (header.data != 2 /* ELFDATA2MSB */) return 1;
201 #else
202 if (header.data != 1 /* ELFDATA2LSB */) return 1;
203 #endif
204 if (sizeof(void *) == sizeof(int)) return header.class == 1; /* ELFCLASS32 */
205 else return header.class == 2; /* ELFCLASS64 */
206 #endif
209 /* check if a given file can be opened */
210 static inline int file_exists( const char *name )
212 int ret = 0;
213 int fd = open( name, O_RDONLY );
214 if (fd != -1)
216 ret = check_library_arch( fd );
217 close( fd );
219 return ret;
222 static inline char *prepend( char *buffer, const char *str, size_t len )
224 return memcpy( buffer - len, str, len );
227 /* get a filename from the next entry in the dll path */
228 static char *next_dll_path( struct dll_path_context *context )
230 unsigned int index = context->index++;
231 int namelen = context->namelen;
232 char *path = context->name;
234 switch(index)
236 case 0: /* try dlls dir with subdir prefix */
237 if (namelen > 4 && !memcmp( context->name + namelen - 4, ".dll", 4 )) namelen -= 4;
238 if (!context->win16) path = prepend( path, context->name, namelen );
239 path = prepend( path, "/dlls", sizeof("/dlls") - 1 );
240 path = prepend( path, build_dir, strlen(build_dir) );
241 return path;
242 case 1: /* try programs dir with subdir prefix */
243 if (!context->win16)
245 if (namelen > 4 && !memcmp( context->name + namelen - 4, ".exe", 4 )) namelen -= 4;
246 path = prepend( path, context->name, namelen );
247 path = prepend( path, "/programs", sizeof("/programs") - 1 );
248 path = prepend( path, build_dir, strlen(build_dir) );
249 return path;
251 context->index++;
252 /* fall through */
253 default:
254 index -= 2;
255 if (index >= nb_dll_paths) return NULL;
256 path = prepend( path, dll_paths[index], strlen( dll_paths[index] ));
257 return path;
262 /* get a filename from the first entry in the dll path */
263 static char *first_dll_path( const char *name, int win16, struct dll_path_context *context )
265 char *p;
266 int namelen = strlen( name );
267 const char *ext = win16 ? "16" : ".so";
269 context->buffer = malloc( dll_path_maxlen + 2 * namelen + strlen(ext) + 3 );
270 context->index = build_dir ? 0 : 2; /* if no build dir skip all the build dir magic cases */
271 context->name = context->buffer + dll_path_maxlen + namelen + 1;
272 context->namelen = namelen + 1;
273 context->win16 = win16;
275 /* store the name at the end of the buffer, followed by extension */
276 p = context->name;
277 *p++ = '/';
278 memcpy( p, name, namelen );
279 strcpy( p + namelen, ext );
280 return next_dll_path( context );
284 /* free the dll path context created by first_dll_path */
285 static inline void free_dll_path( struct dll_path_context *context )
287 free( context->buffer );
291 /* open a library for a given dll, searching in the dll path
292 * 'name' must be the Windows dll name (e.g. "kernel32.dll") */
293 static void *dlopen_dll( const char *name, char *error, int errorsize,
294 int test_only, int *exists )
296 struct dll_path_context context;
297 char *path;
298 void *ret = NULL;
300 *exists = 0;
301 for (path = first_dll_path( name, 0, &context ); path; path = next_dll_path( &context ))
303 if (!test_only && (ret = wine_dlopen( path, RTLD_NOW, error, errorsize ))) break;
304 if ((*exists = file_exists( path ))) break; /* exists but cannot be loaded, return the error */
306 free_dll_path( &context );
307 return ret;
311 /* adjust an array of pointers to make them into RVAs */
312 static inline void fixup_rva_ptrs( void *array, BYTE *base, unsigned int count )
314 void **src = (void **)array;
315 DWORD *dst = (DWORD *)array;
316 while (count--)
318 *dst++ = *src ? (BYTE *)*src - base : 0;
319 src++;
323 /* fixup an array of RVAs by adding the specified delta */
324 static inline void fixup_rva_dwords( DWORD *ptr, int delta, unsigned int count )
326 while (count--)
328 if (*ptr) *ptr += delta;
329 ptr++;
334 /* fixup RVAs in the import directory */
335 static void fixup_imports( IMAGE_IMPORT_DESCRIPTOR *dir, BYTE *base, int delta )
337 UINT_PTR *ptr;
339 while (dir->Name)
341 fixup_rva_dwords( &dir->u.OriginalFirstThunk, delta, 1 );
342 fixup_rva_dwords( &dir->Name, delta, 1 );
343 fixup_rva_dwords( &dir->FirstThunk, delta, 1 );
344 ptr = (UINT_PTR *)(base + (dir->u.OriginalFirstThunk ? dir->u.OriginalFirstThunk : dir->FirstThunk));
345 while (*ptr)
347 if (!(*ptr & IMAGE_ORDINAL_FLAG)) *ptr += delta;
348 ptr++;
350 dir++;
355 /* fixup RVAs in the export directory */
356 static void fixup_exports( IMAGE_EXPORT_DIRECTORY *dir, BYTE *base, int delta )
358 fixup_rva_dwords( &dir->Name, delta, 1 );
359 fixup_rva_dwords( &dir->AddressOfFunctions, delta, 1 );
360 fixup_rva_dwords( &dir->AddressOfNames, delta, 1 );
361 fixup_rva_dwords( &dir->AddressOfNameOrdinals, delta, 1 );
362 fixup_rva_dwords( (DWORD *)(base + dir->AddressOfNames), delta, dir->NumberOfNames );
363 fixup_rva_ptrs( (base + dir->AddressOfFunctions), base, dir->NumberOfFunctions );
367 /* fixup RVAs in the resource directory */
368 static void fixup_resources( IMAGE_RESOURCE_DIRECTORY *dir, BYTE *root, int delta )
370 IMAGE_RESOURCE_DIRECTORY_ENTRY *entry;
371 int i;
373 entry = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(dir + 1);
374 for (i = 0; i < dir->NumberOfNamedEntries + dir->NumberOfIdEntries; i++, entry++)
376 void *ptr = root + entry->u2.s2.OffsetToDirectory;
377 if (entry->u2.s2.DataIsDirectory) fixup_resources( ptr, root, delta );
378 else
380 IMAGE_RESOURCE_DATA_ENTRY *data = ptr;
381 fixup_rva_dwords( &data->OffsetToData, delta, 1 );
387 /* map a builtin dll in memory and fixup RVAs */
388 static void *map_dll( const IMAGE_NT_HEADERS *nt_descr )
390 #ifdef HAVE_MMAP
391 IMAGE_DATA_DIRECTORY *dir;
392 IMAGE_DOS_HEADER *dos;
393 IMAGE_NT_HEADERS *nt;
394 IMAGE_SECTION_HEADER *sec;
395 BYTE *addr;
396 DWORD code_start, data_start, data_end;
397 const size_t page_size = sysconf( _SC_PAGESIZE );
398 const size_t page_mask = page_size - 1;
399 int delta, nb_sections = 2; /* code + data */
400 unsigned int i;
402 size_t size = (sizeof(IMAGE_DOS_HEADER)
403 + sizeof(IMAGE_NT_HEADERS)
404 + nb_sections * sizeof(IMAGE_SECTION_HEADER));
406 assert( size <= page_size );
408 /* module address must be aligned on 64K boundary */
409 addr = (BYTE *)((nt_descr->OptionalHeader.ImageBase + 0xffff) & ~0xffff);
410 if (wine_anon_mmap( addr, page_size, PROT_READ|PROT_WRITE, MAP_FIXED ) != addr) return NULL;
412 dos = (IMAGE_DOS_HEADER *)addr;
413 nt = (IMAGE_NT_HEADERS *)(dos + 1);
414 sec = (IMAGE_SECTION_HEADER *)(nt + 1);
416 /* Build the DOS and NT headers */
418 dos->e_magic = IMAGE_DOS_SIGNATURE;
419 dos->e_cblp = 0x90;
420 dos->e_cp = 3;
421 dos->e_cparhdr = (sizeof(*dos)+0xf)/0x10;
422 dos->e_minalloc = 0;
423 dos->e_maxalloc = 0xffff;
424 dos->e_ss = 0x0000;
425 dos->e_sp = 0x00b8;
426 dos->e_lfarlc = sizeof(*dos);
427 dos->e_lfanew = sizeof(*dos);
429 *nt = *nt_descr;
431 delta = (const BYTE *)nt_descr - addr;
432 code_start = page_size;
433 data_start = delta & ~page_mask;
434 data_end = (nt->OptionalHeader.SizeOfImage + delta + page_mask) & ~page_mask;
436 fixup_rva_ptrs( &nt->OptionalHeader.AddressOfEntryPoint, addr, 1 );
438 nt->FileHeader.NumberOfSections = nb_sections;
439 nt->OptionalHeader.BaseOfCode = code_start;
440 #ifndef _WIN64
441 nt->OptionalHeader.BaseOfData = data_start;
442 #endif
443 nt->OptionalHeader.SizeOfCode = data_start - code_start;
444 nt->OptionalHeader.SizeOfInitializedData = data_end - data_start;
445 nt->OptionalHeader.SizeOfUninitializedData = 0;
446 nt->OptionalHeader.SizeOfImage = data_end;
447 nt->OptionalHeader.ImageBase = (ULONG_PTR)addr;
449 /* Build the code section */
451 memcpy( sec->Name, ".text", sizeof(".text") );
452 sec->SizeOfRawData = data_start - code_start;
453 sec->Misc.VirtualSize = sec->SizeOfRawData;
454 sec->VirtualAddress = code_start;
455 sec->PointerToRawData = code_start;
456 sec->Characteristics = (IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ);
457 sec++;
459 /* Build the data section */
461 memcpy( sec->Name, ".data", sizeof(".data") );
462 sec->SizeOfRawData = data_end - data_start;
463 sec->Misc.VirtualSize = sec->SizeOfRawData;
464 sec->VirtualAddress = data_start;
465 sec->PointerToRawData = data_start;
466 sec->Characteristics = (IMAGE_SCN_CNT_INITIALIZED_DATA |
467 IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_READ);
468 sec++;
470 for (i = 0; i < nt->OptionalHeader.NumberOfRvaAndSizes; i++)
471 fixup_rva_dwords( &nt->OptionalHeader.DataDirectory[i].VirtualAddress, delta, 1 );
473 /* Build the import directory */
475 dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_IMPORT_DIRECTORY];
476 if (dir->Size)
478 IMAGE_IMPORT_DESCRIPTOR *imports = (void *)(addr + dir->VirtualAddress);
479 fixup_imports( imports, addr, delta );
482 /* Build the resource directory */
484 dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_RESOURCE_DIRECTORY];
485 if (dir->Size)
487 void *ptr = (void *)(addr + dir->VirtualAddress);
488 fixup_resources( ptr, ptr, delta );
491 /* Build the export directory */
493 dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_EXPORT_DIRECTORY];
494 if (dir->Size)
496 IMAGE_EXPORT_DIRECTORY *exports = (void *)(addr + dir->VirtualAddress);
497 fixup_exports( exports, addr, delta );
499 return addr;
500 #else /* HAVE_MMAP */
501 return NULL;
502 #endif /* HAVE_MMAP */
506 /***********************************************************************
507 * __wine_get_main_environment
509 * Return an environment pointer to work around lack of environ variable.
510 * Only exported on Mac OS.
512 char **__wine_get_main_environment(void)
514 return environ;
518 /***********************************************************************
519 * __wine_dll_register
521 * Register a built-in DLL descriptor.
523 void __wine_dll_register( const IMAGE_NT_HEADERS *header, const char *filename )
525 if (load_dll_callback) load_dll_callback( map_dll(header), filename );
526 else
528 if (!(header->FileHeader.Characteristics & IMAGE_FILE_DLL))
529 main_exe = header;
530 else
532 assert( nb_dlls < MAX_DLLS );
533 builtin_dlls[nb_dlls].nt = header;
534 builtin_dlls[nb_dlls].filename = filename;
535 nb_dlls++;
541 /***********************************************************************
542 * wine_dll_set_callback
544 * Set the callback function for dll loading, and call it
545 * for all dlls that were implicitly loaded already.
547 void wine_dll_set_callback( load_dll_callback_t load )
549 int i;
550 load_dll_callback = load;
551 for (i = 0; i < nb_dlls; i++)
553 const IMAGE_NT_HEADERS *nt = builtin_dlls[i].nt;
554 if (!nt) continue;
555 builtin_dlls[i].nt = NULL;
556 load_dll_callback( map_dll(nt), builtin_dlls[i].filename );
558 nb_dlls = 0;
559 if (main_exe) load_dll_callback( map_dll(main_exe), "" );
563 /***********************************************************************
564 * wine_dll_load
566 * Load a builtin dll.
568 void *wine_dll_load( const char *filename, char *error, int errorsize, int *file_exists )
570 int i;
572 /* callback must have been set already */
573 assert( load_dll_callback );
575 /* check if we have it in the list */
576 /* this can happen when initializing pre-loaded dlls in wine_dll_set_callback */
577 for (i = 0; i < nb_dlls; i++)
579 if (!builtin_dlls[i].nt) continue;
580 if (!strcmp( builtin_dlls[i].filename, filename ))
582 const IMAGE_NT_HEADERS *nt = builtin_dlls[i].nt;
583 builtin_dlls[i].nt = NULL;
584 load_dll_callback( map_dll(nt), builtin_dlls[i].filename );
585 *file_exists = 1;
586 return (void *)1;
589 return dlopen_dll( filename, error, errorsize, 0, file_exists );
593 /***********************************************************************
594 * wine_dll_unload
596 * Unload a builtin dll.
598 void wine_dll_unload( void *handle )
600 if (handle != (void *)1)
601 wine_dlclose( handle, NULL, 0 );
605 /***********************************************************************
606 * wine_dll_load_main_exe
608 * Try to load the .so for the main exe.
610 void *wine_dll_load_main_exe( const char *name, char *error, int errorsize,
611 int test_only, int *file_exists )
613 return dlopen_dll( name, error, errorsize, test_only, file_exists );
617 /***********************************************************************
618 * wine_dll_enum_load_path
620 * Enumerate the dll load path.
622 const char *wine_dll_enum_load_path( unsigned int index )
624 if (index >= nb_dll_paths) return NULL;
625 return dll_paths[index];
629 /***********************************************************************
630 * wine_dll_get_owner
632 * Retrieve the name of the 32-bit owner dll for a 16-bit dll.
633 * Return 0 if OK, -1 on error.
635 int wine_dll_get_owner( const char *name, char *buffer, int size, int *exists )
637 int ret = -1;
638 char *path;
639 struct dll_path_context context;
641 *exists = 0;
643 for (path = first_dll_path( name, 1, &context ); path; path = next_dll_path( &context ))
645 int fd = open( path, O_RDONLY );
646 if (fd != -1)
648 int res = read( fd, buffer, size - 1 );
649 while (res > 0 && (buffer[res-1] == '\n' || buffer[res-1] == '\r')) res--;
650 buffer[res] = 0;
651 close( fd );
652 *exists = 1;
653 ret = 0;
654 break;
657 free_dll_path( &context );
658 return ret;
661 /***********************************************************************
662 * set_max_limit
664 * Set a user limit to the maximum allowed value.
666 static void set_max_limit( int limit )
668 #ifdef HAVE_SETRLIMIT
669 struct rlimit rlimit;
671 #if defined(RLIMIT_NOFILE) && defined(RUNNING_ON_VALGRIND)
672 if (limit == RLIMIT_NOFILE && RUNNING_ON_VALGRIND)
673 return;
674 #endif
676 if (!getrlimit( limit, &rlimit ))
678 rlimit.rlim_cur = rlimit.rlim_max;
679 if (setrlimit( limit, &rlimit ) != 0)
681 #if defined(__APPLE__) && defined(RLIMIT_NOFILE) && defined(OPEN_MAX)
682 /* On Leopard, setrlimit(RLIMIT_NOFILE, ...) fails on attempts to set
683 * rlim_cur above OPEN_MAX (even if rlim_max > OPEN_MAX). */
684 if (limit == RLIMIT_NOFILE && rlimit.rlim_cur > OPEN_MAX)
686 rlimit.rlim_cur = OPEN_MAX;
687 setrlimit( limit, &rlimit );
689 #endif
692 #endif
696 #ifdef __APPLE__
697 struct apple_stack_info
699 void *stack;
700 size_t desired_size;
703 /***********************************************************************
704 * apple_alloc_thread_stack
706 * Callback for wine_mmap_enum_reserved_areas to allocate space for
707 * the secondary thread's stack.
709 static int apple_alloc_thread_stack( void *base, size_t size, void *arg )
711 struct apple_stack_info *info = arg;
713 /* For mysterious reasons, putting the thread stack at the very top
714 * of the address space causes subsequent execs to fail, even on the
715 * child side of a fork. Avoid the top 16MB. */
716 char * const limit = (char*)0xff000000;
717 if ((char *)base >= limit) return 0;
718 if (size > limit - (char*)base)
719 size = limit - (char*)base;
720 if (size < info->desired_size) return 0;
721 info->stack = wine_anon_mmap( (char *)base + size - info->desired_size,
722 info->desired_size, PROT_READ|PROT_WRITE, MAP_FIXED );
723 return (info->stack != (void *)-1);
726 /***********************************************************************
727 * apple_create_wine_thread
729 * Spin off a secondary thread to complete Wine initialization, leaving
730 * the original thread for the Mac frameworks.
732 * Invoked as a CFRunLoopSource perform callback.
734 static void apple_create_wine_thread( void *init_func )
736 int success = 0;
737 pthread_t thread;
738 pthread_attr_t attr;
740 if (!pthread_attr_init( &attr ))
742 struct apple_stack_info info;
744 /* Try to put the new thread's stack in the reserved area. If this
745 * fails, just let it go wherever. It'll be a waste of space, but we
746 * can go on. */
747 if (!pthread_attr_getstacksize( &attr, &info.desired_size ) &&
748 wine_mmap_enum_reserved_areas( apple_alloc_thread_stack, &info, 1 ))
750 wine_mmap_remove_reserved_area( info.stack, info.desired_size, 0 );
751 pthread_attr_setstackaddr( &attr, (char*)info.stack + info.desired_size );
754 if (!pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE ) &&
755 !pthread_create( &thread, &attr, init_func, NULL ))
756 success = 1;
758 pthread_attr_destroy( &attr );
761 /* Failure is indicated by returning from wine_init(). Stopping
762 * the run loop allows apple_main_thread() and thus wine_init() to
763 * return. */
764 if (!success)
765 CFRunLoopStop( CFRunLoopGetCurrent() );
769 /***********************************************************************
770 * apple_main_thread
772 * Park the process's original thread in a Core Foundation run loop for
773 * use by the Mac frameworks, especially receiving and handling
774 * distributed notifications. Spin off a new thread for the rest of the
775 * Wine initialization.
777 static void apple_main_thread( void (*init_func)(void) )
779 CFRunLoopSourceContext source_context = { 0 };
780 CFRunLoopSourceRef source;
782 if (!pthread_main_np())
784 init_func();
785 return;
788 /* Multi-processing Services can get confused about the main thread if the
789 * first time it's used is on a secondary thread. Use it here to make sure
790 * that doesn't happen. */
791 MPTaskIsPreemptive(MPCurrentTaskID());
793 /* Give ourselves the best chance of having the distributed notification
794 * center scheduled on this thread's run loop. In theory, it's scheduled
795 * in the first thread to ask for it. */
796 CFNotificationCenterGetDistributedCenter();
798 /* We use this run loop source for two purposes. First, a run loop exits
799 * if it has no more sources scheduled. So, we need at least one source
800 * to keep the run loop running. Second, although it's not critical, it's
801 * preferable for the Wine initialization to not proceed until we know
802 * the run loop is running. So, we signal our source immediately after
803 * adding it and have its callback spin off the Wine thread. */
804 source_context.info = init_func;
805 source_context.perform = apple_create_wine_thread;
806 source = CFRunLoopSourceCreate( NULL, 0, &source_context );
808 if (source)
810 CFRunLoopAddSource( CFRunLoopGetCurrent(), source, kCFRunLoopCommonModes );
811 CFRunLoopSourceSignal( source );
812 CFRelease( source );
814 CFRunLoopRun(); /* Should never return, except on error. */
817 /* If we get here (i.e. return), that indicates failure to our caller. */
819 #endif
822 #ifdef __ANDROID__
824 #ifndef WINE_JAVA_CLASS
825 #define WINE_JAVA_CLASS "org/winehq/wine/WineActivity"
826 #endif
828 static JavaVM *java_vm;
829 static jobject java_object;
831 /* return the Java VM that was used for JNI initialisation */
832 JavaVM *wine_get_java_vm(void)
834 return java_vm;
837 /* return the Java object that called the wine_init method */
838 jobject wine_get_java_object(void)
840 return java_object;
843 /* main Wine initialisation */
844 static jstring wine_init_jni( JNIEnv *env, jobject obj, jobjectArray cmdline, jobjectArray environment )
846 char **argv;
847 char *str;
848 char error[1024];
849 int i, argc, length;
851 /* get the command line array */
853 argc = (*env)->GetArrayLength( env, cmdline );
854 for (i = length = 0; i < argc; i++)
856 jobject str_obj = (*env)->GetObjectArrayElement( env, cmdline, i );
857 length += (*env)->GetStringUTFLength( env, str_obj ) + 1;
860 argv = malloc( (argc + 1) * sizeof(*argv) + length );
861 str = (char *)(argv + argc + 1);
862 for (i = 0; i < argc; i++)
864 jobject str_obj = (*env)->GetObjectArrayElement( env, cmdline, i );
865 length = (*env)->GetStringUTFLength( env, str_obj );
866 (*env)->GetStringUTFRegion( env, str_obj, 0,
867 (*env)->GetStringLength( env, str_obj ), str );
868 argv[i] = str;
869 str[length] = 0;
870 str += length + 1;
872 argv[argc] = NULL;
874 /* set the environment variables */
876 if (environment)
878 int count = (*env)->GetArrayLength( env, environment );
879 for (i = 0; i < count - 1; i += 2)
881 jobject var_obj = (*env)->GetObjectArrayElement( env, environment, i );
882 jobject val_obj = (*env)->GetObjectArrayElement( env, environment, i + 1 );
883 const char *var = (*env)->GetStringUTFChars( env, var_obj, NULL );
885 if (val_obj)
887 const char *val = (*env)->GetStringUTFChars( env, val_obj, NULL );
888 setenv( var, val, 1 );
889 if (!strcmp( var, "LD_LIBRARY_PATH" ))
891 void (*update_func)( const char * ) = dlsym( RTLD_DEFAULT,
892 "android_update_LD_LIBRARY_PATH" );
893 if (update_func) update_func( val );
895 (*env)->ReleaseStringUTFChars( env, val_obj, val );
897 else unsetenv( var );
899 (*env)->ReleaseStringUTFChars( env, var_obj, var );
903 java_object = (*env)->NewGlobalRef( env, obj );
905 wine_init( argc, argv, error, sizeof(error) );
906 return (*env)->NewStringUTF( env, error );
909 jint JNI_OnLoad( JavaVM *vm, void *reserved )
911 static const JNINativeMethod method =
913 "wine_init", "([Ljava/lang/String;[Ljava/lang/String;)Ljava/lang/String;", wine_init_jni
916 JNIEnv *env;
917 jclass class;
919 java_vm = vm;
920 if ((*vm)->AttachCurrentThread( vm, &env, NULL ) != JNI_OK) return JNI_ERR;
921 if (!(class = (*env)->FindClass( env, WINE_JAVA_CLASS ))) return JNI_ERR;
922 (*env)->RegisterNatives( env, class, &method, 1 );
923 return JNI_VERSION_1_6;
926 #endif /* __ANDROID__ */
928 /***********************************************************************
929 * set_rttime_limit
931 * set a limit on the cpu time used
933 static void set_rttime_limit(void)
935 #if defined(HAVE_SETRLIMIT) && defined(__linux__)
936 #ifndef RLIMIT_RTTIME
937 #define RLIMIT_RTTIME 15
938 #endif
939 struct rlimit rlimit;
941 if (!getrlimit( RLIMIT_RTTIME, &rlimit ))
943 /* 1000 ms maximum realtime before the first SIGXCPU, this will drop
944 * all realtime threads to normal priority.
946 if (rlimit.rlim_max > 5000000)
947 rlimit.rlim_max = 5000000;
948 rlimit.rlim_cur = 1000000;
950 setrlimit( RLIMIT_RTTIME, &rlimit );
952 #endif
956 /***********************************************************************
957 * wine_init
959 * Main Wine initialisation.
961 void wine_init( int argc, char *argv[], char *error, int error_size )
963 struct dll_path_context context;
964 char *path;
965 void *ntdll = NULL;
966 void (*init_func)(void);
968 /* force a few limits that are set too low on some platforms */
969 #ifdef RLIMIT_NOFILE
970 set_max_limit( RLIMIT_NOFILE );
971 #endif
972 #ifdef RLIMIT_AS
973 set_max_limit( RLIMIT_AS );
974 #endif
975 set_rttime_limit();
977 wine_init_argv0_path( argv[0] );
978 build_dll_path();
979 __wine_main_argc = argc;
980 __wine_main_argv = argv;
981 __wine_main_environ = __wine_get_main_environment();
982 mmap_init();
984 for (path = first_dll_path( "ntdll.dll", 0, &context ); path; path = next_dll_path( &context ))
986 if ((ntdll = wine_dlopen( path, RTLD_NOW, error, error_size )))
988 /* if we didn't use the default dll dir, remove it from the search path */
989 if (default_dlldir[0] && context.index < nb_dll_paths + 2) nb_dll_paths--;
990 break;
993 free_dll_path( &context );
995 if (!ntdll) return;
996 if (!(init_func = wine_dlsym( ntdll, "__wine_process_init", error, error_size ))) return;
997 #ifdef __APPLE__
998 apple_main_thread( init_func );
999 #else
1000 init_func();
1001 #endif
1006 * These functions provide wrappers around dlopen() and associated
1007 * functions. They work around a bug in glibc 2.1.x where calling
1008 * a dl*() function after a previous dl*() function has failed
1009 * without a dlerror() call between the two will cause a crash.
1010 * They all take a pointer to a buffer that
1011 * will receive the error description (from dlerror()). This
1012 * parameter may be NULL if the error description is not required.
1015 #ifndef RTLD_FIRST
1016 #define RTLD_FIRST 0
1017 #endif
1019 /***********************************************************************
1020 * wine_dlopen
1022 void *wine_dlopen( const char *filename, int flag, char *error, size_t errorsize )
1024 #ifdef HAVE_DLOPEN
1025 void *ret;
1026 const char *s;
1028 #ifdef __APPLE__
1029 /* the Mac OS loader pretends to be able to load PE files, so avoid them here */
1030 unsigned char magic[2];
1031 int fd = open( filename, O_RDONLY );
1032 if (fd != -1)
1034 if (pread( fd, magic, 2, 0 ) == 2 && magic[0] == 'M' && magic[1] == 'Z')
1036 if (error && errorsize)
1038 static const char msg[] = "MZ format";
1039 size_t len = min( errorsize, sizeof(msg) );
1040 memcpy( error, msg, len );
1041 error[len - 1] = 0;
1043 close( fd );
1044 return NULL;
1046 close( fd );
1048 #endif
1049 dlerror(); dlerror();
1050 #ifdef __sun
1051 if (strchr( filename, ':' ))
1053 char path[PATH_MAX];
1054 /* Solaris' brain damaged dlopen() treats ':' as a path separator */
1055 realpath( filename, path );
1056 ret = dlopen( path, flag | RTLD_FIRST );
1058 else
1059 #endif
1060 ret = dlopen( filename, flag | RTLD_FIRST );
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_dlsym
1090 void *wine_dlsym( void *handle, const char *symbol, char *error, size_t errorsize )
1092 #ifdef HAVE_DLOPEN
1093 void *ret;
1094 const char *s;
1095 dlerror(); dlerror();
1096 ret = dlsym( handle, symbol );
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 NULL;
1120 #endif
1123 /***********************************************************************
1124 * wine_dlclose
1126 int wine_dlclose( void *handle, char *error, size_t errorsize )
1128 #ifdef HAVE_DLOPEN
1129 int ret;
1130 const char *s;
1131 dlerror(); dlerror();
1132 ret = dlclose( handle );
1133 s = dlerror();
1134 if (error && errorsize)
1136 if (s)
1138 size_t len = strlen(s);
1139 if (len >= errorsize) len = errorsize - 1;
1140 memcpy( error, s, len );
1141 error[len] = 0;
1143 else error[0] = 0;
1145 dlerror();
1146 return ret;
1147 #else
1148 if (error)
1150 static const char msg[] = "dlopen interface not detected by configure";
1151 size_t len = min( errorsize, sizeof(msg) );
1152 memcpy( error, msg, len );
1153 error[len - 1] = 0;
1155 return 1;
1156 #endif