winegcc: Add -I for the prefix's include dir.
[wine.git] / libs / wine / loader.c
blob0af3b8e5204d5ab54a7013b969c3367450beee54
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 #include <mach-o/getsect.h>
53 #else
54 extern char **environ;
55 #endif
57 #ifdef __ANDROID__
58 #include <jni.h>
59 #endif
61 #define NONAMELESSUNION
62 #define NONAMELESSSTRUCT
63 #include "windef.h"
64 #include "winbase.h"
65 #include "wine/library.h"
67 /* argc/argv for the Windows application */
68 int __wine_main_argc = 0;
69 char **__wine_main_argv = NULL;
70 WCHAR **__wine_main_wargv = NULL;
71 char **__wine_main_environ = NULL;
73 struct dll_path_context
75 unsigned int index; /* current index in the dll path list */
76 char *buffer; /* buffer used for storing path names */
77 char *name; /* start of file name part in buffer (including leading slash) */
78 int namelen; /* length of file name without .so extension */
79 int win16; /* 16-bit dll search */
82 #define MAX_DLLS 100
84 static struct
86 const IMAGE_NT_HEADERS *nt; /* NT header */
87 const char *filename; /* DLL file name */
88 } builtin_dlls[MAX_DLLS];
90 static int nb_dlls;
92 static const IMAGE_NT_HEADERS *main_exe;
94 static load_dll_callback_t load_dll_callback;
96 static const char *build_dir;
97 static const char *default_dlldir;
98 static const char **dll_paths;
99 static unsigned int nb_dll_paths;
100 static int dll_path_maxlen;
102 extern void mmap_init(void);
103 extern const char *get_dlldir( const char **default_dlldir );
105 /* build the dll load path from the WINEDLLPATH variable */
106 static void build_dll_path(void)
108 int len, count = 0;
109 char *p, *path = getenv( "WINEDLLPATH" );
110 const char *dlldir = get_dlldir( &default_dlldir );
112 if (path)
114 /* count how many path elements we need */
115 path = strdup(path);
116 p = path;
117 while (*p)
119 while (*p == ':') p++;
120 if (!*p) break;
121 count++;
122 while (*p && *p != ':') p++;
126 dll_paths = malloc( (count+2) * sizeof(*dll_paths) );
127 nb_dll_paths = 0;
129 if (dlldir)
131 dll_path_maxlen = strlen(dlldir);
132 dll_paths[nb_dll_paths++] = dlldir;
134 else if ((build_dir = wine_get_build_dir()))
136 dll_path_maxlen = strlen(build_dir) + sizeof("/programs");
139 if (count)
141 p = path;
142 while (*p)
144 while (*p == ':') *p++ = 0;
145 if (!*p) break;
146 dll_paths[nb_dll_paths] = p;
147 while (*p && *p != ':') p++;
148 if (p - dll_paths[nb_dll_paths] > dll_path_maxlen)
149 dll_path_maxlen = p - dll_paths[nb_dll_paths];
150 nb_dll_paths++;
154 /* append default dll dir (if not empty) to path */
155 if ((len = strlen(default_dlldir)) > 0)
157 if (len > dll_path_maxlen) dll_path_maxlen = len;
158 dll_paths[nb_dll_paths++] = default_dlldir;
162 /* check if the library is the correct architecture */
163 /* only returns false for a valid library of the wrong arch */
164 static int check_library_arch( int fd )
166 #ifdef __APPLE__
167 struct /* Mach-O header */
169 unsigned int magic;
170 unsigned int cputype;
171 } header;
173 if (read( fd, &header, sizeof(header) ) != sizeof(header)) return 1;
174 if (header.magic != 0xfeedface) return 1;
175 if (sizeof(void *) == sizeof(int)) return !(header.cputype >> 24);
176 else return (header.cputype >> 24) == 1; /* CPU_ARCH_ABI64 */
177 #else
178 struct /* ELF header */
180 unsigned char magic[4];
181 unsigned char class;
182 unsigned char data;
183 unsigned char version;
184 } header;
186 if (read( fd, &header, sizeof(header) ) != sizeof(header)) return 1;
187 if (memcmp( header.magic, "\177ELF", 4 )) return 1;
188 if (header.version != 1 /* EV_CURRENT */) return 1;
189 #ifdef WORDS_BIGENDIAN
190 if (header.data != 2 /* ELFDATA2MSB */) return 1;
191 #else
192 if (header.data != 1 /* ELFDATA2LSB */) return 1;
193 #endif
194 if (sizeof(void *) == sizeof(int)) return header.class == 1; /* ELFCLASS32 */
195 else return header.class == 2; /* ELFCLASS64 */
196 #endif
199 /* check if a given file can be opened */
200 static inline int file_exists( const char *name )
202 int ret = 0;
203 int fd = open( name, O_RDONLY );
204 if (fd != -1)
206 ret = check_library_arch( fd );
207 close( fd );
209 return ret;
212 static inline char *prepend( char *buffer, const char *str, size_t len )
214 return memcpy( buffer - len, str, len );
217 /* get a filename from the next entry in the dll path */
218 static char *next_dll_path( struct dll_path_context *context )
220 unsigned int index = context->index++;
221 int namelen = context->namelen;
222 char *path = context->name;
224 switch(index)
226 case 0: /* try dlls dir with subdir prefix */
227 if (namelen > 4 && !memcmp( context->name + namelen - 4, ".dll", 4 )) namelen -= 4;
228 if (!context->win16) path = prepend( path, context->name, namelen );
229 path = prepend( path, "/dlls", sizeof("/dlls") - 1 );
230 path = prepend( path, build_dir, strlen(build_dir) );
231 return path;
232 case 1: /* try programs dir with subdir prefix */
233 if (!context->win16)
235 if (namelen > 4 && !memcmp( context->name + namelen - 4, ".exe", 4 )) namelen -= 4;
236 path = prepend( path, context->name, namelen );
237 path = prepend( path, "/programs", sizeof("/programs") - 1 );
238 path = prepend( path, build_dir, strlen(build_dir) );
239 return path;
241 context->index++;
242 /* fall through */
243 default:
244 index -= 2;
245 if (index >= nb_dll_paths) return NULL;
246 path = prepend( path, dll_paths[index], strlen( dll_paths[index] ));
247 return path;
252 /* get a filename from the first entry in the dll path */
253 static char *first_dll_path( const char *name, int win16, struct dll_path_context *context )
255 char *p;
256 int namelen = strlen( name );
257 const char *ext = win16 ? "16" : ".so";
259 context->buffer = malloc( dll_path_maxlen + 2 * namelen + strlen(ext) + 3 );
260 context->index = build_dir ? 0 : 2; /* if no build dir skip all the build dir magic cases */
261 context->name = context->buffer + dll_path_maxlen + namelen + 1;
262 context->namelen = namelen + 1;
263 context->win16 = win16;
265 /* store the name at the end of the buffer, followed by extension */
266 p = context->name;
267 *p++ = '/';
268 memcpy( p, name, namelen );
269 strcpy( p + namelen, ext );
270 return next_dll_path( context );
274 /* free the dll path context created by first_dll_path */
275 static inline void free_dll_path( struct dll_path_context *context )
277 free( context->buffer );
281 /* open a library for a given dll, searching in the dll path
282 * 'name' must be the Windows dll name (e.g. "kernel32.dll") */
283 static void *dlopen_dll( const char *name, char *error, int errorsize,
284 int test_only, int *exists )
286 struct dll_path_context context;
287 char *path;
288 void *ret = NULL;
290 *exists = 0;
291 for (path = first_dll_path( name, 0, &context ); path; path = next_dll_path( &context ))
293 if (!test_only && (ret = wine_dlopen( path, RTLD_NOW, error, errorsize ))) break;
294 if ((*exists = file_exists( path ))) break; /* exists but cannot be loaded, return the error */
296 free_dll_path( &context );
297 return ret;
301 /* adjust an array of pointers to make them into RVAs */
302 static inline void fixup_rva_ptrs( void *array, BYTE *base, unsigned int count )
304 void **src = (void **)array;
305 DWORD *dst = (DWORD *)array;
306 while (count--)
308 *dst++ = *src ? (BYTE *)*src - base : 0;
309 src++;
313 /* fixup an array of RVAs by adding the specified delta */
314 static inline void fixup_rva_dwords( DWORD *ptr, int delta, unsigned int count )
316 while (count--)
318 if (*ptr) *ptr += delta;
319 ptr++;
324 /* fixup an array of name/ordinal RVAs by adding the specified delta */
325 static inline void fixup_rva_names( UINT_PTR *ptr, int delta )
327 while (*ptr)
329 if (!(*ptr & IMAGE_ORDINAL_FLAG)) *ptr += delta;
330 ptr++;
335 /* fixup RVAs in the import directory */
336 static void fixup_imports( IMAGE_IMPORT_DESCRIPTOR *dir, BYTE *base, int delta )
338 while (dir->Name)
340 fixup_rva_dwords( &dir->u.OriginalFirstThunk, delta, 1 );
341 fixup_rva_dwords( &dir->Name, delta, 1 );
342 fixup_rva_dwords( &dir->FirstThunk, delta, 1 );
343 if (dir->u.OriginalFirstThunk) fixup_rva_names( (UINT_PTR *)(base + dir->u.OriginalFirstThunk), delta );
344 if (dir->FirstThunk) fixup_rva_names( (UINT_PTR *)(base + dir->FirstThunk), delta );
345 dir++;
350 /* fixup RVAs in the export directory */
351 static void fixup_exports( IMAGE_EXPORT_DIRECTORY *dir, BYTE *base, int delta )
353 fixup_rva_dwords( &dir->Name, delta, 1 );
354 fixup_rva_dwords( &dir->AddressOfFunctions, delta, 1 );
355 fixup_rva_dwords( &dir->AddressOfNames, delta, 1 );
356 fixup_rva_dwords( &dir->AddressOfNameOrdinals, delta, 1 );
357 fixup_rva_dwords( (DWORD *)(base + dir->AddressOfNames), delta, dir->NumberOfNames );
358 fixup_rva_ptrs( (base + dir->AddressOfFunctions), base, dir->NumberOfFunctions );
362 /* fixup RVAs in the resource directory */
363 static void fixup_resources( IMAGE_RESOURCE_DIRECTORY *dir, BYTE *root, int delta )
365 IMAGE_RESOURCE_DIRECTORY_ENTRY *entry;
366 int i;
368 entry = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(dir + 1);
369 for (i = 0; i < dir->NumberOfNamedEntries + dir->NumberOfIdEntries; i++, entry++)
371 void *ptr = root + entry->u2.s2.OffsetToDirectory;
372 if (entry->u2.s2.DataIsDirectory) fixup_resources( ptr, root, delta );
373 else
375 IMAGE_RESOURCE_DATA_ENTRY *data = ptr;
376 fixup_rva_dwords( &data->OffsetToData, delta, 1 );
382 /* map a builtin dll in memory and fixup RVAs */
383 static void *map_dll( const IMAGE_NT_HEADERS *nt_descr )
385 #ifdef HAVE_MMAP
386 IMAGE_DATA_DIRECTORY *dir;
387 IMAGE_DOS_HEADER *dos;
388 IMAGE_NT_HEADERS *nt;
389 IMAGE_SECTION_HEADER *sec;
390 BYTE *addr;
391 DWORD code_start, code_end, data_start, data_end;
392 const size_t page_size = sysconf( _SC_PAGESIZE );
393 const size_t page_mask = page_size - 1;
394 int delta, nb_sections = 2; /* code + data */
395 unsigned int i;
396 #ifdef __APPLE__
397 Dl_info dli;
398 unsigned long data_size;
399 #endif
401 size_t size = (sizeof(IMAGE_DOS_HEADER)
402 + sizeof(IMAGE_NT_HEADERS)
403 + nb_sections * sizeof(IMAGE_SECTION_HEADER));
405 assert( size <= page_size );
407 /* module address must be aligned on 64K boundary */
408 addr = (BYTE *)((nt_descr->OptionalHeader.ImageBase + 0xffff) & ~0xffff);
409 if (wine_anon_mmap( addr, page_size, PROT_READ|PROT_WRITE, MAP_FIXED ) != addr) return NULL;
411 dos = (IMAGE_DOS_HEADER *)addr;
412 nt = (IMAGE_NT_HEADERS *)(dos + 1);
413 sec = (IMAGE_SECTION_HEADER *)(nt + 1);
415 /* Build the DOS and NT headers */
417 dos->e_magic = IMAGE_DOS_SIGNATURE;
418 dos->e_cblp = 0x90;
419 dos->e_cp = 3;
420 dos->e_cparhdr = (sizeof(*dos)+0xf)/0x10;
421 dos->e_minalloc = 0;
422 dos->e_maxalloc = 0xffff;
423 dos->e_ss = 0x0000;
424 dos->e_sp = 0x00b8;
425 dos->e_lfarlc = sizeof(*dos);
426 dos->e_lfanew = sizeof(*dos);
428 *nt = *nt_descr;
430 delta = (const BYTE *)nt_descr - addr;
431 code_start = page_size;
432 data_start = delta & ~page_mask;
433 #ifdef __APPLE__
434 /* Need the mach_header, not the PE header, to give to getsegmentdata(3) */
435 dladdr(addr, &dli);
436 code_end = getsegmentdata(dli.dli_fbase, "__DATA", &data_size) - addr;
437 data_end = (code_end + data_size + page_mask) & ~page_mask;
438 #else
439 code_end = data_start;
440 data_end = (nt->OptionalHeader.SizeOfImage + delta + page_mask) & ~page_mask;
441 #endif
443 fixup_rva_ptrs( &nt->OptionalHeader.AddressOfEntryPoint, addr, 1 );
445 nt->FileHeader.NumberOfSections = nb_sections;
446 nt->OptionalHeader.BaseOfCode = code_start;
447 #ifndef _WIN64
448 nt->OptionalHeader.BaseOfData = data_start;
449 #endif
450 nt->OptionalHeader.SizeOfCode = code_end - code_start;
451 nt->OptionalHeader.SizeOfInitializedData = data_end - data_start;
452 nt->OptionalHeader.SizeOfUninitializedData = 0;
453 nt->OptionalHeader.SizeOfImage = data_end;
454 nt->OptionalHeader.ImageBase = (ULONG_PTR)addr;
456 /* Build the code section */
458 memcpy( sec->Name, ".text", sizeof(".text") );
459 sec->SizeOfRawData = code_end - code_start;
460 sec->Misc.VirtualSize = sec->SizeOfRawData;
461 sec->VirtualAddress = code_start;
462 sec->PointerToRawData = code_start;
463 sec->Characteristics = (IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ);
464 sec++;
466 /* Build the data section */
468 memcpy( sec->Name, ".data", sizeof(".data") );
469 sec->SizeOfRawData = data_end - data_start;
470 sec->Misc.VirtualSize = sec->SizeOfRawData;
471 sec->VirtualAddress = data_start;
472 sec->PointerToRawData = data_start;
473 sec->Characteristics = (IMAGE_SCN_CNT_INITIALIZED_DATA |
474 IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_READ);
475 sec++;
477 for (i = 0; i < nt->OptionalHeader.NumberOfRvaAndSizes; i++)
478 fixup_rva_dwords( &nt->OptionalHeader.DataDirectory[i].VirtualAddress, delta, 1 );
480 /* Build the import directory */
482 dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_IMPORT_DIRECTORY];
483 if (dir->Size)
485 IMAGE_IMPORT_DESCRIPTOR *imports = (void *)(addr + dir->VirtualAddress);
486 fixup_imports( imports, addr, delta );
489 /* Build the resource directory */
491 dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_RESOURCE_DIRECTORY];
492 if (dir->Size)
494 void *ptr = (void *)(addr + dir->VirtualAddress);
495 fixup_resources( ptr, ptr, delta );
498 /* Build the export directory */
500 dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_EXPORT_DIRECTORY];
501 if (dir->Size)
503 IMAGE_EXPORT_DIRECTORY *exports = (void *)(addr + dir->VirtualAddress);
504 fixup_exports( exports, addr, delta );
506 return addr;
507 #else /* HAVE_MMAP */
508 return NULL;
509 #endif /* HAVE_MMAP */
513 /***********************************************************************
514 * __wine_get_main_environment
516 * Return an environment pointer to work around lack of environ variable.
517 * Only exported on Mac OS.
519 char **__wine_get_main_environment(void)
521 return environ;
525 /***********************************************************************
526 * __wine_dll_register
528 * Register a built-in DLL descriptor.
530 void __wine_dll_register( const IMAGE_NT_HEADERS *header, const char *filename )
532 if (load_dll_callback) load_dll_callback( map_dll(header), filename );
533 else
535 if (!(header->FileHeader.Characteristics & IMAGE_FILE_DLL))
536 main_exe = header;
537 else
539 assert( nb_dlls < MAX_DLLS );
540 builtin_dlls[nb_dlls].nt = header;
541 builtin_dlls[nb_dlls].filename = filename;
542 nb_dlls++;
548 /***********************************************************************
549 * wine_dll_set_callback
551 * Set the callback function for dll loading, and call it
552 * for all dlls that were implicitly loaded already.
554 void wine_dll_set_callback( load_dll_callback_t load )
556 int i;
557 load_dll_callback = load;
558 for (i = 0; i < nb_dlls; i++)
560 const IMAGE_NT_HEADERS *nt = builtin_dlls[i].nt;
561 if (!nt) continue;
562 builtin_dlls[i].nt = NULL;
563 load_dll_callback( map_dll(nt), builtin_dlls[i].filename );
565 nb_dlls = 0;
566 if (main_exe) load_dll_callback( map_dll(main_exe), "" );
570 /***********************************************************************
571 * wine_dll_load
573 * Load a builtin dll.
575 void *wine_dll_load( const char *filename, char *error, int errorsize, int *file_exists )
577 int i;
579 /* callback must have been set already */
580 assert( load_dll_callback );
582 /* check if we have it in the list */
583 /* this can happen when initializing pre-loaded dlls in wine_dll_set_callback */
584 for (i = 0; i < nb_dlls; i++)
586 if (!builtin_dlls[i].nt) continue;
587 if (!strcmp( builtin_dlls[i].filename, filename ))
589 const IMAGE_NT_HEADERS *nt = builtin_dlls[i].nt;
590 builtin_dlls[i].nt = NULL;
591 load_dll_callback( map_dll(nt), builtin_dlls[i].filename );
592 *file_exists = 1;
593 return (void *)1;
596 return dlopen_dll( filename, error, errorsize, 0, file_exists );
600 /***********************************************************************
601 * wine_dll_unload
603 * Unload a builtin dll.
605 void wine_dll_unload( void *handle )
607 if (handle != (void *)1)
608 wine_dlclose( handle, NULL, 0 );
612 /***********************************************************************
613 * wine_dll_load_main_exe
615 * Try to load the .so for the main exe.
617 void *wine_dll_load_main_exe( const char *name, char *error, int errorsize,
618 int test_only, int *file_exists )
620 return dlopen_dll( name, error, errorsize, test_only, file_exists );
624 /***********************************************************************
625 * wine_dll_enum_load_path
627 * Enumerate the dll load path.
629 const char *wine_dll_enum_load_path( unsigned int index )
631 if (index >= nb_dll_paths) return NULL;
632 return dll_paths[index];
636 /***********************************************************************
637 * wine_dll_get_owner
639 * Retrieve the name of the 32-bit owner dll for a 16-bit dll.
640 * Return 0 if OK, -1 on error.
642 int wine_dll_get_owner( const char *name, char *buffer, int size, int *exists )
644 int ret = -1;
645 char *path;
646 struct dll_path_context context;
648 *exists = 0;
650 for (path = first_dll_path( name, 1, &context ); path; path = next_dll_path( &context ))
652 int fd = open( path, O_RDONLY );
653 if (fd != -1)
655 int res = read( fd, buffer, size - 1 );
656 while (res > 0 && (buffer[res-1] == '\n' || buffer[res-1] == '\r')) res--;
657 buffer[res] = 0;
658 close( fd );
659 *exists = 1;
660 ret = 0;
661 break;
664 free_dll_path( &context );
665 return ret;
669 /***********************************************************************
670 * set_max_limit
672 * Set a user limit to the maximum allowed value.
674 static void set_max_limit( int limit )
676 #ifdef HAVE_SETRLIMIT
677 struct rlimit rlimit;
679 if (!getrlimit( limit, &rlimit ))
681 rlimit.rlim_cur = rlimit.rlim_max;
682 if (setrlimit( limit, &rlimit ) != 0)
684 #if defined(__APPLE__) && defined(RLIMIT_NOFILE) && defined(OPEN_MAX)
685 /* On Leopard, setrlimit(RLIMIT_NOFILE, ...) fails on attempts to set
686 * rlim_cur above OPEN_MAX (even if rlim_max > OPEN_MAX). */
687 if (limit == RLIMIT_NOFILE && rlimit.rlim_cur > OPEN_MAX)
689 rlimit.rlim_cur = OPEN_MAX;
690 setrlimit( limit, &rlimit );
692 #endif
695 #endif
699 #ifdef __APPLE__
700 struct apple_stack_info
702 void *stack;
703 size_t desired_size;
706 /***********************************************************************
707 * apple_alloc_thread_stack
709 * Callback for wine_mmap_enum_reserved_areas to allocate space for
710 * the secondary thread's stack.
712 static int apple_alloc_thread_stack( void *base, size_t size, void *arg )
714 struct apple_stack_info *info = arg;
716 /* For mysterious reasons, putting the thread stack at the very top
717 * of the address space causes subsequent execs to fail, even on the
718 * child side of a fork. Avoid the top 16MB. */
719 char * const limit = (char*)0xff000000;
720 if ((char *)base >= limit) return 0;
721 if (size > limit - (char*)base)
722 size = limit - (char*)base;
723 if (size < info->desired_size) return 0;
724 info->stack = wine_anon_mmap( (char *)base + size - info->desired_size,
725 info->desired_size, PROT_READ|PROT_WRITE, MAP_FIXED );
726 return (info->stack != (void *)-1);
729 /***********************************************************************
730 * apple_create_wine_thread
732 * Spin off a secondary thread to complete Wine initialization, leaving
733 * the original thread for the Mac frameworks.
735 * Invoked as a CFRunLoopSource perform callback.
737 static void apple_create_wine_thread( void *init_func )
739 int success = 0;
740 pthread_t thread;
741 pthread_attr_t attr;
743 if (!pthread_attr_init( &attr ))
745 struct apple_stack_info info;
747 /* Try to put the new thread's stack in the reserved area. If this
748 * fails, just let it go wherever. It'll be a waste of space, but we
749 * can go on. */
750 if (!pthread_attr_getstacksize( &attr, &info.desired_size ) &&
751 wine_mmap_enum_reserved_areas( apple_alloc_thread_stack, &info, 1 ))
753 wine_mmap_remove_reserved_area( info.stack, info.desired_size, 0 );
754 pthread_attr_setstackaddr( &attr, (char*)info.stack + info.desired_size );
757 if (!pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE ) &&
758 !pthread_create( &thread, &attr, init_func, NULL ))
759 success = 1;
761 pthread_attr_destroy( &attr );
764 /* Failure is indicated by returning from wine_init(). Stopping
765 * the run loop allows apple_main_thread() and thus wine_init() to
766 * return. */
767 if (!success)
768 CFRunLoopStop( CFRunLoopGetCurrent() );
772 /***********************************************************************
773 * apple_main_thread
775 * Park the process's original thread in a Core Foundation run loop for
776 * use by the Mac frameworks, especially receiving and handling
777 * distributed notifications. Spin off a new thread for the rest of the
778 * Wine initialization.
780 static void apple_main_thread( void (*init_func)(void) )
782 CFRunLoopSourceContext source_context = { 0 };
783 CFRunLoopSourceRef source;
785 if (!pthread_main_np())
787 init_func();
788 return;
791 /* Multi-processing Services can get confused about the main thread if the
792 * first time it's used is on a secondary thread. Use it here to make sure
793 * that doesn't happen. */
794 MPTaskIsPreemptive(MPCurrentTaskID());
796 /* Give ourselves the best chance of having the distributed notification
797 * center scheduled on this thread's run loop. In theory, it's scheduled
798 * in the first thread to ask for it. */
799 CFNotificationCenterGetDistributedCenter();
801 /* We use this run loop source for two purposes. First, a run loop exits
802 * if it has no more sources scheduled. So, we need at least one source
803 * to keep the run loop running. Second, although it's not critical, it's
804 * preferable for the Wine initialization to not proceed until we know
805 * the run loop is running. So, we signal our source immediately after
806 * adding it and have its callback spin off the Wine thread. */
807 source_context.info = init_func;
808 source_context.perform = apple_create_wine_thread;
809 source = CFRunLoopSourceCreate( NULL, 0, &source_context );
811 if (source)
813 CFRunLoopAddSource( CFRunLoopGetCurrent(), source, kCFRunLoopCommonModes );
814 CFRunLoopSourceSignal( source );
815 CFRelease( source );
817 CFRunLoopRun(); /* Should never return, except on error. */
820 /* If we get here (i.e. return), that indicates failure to our caller. */
822 #endif
825 #ifdef __ANDROID__
827 #ifndef WINE_JAVA_CLASS
828 #define WINE_JAVA_CLASS "org/winehq/wine/WineActivity"
829 #endif
831 static JavaVM *java_vm;
832 static jobject java_object;
834 /* return the Java VM that was used for JNI initialisation */
835 JavaVM *wine_get_java_vm(void)
837 return java_vm;
840 /* return the Java object that called the wine_init method */
841 jobject wine_get_java_object(void)
843 return java_object;
846 /* main Wine initialisation */
847 static jstring wine_init_jni( JNIEnv *env, jobject obj, jobjectArray cmdline, jobjectArray environment )
849 char **argv;
850 char *str;
851 char error[1024];
852 int i, argc, length;
854 /* get the command line array */
856 argc = (*env)->GetArrayLength( env, cmdline );
857 for (i = length = 0; i < argc; i++)
859 jobject str_obj = (*env)->GetObjectArrayElement( env, cmdline, i );
860 length += (*env)->GetStringUTFLength( env, str_obj ) + 1;
863 argv = malloc( (argc + 1) * sizeof(*argv) + length );
864 str = (char *)(argv + argc + 1);
865 for (i = 0; i < argc; i++)
867 jobject str_obj = (*env)->GetObjectArrayElement( env, cmdline, i );
868 length = (*env)->GetStringUTFLength( env, str_obj );
869 (*env)->GetStringUTFRegion( env, str_obj, 0,
870 (*env)->GetStringLength( env, str_obj ), str );
871 argv[i] = str;
872 str[length] = 0;
873 str += length + 1;
875 argv[argc] = NULL;
877 /* set the environment variables */
879 if (environment)
881 int count = (*env)->GetArrayLength( env, environment );
882 for (i = 0; i < count - 1; i += 2)
884 jobject var_obj = (*env)->GetObjectArrayElement( env, environment, i );
885 jobject val_obj = (*env)->GetObjectArrayElement( env, environment, i + 1 );
886 const char *var = (*env)->GetStringUTFChars( env, var_obj, NULL );
888 if (val_obj)
890 const char *val = (*env)->GetStringUTFChars( env, val_obj, NULL );
891 setenv( var, val, 1 );
892 if (!strcmp( var, "LD_LIBRARY_PATH" ))
894 void (*update_func)( const char * ) = dlsym( RTLD_DEFAULT,
895 "android_update_LD_LIBRARY_PATH" );
896 if (update_func) update_func( val );
898 else if (!strcmp( var, "WINEDEBUGLOG" ))
900 int fd = open( val, O_WRONLY | O_CREAT | O_APPEND, 0666 );
901 if (fd != -1)
903 dup2( fd, 2 );
904 close( fd );
907 (*env)->ReleaseStringUTFChars( env, val_obj, val );
909 else unsetenv( var );
911 (*env)->ReleaseStringUTFChars( env, var_obj, var );
915 java_object = (*env)->NewGlobalRef( env, obj );
917 #ifdef __i386__
919 unsigned short java_fs = wine_get_fs();
920 wine_set_fs( 0 );
921 wine_init( argc, argv, error, sizeof(error) );
922 wine_set_fs( java_fs );
924 #else
925 wine_init( argc, argv, error, sizeof(error) );
926 #endif
927 return (*env)->NewStringUTF( env, error );
930 jint JNI_OnLoad( JavaVM *vm, void *reserved )
932 static const JNINativeMethod method =
934 "wine_init", "([Ljava/lang/String;[Ljava/lang/String;)Ljava/lang/String;", wine_init_jni
937 JNIEnv *env;
938 jclass class;
940 java_vm = vm;
941 if ((*vm)->AttachCurrentThread( vm, &env, NULL ) != JNI_OK) return JNI_ERR;
942 if (!(class = (*env)->FindClass( env, WINE_JAVA_CLASS ))) return JNI_ERR;
943 (*env)->RegisterNatives( env, class, &method, 1 );
944 return JNI_VERSION_1_6;
947 #endif /* __ANDROID__ */
949 /***********************************************************************
950 * wine_init
952 * Main Wine initialisation.
954 void wine_init( int argc, char *argv[], char *error, int error_size )
956 struct dll_path_context context;
957 char *path;
958 void *ntdll = NULL;
959 void (*init_func)(void);
961 /* force a few limits that are set too low on some platforms */
962 #ifdef RLIMIT_NOFILE
963 set_max_limit( RLIMIT_NOFILE );
964 #endif
965 #ifdef RLIMIT_AS
966 set_max_limit( RLIMIT_AS );
967 #endif
969 wine_init_argv0_path( argv[0] );
970 build_dll_path();
971 __wine_main_argc = argc;
972 __wine_main_argv = argv;
973 __wine_main_environ = __wine_get_main_environment();
974 mmap_init();
976 for (path = first_dll_path( "ntdll.dll", 0, &context ); path; path = next_dll_path( &context ))
978 if ((ntdll = wine_dlopen( path, RTLD_NOW, error, error_size )))
980 /* if we didn't use the default dll dir, remove it from the search path */
981 if (default_dlldir[0] && context.index < nb_dll_paths + 2) nb_dll_paths--;
982 break;
985 free_dll_path( &context );
987 if (!ntdll) return;
988 if (!(init_func = wine_dlsym( ntdll, "__wine_process_init", error, error_size ))) return;
989 #ifdef __APPLE__
990 apple_main_thread( init_func );
991 #else
992 init_func();
993 #endif
998 * These functions provide wrappers around dlopen() and associated
999 * functions. They work around a bug in glibc 2.1.x where calling
1000 * a dl*() function after a previous dl*() function has failed
1001 * without a dlerror() call between the two will cause a crash.
1002 * They all take a pointer to a buffer that
1003 * will receive the error description (from dlerror()). This
1004 * parameter may be NULL if the error description is not required.
1007 #ifndef RTLD_FIRST
1008 #define RTLD_FIRST 0
1009 #endif
1011 /***********************************************************************
1012 * wine_dlopen
1014 void *wine_dlopen( const char *filename, int flag, char *error, size_t errorsize )
1016 #ifdef HAVE_DLOPEN
1017 void *ret;
1018 const char *s;
1020 #ifdef __APPLE__
1021 /* the Mac OS loader pretends to be able to load PE files, so avoid them here */
1022 unsigned char magic[2];
1023 int fd = open( filename, O_RDONLY );
1024 if (fd != -1)
1026 if (pread( fd, magic, 2, 0 ) == 2 && magic[0] == 'M' && magic[1] == 'Z')
1028 if (error && errorsize)
1030 static const char msg[] = "MZ format";
1031 size_t len = min( errorsize, sizeof(msg) );
1032 memcpy( error, msg, len );
1033 error[len - 1] = 0;
1035 close( fd );
1036 return NULL;
1038 close( fd );
1040 #endif
1041 dlerror(); dlerror();
1042 #ifdef __sun
1043 if (strchr( filename, ':' ))
1045 char path[PATH_MAX];
1046 /* Solaris' brain damaged dlopen() treats ':' as a path separator */
1047 realpath( filename, path );
1048 ret = dlopen( path, flag | RTLD_FIRST );
1050 else
1051 #endif
1052 ret = dlopen( filename, flag | RTLD_FIRST );
1053 s = dlerror();
1054 if (error && errorsize)
1056 if (s)
1058 size_t len = strlen(s);
1059 if (len >= errorsize) len = errorsize - 1;
1060 memcpy( error, s, len );
1061 error[len] = 0;
1063 else error[0] = 0;
1065 dlerror();
1066 return ret;
1067 #else
1068 if (error)
1070 static const char msg[] = "dlopen interface not detected by configure";
1071 size_t len = min( errorsize, sizeof(msg) );
1072 memcpy( error, msg, len );
1073 error[len - 1] = 0;
1075 return NULL;
1076 #endif
1079 /***********************************************************************
1080 * wine_dlsym
1082 void *wine_dlsym( void *handle, const char *symbol, char *error, size_t errorsize )
1084 #ifdef HAVE_DLOPEN
1085 void *ret;
1086 const char *s;
1087 dlerror(); dlerror();
1088 ret = dlsym( handle, symbol );
1089 s = dlerror();
1090 if (error && errorsize)
1092 if (s)
1094 size_t len = strlen(s);
1095 if (len >= errorsize) len = errorsize - 1;
1096 memcpy( error, s, len );
1097 error[len] = 0;
1099 else error[0] = 0;
1101 dlerror();
1102 return ret;
1103 #else
1104 if (error)
1106 static const char msg[] = "dlopen interface not detected by configure";
1107 size_t len = min( errorsize, sizeof(msg) );
1108 memcpy( error, msg, len );
1109 error[len - 1] = 0;
1111 return NULL;
1112 #endif
1115 /***********************************************************************
1116 * wine_dlclose
1118 int wine_dlclose( void *handle, char *error, size_t errorsize )
1120 #ifdef HAVE_DLOPEN
1121 int ret;
1122 const char *s;
1123 dlerror(); dlerror();
1124 ret = dlclose( handle );
1125 s = dlerror();
1126 if (error && errorsize)
1128 if (s)
1130 size_t len = strlen(s);
1131 if (len >= errorsize) len = errorsize - 1;
1132 memcpy( error, s, len );
1133 error[len] = 0;
1135 else error[0] = 0;
1137 dlerror();
1138 return ret;
1139 #else
1140 if (error)
1142 static const char msg[] = "dlopen interface not detected by configure";
1143 size_t len = min( errorsize, sizeof(msg) );
1144 memcpy( error, msg, len );
1145 error[len - 1] = 0;
1147 return 1;
1148 #endif