msvcp: Fixed complex division.
[wine.git] / libs / wine / loader.c
blob5c0192d429c81736f6473554dc1cc57d254f5625
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 /* argc/argv for the Windows application */
67 int __wine_main_argc = 0;
68 char **__wine_main_argv = NULL;
69 WCHAR **__wine_main_wargv = NULL;
70 char **__wine_main_environ = NULL;
72 struct dll_path_context
74 unsigned int index; /* current index in the dll path list */
75 char *buffer; /* buffer used for storing path names */
76 char *name; /* start of file name part in buffer (including leading slash) */
77 int namelen; /* length of file name without .so extension */
78 int win16; /* 16-bit dll search */
81 #define MAX_DLLS 100
83 static struct
85 const IMAGE_NT_HEADERS *nt; /* NT header */
86 const char *filename; /* DLL file name */
87 } builtin_dlls[MAX_DLLS];
89 static int nb_dlls;
91 static const IMAGE_NT_HEADERS *main_exe;
93 static load_dll_callback_t load_dll_callback;
95 static const char *build_dir;
96 static const char *default_dlldir;
97 static const char *dll_prefix;
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, const char **dll_prefix );
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, &dll_prefix );
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;
160 dll_path_maxlen += strlen( dll_prefix ) - 1;
163 /* check if the library is the correct architecture */
164 /* only returns false for a valid library of the wrong arch */
165 static int check_library_arch( int fd )
167 #ifdef __APPLE__
168 struct /* Mach-O header */
170 unsigned int magic;
171 unsigned int cputype;
172 } header;
174 if (read( fd, &header, sizeof(header) ) != sizeof(header)) return 1;
175 if (header.magic != 0xfeedface) return 1;
176 if (sizeof(void *) == sizeof(int)) return !(header.cputype >> 24);
177 else return (header.cputype >> 24) == 1; /* CPU_ARCH_ABI64 */
178 #else
179 struct /* ELF header */
181 unsigned char magic[4];
182 unsigned char class;
183 unsigned char data;
184 unsigned char version;
185 } header;
187 if (read( fd, &header, sizeof(header) ) != sizeof(header)) return 1;
188 if (memcmp( header.magic, "\177ELF", 4 )) return 1;
189 if (header.version != 1 /* EV_CURRENT */) return 1;
190 #ifdef WORDS_BIGENDIAN
191 if (header.data != 2 /* ELFDATA2MSB */) return 1;
192 #else
193 if (header.data != 1 /* ELFDATA2LSB */) return 1;
194 #endif
195 if (sizeof(void *) == sizeof(int)) return header.class == 1; /* ELFCLASS32 */
196 else return header.class == 2; /* ELFCLASS64 */
197 #endif
200 /* check if a given file can be opened */
201 static inline int file_exists( const char *name )
203 int ret = 0;
204 int fd = open( name, O_RDONLY );
205 if (fd != -1)
207 ret = check_library_arch( fd );
208 close( fd );
210 return ret;
213 static inline char *prepend( char *buffer, const char *str, size_t len )
215 return memcpy( buffer - len, str, len );
218 /* get a filename from the next entry in the dll path */
219 static char *next_dll_path( struct dll_path_context *context )
221 unsigned int index = context->index++;
222 int namelen = context->namelen;
223 char *path = context->name;
225 switch(index)
227 case 0: /* try dlls dir with subdir prefix */
228 if (namelen > 4 && !memcmp( context->name + namelen - 4, ".dll", 4 )) namelen -= 4;
229 if (!context->win16) path = prepend( path, context->name, namelen );
230 path = prepend( path, "/dlls", sizeof("/dlls") - 1 );
231 path = prepend( path, build_dir, strlen(build_dir) );
232 return path;
233 case 1: /* try programs dir with subdir prefix */
234 if (!context->win16)
236 if (namelen > 4 && !memcmp( context->name + namelen - 4, ".exe", 4 )) namelen -= 4;
237 path = prepend( path, context->name, namelen );
238 path = prepend( path, "/programs", sizeof("/programs") - 1 );
239 path = prepend( path, build_dir, strlen(build_dir) );
240 return path;
242 context->index++;
243 /* fall through */
244 default:
245 index -= 2;
246 if (index >= nb_dll_paths) return NULL;
247 path = prepend( path + 1, dll_prefix, strlen( dll_prefix ));
248 path = prepend( path, dll_paths[index], strlen( dll_paths[index] ));
249 return path;
254 /* get a filename from the first entry in the dll path */
255 static char *first_dll_path( const char *name, int win16, struct dll_path_context *context )
257 char *p;
258 int namelen = strlen( name );
259 const char *ext = win16 ? "16" : ".so";
261 context->buffer = malloc( dll_path_maxlen + 2 * namelen + strlen(ext) + 3 );
262 context->index = build_dir ? 0 : 2; /* if no build dir skip all the build dir magic cases */
263 context->name = context->buffer + dll_path_maxlen + namelen + 1;
264 context->namelen = namelen + 1;
265 context->win16 = win16;
267 /* store the name at the end of the buffer, followed by extension */
268 p = context->name;
269 *p++ = '/';
270 memcpy( p, name, namelen );
271 strcpy( p + namelen, ext );
272 return next_dll_path( context );
276 /* free the dll path context created by first_dll_path */
277 static inline void free_dll_path( struct dll_path_context *context )
279 free( context->buffer );
283 /* open a library for a given dll, searching in the dll path
284 * 'name' must be the Windows dll name (e.g. "kernel32.dll") */
285 static void *dlopen_dll( const char *name, char *error, int errorsize,
286 int test_only, int *exists )
288 struct dll_path_context context;
289 char *path;
290 void *ret = NULL;
292 *exists = 0;
293 for (path = first_dll_path( name, 0, &context ); path; path = next_dll_path( &context ))
295 if (!test_only && (ret = wine_dlopen( path, RTLD_NOW, error, errorsize ))) break;
296 if ((*exists = file_exists( path ))) break; /* exists but cannot be loaded, return the error */
298 free_dll_path( &context );
299 return ret;
303 /* adjust an array of pointers to make them into RVAs */
304 static inline void fixup_rva_ptrs( void *array, BYTE *base, unsigned int count )
306 void **src = (void **)array;
307 DWORD *dst = (DWORD *)array;
308 while (count--)
310 *dst++ = *src ? (BYTE *)*src - base : 0;
311 src++;
315 /* fixup an array of RVAs by adding the specified delta */
316 static inline void fixup_rva_dwords( DWORD *ptr, int delta, unsigned int count )
318 while (count--)
320 if (*ptr) *ptr += delta;
321 ptr++;
326 /* fixup RVAs in the import directory */
327 static void fixup_imports( IMAGE_IMPORT_DESCRIPTOR *dir, BYTE *base, int delta )
329 UINT_PTR *ptr;
331 while (dir->Name)
333 fixup_rva_dwords( &dir->u.OriginalFirstThunk, delta, 1 );
334 fixup_rva_dwords( &dir->Name, delta, 1 );
335 fixup_rva_dwords( &dir->FirstThunk, delta, 1 );
336 ptr = (UINT_PTR *)(base + (dir->u.OriginalFirstThunk ? dir->u.OriginalFirstThunk : dir->FirstThunk));
337 while (*ptr)
339 if (!(*ptr & IMAGE_ORDINAL_FLAG)) *ptr += delta;
340 ptr++;
342 dir++;
347 /* fixup RVAs in the export directory */
348 static void fixup_exports( IMAGE_EXPORT_DIRECTORY *dir, BYTE *base, int delta )
350 fixup_rva_dwords( &dir->Name, delta, 1 );
351 fixup_rva_dwords( &dir->AddressOfFunctions, delta, 1 );
352 fixup_rva_dwords( &dir->AddressOfNames, delta, 1 );
353 fixup_rva_dwords( &dir->AddressOfNameOrdinals, delta, 1 );
354 fixup_rva_dwords( (DWORD *)(base + dir->AddressOfNames), delta, dir->NumberOfNames );
355 fixup_rva_ptrs( (base + dir->AddressOfFunctions), base, dir->NumberOfFunctions );
359 /* fixup RVAs in the resource directory */
360 static void fixup_resources( IMAGE_RESOURCE_DIRECTORY *dir, BYTE *root, int delta )
362 IMAGE_RESOURCE_DIRECTORY_ENTRY *entry;
363 int i;
365 entry = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(dir + 1);
366 for (i = 0; i < dir->NumberOfNamedEntries + dir->NumberOfIdEntries; i++, entry++)
368 void *ptr = root + entry->u2.s2.OffsetToDirectory;
369 if (entry->u2.s2.DataIsDirectory) fixup_resources( ptr, root, delta );
370 else
372 IMAGE_RESOURCE_DATA_ENTRY *data = ptr;
373 fixup_rva_dwords( &data->OffsetToData, delta, 1 );
379 /* map a builtin dll in memory and fixup RVAs */
380 static void *map_dll( const IMAGE_NT_HEADERS *nt_descr )
382 #ifdef HAVE_MMAP
383 IMAGE_DATA_DIRECTORY *dir;
384 IMAGE_DOS_HEADER *dos;
385 IMAGE_NT_HEADERS *nt;
386 IMAGE_SECTION_HEADER *sec;
387 BYTE *addr;
388 DWORD code_start, data_start, data_end;
389 const size_t page_size = sysconf( _SC_PAGESIZE );
390 const size_t page_mask = page_size - 1;
391 int delta, nb_sections = 2; /* code + data */
392 unsigned int i;
394 size_t size = (sizeof(IMAGE_DOS_HEADER)
395 + sizeof(IMAGE_NT_HEADERS)
396 + nb_sections * sizeof(IMAGE_SECTION_HEADER));
398 assert( size <= page_size );
400 /* module address must be aligned on 64K boundary */
401 addr = (BYTE *)((nt_descr->OptionalHeader.ImageBase + 0xffff) & ~0xffff);
402 if (wine_anon_mmap( addr, page_size, PROT_READ|PROT_WRITE, MAP_FIXED ) != addr) return NULL;
404 dos = (IMAGE_DOS_HEADER *)addr;
405 nt = (IMAGE_NT_HEADERS *)(dos + 1);
406 sec = (IMAGE_SECTION_HEADER *)(nt + 1);
408 /* Build the DOS and NT headers */
410 dos->e_magic = IMAGE_DOS_SIGNATURE;
411 dos->e_cblp = 0x90;
412 dos->e_cp = 3;
413 dos->e_cparhdr = (sizeof(*dos)+0xf)/0x10;
414 dos->e_minalloc = 0;
415 dos->e_maxalloc = 0xffff;
416 dos->e_ss = 0x0000;
417 dos->e_sp = 0x00b8;
418 dos->e_lfarlc = sizeof(*dos);
419 dos->e_lfanew = sizeof(*dos);
421 *nt = *nt_descr;
423 delta = (const BYTE *)nt_descr - addr;
424 code_start = page_size;
425 data_start = delta & ~page_mask;
426 data_end = (nt->OptionalHeader.SizeOfImage + delta + page_mask) & ~page_mask;
428 fixup_rva_ptrs( &nt->OptionalHeader.AddressOfEntryPoint, addr, 1 );
430 nt->FileHeader.NumberOfSections = nb_sections;
431 nt->OptionalHeader.BaseOfCode = code_start;
432 #ifndef _WIN64
433 nt->OptionalHeader.BaseOfData = data_start;
434 #endif
435 nt->OptionalHeader.SizeOfCode = data_start - code_start;
436 nt->OptionalHeader.SizeOfInitializedData = data_end - data_start;
437 nt->OptionalHeader.SizeOfUninitializedData = 0;
438 nt->OptionalHeader.SizeOfImage = data_end;
439 nt->OptionalHeader.ImageBase = (ULONG_PTR)addr;
441 /* Build the code section */
443 memcpy( sec->Name, ".text", sizeof(".text") );
444 sec->SizeOfRawData = data_start - code_start;
445 sec->Misc.VirtualSize = sec->SizeOfRawData;
446 sec->VirtualAddress = code_start;
447 sec->PointerToRawData = code_start;
448 sec->Characteristics = (IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ);
449 sec++;
451 /* Build the data section */
453 memcpy( sec->Name, ".data", sizeof(".data") );
454 sec->SizeOfRawData = data_end - data_start;
455 sec->Misc.VirtualSize = sec->SizeOfRawData;
456 sec->VirtualAddress = data_start;
457 sec->PointerToRawData = data_start;
458 sec->Characteristics = (IMAGE_SCN_CNT_INITIALIZED_DATA |
459 IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_READ);
460 sec++;
462 for (i = 0; i < nt->OptionalHeader.NumberOfRvaAndSizes; i++)
463 fixup_rva_dwords( &nt->OptionalHeader.DataDirectory[i].VirtualAddress, delta, 1 );
465 /* Build the import directory */
467 dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_IMPORT_DIRECTORY];
468 if (dir->Size)
470 IMAGE_IMPORT_DESCRIPTOR *imports = (void *)(addr + dir->VirtualAddress);
471 fixup_imports( imports, addr, delta );
474 /* Build the resource directory */
476 dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_RESOURCE_DIRECTORY];
477 if (dir->Size)
479 void *ptr = (void *)(addr + dir->VirtualAddress);
480 fixup_resources( ptr, ptr, delta );
483 /* Build the export directory */
485 dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_EXPORT_DIRECTORY];
486 if (dir->Size)
488 IMAGE_EXPORT_DIRECTORY *exports = (void *)(addr + dir->VirtualAddress);
489 fixup_exports( exports, addr, delta );
491 return addr;
492 #else /* HAVE_MMAP */
493 return NULL;
494 #endif /* HAVE_MMAP */
498 /***********************************************************************
499 * __wine_get_main_environment
501 * Return an environment pointer to work around lack of environ variable.
502 * Only exported on Mac OS.
504 char **__wine_get_main_environment(void)
506 return environ;
510 /***********************************************************************
511 * __wine_dll_register
513 * Register a built-in DLL descriptor.
515 void __wine_dll_register( const IMAGE_NT_HEADERS *header, const char *filename )
517 if (load_dll_callback) load_dll_callback( map_dll(header), filename );
518 else
520 if (!(header->FileHeader.Characteristics & IMAGE_FILE_DLL))
521 main_exe = header;
522 else
524 assert( nb_dlls < MAX_DLLS );
525 builtin_dlls[nb_dlls].nt = header;
526 builtin_dlls[nb_dlls].filename = filename;
527 nb_dlls++;
533 /***********************************************************************
534 * wine_dll_set_callback
536 * Set the callback function for dll loading, and call it
537 * for all dlls that were implicitly loaded already.
539 void wine_dll_set_callback( load_dll_callback_t load )
541 int i;
542 load_dll_callback = load;
543 for (i = 0; i < nb_dlls; i++)
545 const IMAGE_NT_HEADERS *nt = builtin_dlls[i].nt;
546 if (!nt) continue;
547 builtin_dlls[i].nt = NULL;
548 load_dll_callback( map_dll(nt), builtin_dlls[i].filename );
550 nb_dlls = 0;
551 if (main_exe) load_dll_callback( map_dll(main_exe), "" );
555 /***********************************************************************
556 * wine_dll_load
558 * Load a builtin dll.
560 void *wine_dll_load( const char *filename, char *error, int errorsize, int *file_exists )
562 int i;
564 /* callback must have been set already */
565 assert( load_dll_callback );
567 /* check if we have it in the list */
568 /* this can happen when initializing pre-loaded dlls in wine_dll_set_callback */
569 for (i = 0; i < nb_dlls; i++)
571 if (!builtin_dlls[i].nt) continue;
572 if (!strcmp( builtin_dlls[i].filename, filename ))
574 const IMAGE_NT_HEADERS *nt = builtin_dlls[i].nt;
575 builtin_dlls[i].nt = NULL;
576 load_dll_callback( map_dll(nt), builtin_dlls[i].filename );
577 *file_exists = 1;
578 return (void *)1;
581 return dlopen_dll( filename, error, errorsize, 0, file_exists );
585 /***********************************************************************
586 * wine_dll_unload
588 * Unload a builtin dll.
590 void wine_dll_unload( void *handle )
592 if (handle != (void *)1)
593 wine_dlclose( handle, NULL, 0 );
597 /***********************************************************************
598 * wine_dll_load_main_exe
600 * Try to load the .so for the main exe.
602 void *wine_dll_load_main_exe( const char *name, char *error, int errorsize,
603 int test_only, int *file_exists )
605 return dlopen_dll( name, error, errorsize, test_only, file_exists );
609 /***********************************************************************
610 * wine_dll_enum_load_path
612 * Enumerate the dll load path.
614 const char *wine_dll_enum_load_path( unsigned int index )
616 if (index >= nb_dll_paths) return NULL;
617 return dll_paths[index];
621 /***********************************************************************
622 * wine_dll_get_owner
624 * Retrieve the name of the 32-bit owner dll for a 16-bit dll.
625 * Return 0 if OK, -1 on error.
627 int wine_dll_get_owner( const char *name, char *buffer, int size, int *exists )
629 int ret = -1;
630 char *path;
631 struct dll_path_context context;
633 *exists = 0;
635 for (path = first_dll_path( name, 1, &context ); path; path = next_dll_path( &context ))
637 int fd = open( path, O_RDONLY );
638 if (fd != -1)
640 int res = read( fd, buffer, size - 1 );
641 while (res > 0 && (buffer[res-1] == '\n' || buffer[res-1] == '\r')) res--;
642 buffer[res] = 0;
643 close( fd );
644 *exists = 1;
645 ret = 0;
646 break;
649 free_dll_path( &context );
650 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 (!getrlimit( limit, &rlimit ))
666 rlimit.rlim_cur = rlimit.rlim_max;
667 if (setrlimit( limit, &rlimit ) != 0)
669 #if defined(__APPLE__) && defined(RLIMIT_NOFILE) && defined(OPEN_MAX)
670 /* On Leopard, setrlimit(RLIMIT_NOFILE, ...) fails on attempts to set
671 * rlim_cur above OPEN_MAX (even if rlim_max > OPEN_MAX). */
672 if (limit == RLIMIT_NOFILE && rlimit.rlim_cur > OPEN_MAX)
674 rlimit.rlim_cur = OPEN_MAX;
675 setrlimit( limit, &rlimit );
677 #endif
680 #endif
684 #ifdef __APPLE__
685 struct apple_stack_info
687 void *stack;
688 size_t desired_size;
691 /***********************************************************************
692 * apple_alloc_thread_stack
694 * Callback for wine_mmap_enum_reserved_areas to allocate space for
695 * the secondary thread's stack.
697 static int apple_alloc_thread_stack( void *base, size_t size, void *arg )
699 struct apple_stack_info *info = arg;
701 /* For mysterious reasons, putting the thread stack at the very top
702 * of the address space causes subsequent execs to fail, even on the
703 * child side of a fork. Avoid the top 16MB. */
704 char * const limit = (char*)0xff000000;
705 if ((char *)base >= limit) return 0;
706 if (size > limit - (char*)base)
707 size = limit - (char*)base;
708 if (size < info->desired_size) return 0;
709 info->stack = wine_anon_mmap( (char *)base + size - info->desired_size,
710 info->desired_size, PROT_READ|PROT_WRITE, MAP_FIXED );
711 return (info->stack != (void *)-1);
714 /***********************************************************************
715 * apple_create_wine_thread
717 * Spin off a secondary thread to complete Wine initialization, leaving
718 * the original thread for the Mac frameworks.
720 * Invoked as a CFRunLoopSource perform callback.
722 static void apple_create_wine_thread( void *init_func )
724 int success = 0;
725 pthread_t thread;
726 pthread_attr_t attr;
728 if (!pthread_attr_init( &attr ))
730 struct apple_stack_info info;
732 /* Try to put the new thread's stack in the reserved area. If this
733 * fails, just let it go wherever. It'll be a waste of space, but we
734 * can go on. */
735 if (!pthread_attr_getstacksize( &attr, &info.desired_size ) &&
736 wine_mmap_enum_reserved_areas( apple_alloc_thread_stack, &info, 1 ))
738 wine_mmap_remove_reserved_area( info.stack, info.desired_size, 0 );
739 pthread_attr_setstackaddr( &attr, (char*)info.stack + info.desired_size );
742 if (!pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE ) &&
743 !pthread_create( &thread, &attr, init_func, NULL ))
744 success = 1;
746 pthread_attr_destroy( &attr );
749 /* Failure is indicated by returning from wine_init(). Stopping
750 * the run loop allows apple_main_thread() and thus wine_init() to
751 * return. */
752 if (!success)
753 CFRunLoopStop( CFRunLoopGetCurrent() );
757 /***********************************************************************
758 * apple_main_thread
760 * Park the process's original thread in a Core Foundation run loop for
761 * use by the Mac frameworks, especially receiving and handling
762 * distributed notifications. Spin off a new thread for the rest of the
763 * Wine initialization.
765 static void apple_main_thread( void (*init_func)(void) )
767 CFRunLoopSourceContext source_context = { 0 };
768 CFRunLoopSourceRef source;
770 if (!pthread_main_np())
772 init_func();
773 return;
776 /* Multi-processing Services can get confused about the main thread if the
777 * first time it's used is on a secondary thread. Use it here to make sure
778 * that doesn't happen. */
779 MPTaskIsPreemptive(MPCurrentTaskID());
781 /* Give ourselves the best chance of having the distributed notification
782 * center scheduled on this thread's run loop. In theory, it's scheduled
783 * in the first thread to ask for it. */
784 CFNotificationCenterGetDistributedCenter();
786 /* We use this run loop source for two purposes. First, a run loop exits
787 * if it has no more sources scheduled. So, we need at least one source
788 * to keep the run loop running. Second, although it's not critical, it's
789 * preferable for the Wine initialization to not proceed until we know
790 * the run loop is running. So, we signal our source immediately after
791 * adding it and have its callback spin off the Wine thread. */
792 source_context.info = init_func;
793 source_context.perform = apple_create_wine_thread;
794 source = CFRunLoopSourceCreate( NULL, 0, &source_context );
796 if (source)
798 CFRunLoopAddSource( CFRunLoopGetCurrent(), source, kCFRunLoopCommonModes );
799 CFRunLoopSourceSignal( source );
800 CFRelease( source );
802 CFRunLoopRun(); /* Should never return, except on error. */
805 /* If we get here (i.e. return), that indicates failure to our caller. */
807 #endif
810 #ifdef __ANDROID__
812 #ifndef WINE_JAVA_CLASS
813 #define WINE_JAVA_CLASS "org/winehq/wine/WineActivity"
814 #endif
816 static JavaVM *java_vm;
817 static jobject java_object;
819 /* return the Java VM that was used for JNI initialisation */
820 JavaVM *wine_get_java_vm(void)
822 return java_vm;
825 /* return the Java object that called the wine_init method */
826 jobject wine_get_java_object(void)
828 return java_object;
831 /* main Wine initialisation */
832 static jstring wine_init_jni( JNIEnv *env, jobject obj, jobjectArray cmdline, jobjectArray environment )
834 char **argv;
835 char *str;
836 char error[1024];
837 int i, argc, length;
839 /* get the command line array */
841 argc = (*env)->GetArrayLength( env, cmdline );
842 for (i = length = 0; i < argc; i++)
844 jobject str_obj = (*env)->GetObjectArrayElement( env, cmdline, i );
845 length += (*env)->GetStringUTFLength( env, str_obj ) + 1;
848 argv = malloc( (argc + 1) * sizeof(*argv) + length );
849 str = (char *)(argv + argc + 1);
850 for (i = 0; i < argc; i++)
852 jobject str_obj = (*env)->GetObjectArrayElement( env, cmdline, i );
853 length = (*env)->GetStringUTFLength( env, str_obj );
854 (*env)->GetStringUTFRegion( env, str_obj, 0, length, str );
855 argv[i] = str;
856 str[length] = 0;
857 str += length + 1;
859 argv[argc] = NULL;
861 /* set the environment variables */
863 if (environment)
865 int count = (*env)->GetArrayLength( env, environment );
866 for (i = 0; i < count - 1; i += 2)
868 jobject var_obj = (*env)->GetObjectArrayElement( env, environment, i );
869 jobject val_obj = (*env)->GetObjectArrayElement( env, environment, i + 1 );
870 const char *var = (*env)->GetStringUTFChars( env, var_obj, NULL );
872 if (val_obj)
874 const char *val = (*env)->GetStringUTFChars( env, val_obj, NULL );
875 setenv( var, val, 1 );
876 (*env)->ReleaseStringUTFChars( env, val_obj, val );
878 else unsetenv( var );
880 (*env)->ReleaseStringUTFChars( env, var_obj, var );
884 java_object = (*env)->NewGlobalRef( env, obj );
886 wine_init( argc, argv, error, sizeof(error) );
887 return (*env)->NewStringUTF( env, error );
890 jint JNI_OnLoad( JavaVM *vm, void *reserved )
892 static const JNINativeMethod method =
894 "wine_init", "([Ljava/lang/String;[Ljava/lang/String;)Ljava/lang/String;", wine_init_jni
897 JNIEnv *env;
898 jclass class;
900 java_vm = vm;
901 if ((*vm)->AttachCurrentThread( vm, &env, NULL ) != JNI_OK) return JNI_ERR;
902 if (!(class = (*env)->FindClass( env, WINE_JAVA_CLASS ))) return JNI_ERR;
903 (*env)->RegisterNatives( env, class, &method, 1 );
904 return JNI_VERSION_1_6;
907 #endif /* __ANDROID__ */
909 /***********************************************************************
910 * wine_init
912 * Main Wine initialisation.
914 void wine_init( int argc, char *argv[], char *error, int error_size )
916 struct dll_path_context context;
917 char *path;
918 void *ntdll = NULL;
919 void (*init_func)(void);
921 /* force a few limits that are set too low on some platforms */
922 #ifdef RLIMIT_NOFILE
923 set_max_limit( RLIMIT_NOFILE );
924 #endif
925 #ifdef RLIMIT_AS
926 set_max_limit( RLIMIT_AS );
927 #endif
929 wine_init_argv0_path( argv[0] );
930 build_dll_path();
931 __wine_main_argc = argc;
932 __wine_main_argv = argv;
933 __wine_main_environ = __wine_get_main_environment();
934 mmap_init();
936 for (path = first_dll_path( "ntdll.dll", 0, &context ); path; path = next_dll_path( &context ))
938 if ((ntdll = wine_dlopen( path, RTLD_NOW, error, error_size )))
940 /* if we didn't use the default dll dir, remove it from the search path */
941 if (default_dlldir[0] && context.index < nb_dll_paths + 2) nb_dll_paths--;
942 break;
945 free_dll_path( &context );
947 if (!ntdll) return;
948 if (!(init_func = wine_dlsym( ntdll, "__wine_process_init", error, error_size ))) return;
949 #ifdef __APPLE__
950 apple_main_thread( init_func );
951 #else
952 init_func();
953 #endif
958 * These functions provide wrappers around dlopen() and associated
959 * functions. They work around a bug in glibc 2.1.x where calling
960 * a dl*() function after a previous dl*() function has failed
961 * without a dlerror() call between the two will cause a crash.
962 * They all take a pointer to a buffer that
963 * will receive the error description (from dlerror()). This
964 * parameter may be NULL if the error description is not required.
967 #ifndef RTLD_FIRST
968 #define RTLD_FIRST 0
969 #endif
971 /***********************************************************************
972 * wine_dlopen
974 void *wine_dlopen( const char *filename, int flag, char *error, size_t errorsize )
976 #ifdef HAVE_DLOPEN
977 void *ret;
978 const char *s;
980 #ifdef __APPLE__
981 /* the Mac OS loader pretends to be able to load PE files, so avoid them here */
982 unsigned char magic[2];
983 int fd = open( filename, O_RDONLY );
984 if (fd != -1)
986 if (pread( fd, magic, 2, 0 ) == 2 && magic[0] == 'M' && magic[1] == 'Z')
988 if (error && errorsize)
990 static const char msg[] = "MZ format";
991 size_t len = min( errorsize, sizeof(msg) );
992 memcpy( error, msg, len );
993 error[len - 1] = 0;
995 close( fd );
996 return NULL;
998 close( fd );
1000 #endif
1001 dlerror(); dlerror();
1002 #ifdef __sun
1003 if (strchr( filename, ':' ))
1005 char path[PATH_MAX];
1006 /* Solaris' brain damaged dlopen() treats ':' as a path separator */
1007 realpath( filename, path );
1008 ret = dlopen( path, flag | RTLD_FIRST );
1010 else
1011 #elif defined(__ANDROID__)
1012 if (!strchr( filename, '/' ) && nb_dll_paths)
1014 unsigned int i;
1015 char *buffer = malloc( dll_path_maxlen + strlen(filename) + 2 );
1017 buffer[dll_path_maxlen] = '/';
1018 strcpy( buffer + dll_path_maxlen + 1, filename );
1019 for (i = 0; i < nb_dll_paths; i++)
1021 char *path = prepend( buffer + dll_path_maxlen, dll_paths[i], strlen(dll_paths[i]) );
1022 ret = dlopen( path, flag | RTLD_FIRST );
1023 if (ret) break;
1025 free( buffer );
1026 if (ret) return ret;
1028 #endif
1029 ret = dlopen( filename, flag | RTLD_FIRST );
1030 s = dlerror();
1031 if (error && errorsize)
1033 if (s)
1035 size_t len = strlen(s);
1036 if (len >= errorsize) len = errorsize - 1;
1037 memcpy( error, s, len );
1038 error[len] = 0;
1040 else error[0] = 0;
1042 dlerror();
1043 return ret;
1044 #else
1045 if (error)
1047 static const char msg[] = "dlopen interface not detected by configure";
1048 size_t len = min( errorsize, sizeof(msg) );
1049 memcpy( error, msg, len );
1050 error[len - 1] = 0;
1052 return NULL;
1053 #endif
1056 /***********************************************************************
1057 * wine_dlsym
1059 void *wine_dlsym( void *handle, const char *symbol, char *error, size_t errorsize )
1061 #ifdef HAVE_DLOPEN
1062 void *ret;
1063 const char *s;
1064 dlerror(); dlerror();
1065 ret = dlsym( handle, symbol );
1066 s = dlerror();
1067 if (error && errorsize)
1069 if (s)
1071 size_t len = strlen(s);
1072 if (len >= errorsize) len = errorsize - 1;
1073 memcpy( error, s, len );
1074 error[len] = 0;
1076 else error[0] = 0;
1078 dlerror();
1079 return ret;
1080 #else
1081 if (error)
1083 static const char msg[] = "dlopen interface not detected by configure";
1084 size_t len = min( errorsize, sizeof(msg) );
1085 memcpy( error, msg, len );
1086 error[len - 1] = 0;
1088 return NULL;
1089 #endif
1092 /***********************************************************************
1093 * wine_dlclose
1095 int wine_dlclose( void *handle, char *error, size_t errorsize )
1097 #ifdef HAVE_DLOPEN
1098 int ret;
1099 const char *s;
1100 dlerror(); dlerror();
1101 ret = dlclose( handle );
1102 s = dlerror();
1103 if (error && errorsize)
1105 if (s)
1107 size_t len = strlen(s);
1108 if (len >= errorsize) len = errorsize - 1;
1109 memcpy( error, s, len );
1110 error[len] = 0;
1112 else error[0] = 0;
1114 dlerror();
1115 return ret;
1116 #else
1117 if (error)
1119 static const char msg[] = "dlopen interface not detected by configure";
1120 size_t len = min( errorsize, sizeof(msg) );
1121 memcpy( error, msg, len );
1122 error[len - 1] = 0;
1124 return 1;
1125 #endif