user32: Check the DpiScalingVer registry key to enable DPI scaling.
[wine.git] / libs / wine / loader.c
blobc07042a583e6a6a433e8dbfff0d879dbd545318d
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_paths;
98 static unsigned int nb_dll_paths;
99 static int dll_path_maxlen;
101 extern void mmap_init(void);
102 extern const char *get_dlldir( const char **default_dlldir );
104 /* build the dll load path from the WINEDLLPATH variable */
105 static void build_dll_path(void)
107 int len, count = 0;
108 char *p, *path = getenv( "WINEDLLPATH" );
109 const char *dlldir = get_dlldir( &default_dlldir );
111 if (path)
113 /* count how many path elements we need */
114 path = strdup(path);
115 p = path;
116 while (*p)
118 while (*p == ':') p++;
119 if (!*p) break;
120 count++;
121 while (*p && *p != ':') p++;
125 dll_paths = malloc( (count+2) * sizeof(*dll_paths) );
126 nb_dll_paths = 0;
128 if (dlldir)
130 dll_path_maxlen = strlen(dlldir);
131 dll_paths[nb_dll_paths++] = dlldir;
133 else if ((build_dir = wine_get_build_dir()))
135 dll_path_maxlen = strlen(build_dir) + sizeof("/programs");
138 if (count)
140 p = path;
141 while (*p)
143 while (*p == ':') *p++ = 0;
144 if (!*p) break;
145 dll_paths[nb_dll_paths] = p;
146 while (*p && *p != ':') p++;
147 if (p - dll_paths[nb_dll_paths] > dll_path_maxlen)
148 dll_path_maxlen = p - dll_paths[nb_dll_paths];
149 nb_dll_paths++;
153 /* append default dll dir (if not empty) to path */
154 if ((len = strlen(default_dlldir)) > 0)
156 if (len > dll_path_maxlen) dll_path_maxlen = len;
157 dll_paths[nb_dll_paths++] = default_dlldir;
161 /* check if the library is the correct architecture */
162 /* only returns false for a valid library of the wrong arch */
163 static int check_library_arch( int fd )
165 #ifdef __APPLE__
166 struct /* Mach-O header */
168 unsigned int magic;
169 unsigned int cputype;
170 } header;
172 if (read( fd, &header, sizeof(header) ) != sizeof(header)) return 1;
173 if (header.magic != 0xfeedface) return 1;
174 if (sizeof(void *) == sizeof(int)) return !(header.cputype >> 24);
175 else return (header.cputype >> 24) == 1; /* CPU_ARCH_ABI64 */
176 #else
177 struct /* ELF header */
179 unsigned char magic[4];
180 unsigned char class;
181 unsigned char data;
182 unsigned char version;
183 } header;
185 if (read( fd, &header, sizeof(header) ) != sizeof(header)) return 1;
186 if (memcmp( header.magic, "\177ELF", 4 )) return 1;
187 if (header.version != 1 /* EV_CURRENT */) return 1;
188 #ifdef WORDS_BIGENDIAN
189 if (header.data != 2 /* ELFDATA2MSB */) return 1;
190 #else
191 if (header.data != 1 /* ELFDATA2LSB */) return 1;
192 #endif
193 if (sizeof(void *) == sizeof(int)) return header.class == 1; /* ELFCLASS32 */
194 else return header.class == 2; /* ELFCLASS64 */
195 #endif
198 /* check if a given file can be opened */
199 static inline int file_exists( const char *name )
201 int ret = 0;
202 int fd = open( name, O_RDONLY );
203 if (fd != -1)
205 ret = check_library_arch( fd );
206 close( fd );
208 return ret;
211 static inline char *prepend( char *buffer, const char *str, size_t len )
213 return memcpy( buffer - len, str, len );
216 /* get a filename from the next entry in the dll path */
217 static char *next_dll_path( struct dll_path_context *context )
219 unsigned int index = context->index++;
220 int namelen = context->namelen;
221 char *path = context->name;
223 switch(index)
225 case 0: /* try dlls dir with subdir prefix */
226 if (namelen > 4 && !memcmp( context->name + namelen - 4, ".dll", 4 )) namelen -= 4;
227 if (!context->win16) path = prepend( path, context->name, namelen );
228 path = prepend( path, "/dlls", sizeof("/dlls") - 1 );
229 path = prepend( path, build_dir, strlen(build_dir) );
230 return path;
231 case 1: /* try programs dir with subdir prefix */
232 if (!context->win16)
234 if (namelen > 4 && !memcmp( context->name + namelen - 4, ".exe", 4 )) namelen -= 4;
235 path = prepend( path, context->name, namelen );
236 path = prepend( path, "/programs", sizeof("/programs") - 1 );
237 path = prepend( path, build_dir, strlen(build_dir) );
238 return path;
240 context->index++;
241 /* fall through */
242 default:
243 index -= 2;
244 if (index >= nb_dll_paths) return NULL;
245 path = prepend( path, dll_paths[index], strlen( dll_paths[index] ));
246 return path;
251 /* get a filename from the first entry in the dll path */
252 static char *first_dll_path( const char *name, int win16, struct dll_path_context *context )
254 char *p;
255 int namelen = strlen( name );
256 const char *ext = win16 ? "16" : ".so";
258 context->buffer = malloc( dll_path_maxlen + 2 * namelen + strlen(ext) + 3 );
259 context->index = build_dir ? 0 : 2; /* if no build dir skip all the build dir magic cases */
260 context->name = context->buffer + dll_path_maxlen + namelen + 1;
261 context->namelen = namelen + 1;
262 context->win16 = win16;
264 /* store the name at the end of the buffer, followed by extension */
265 p = context->name;
266 *p++ = '/';
267 memcpy( p, name, namelen );
268 strcpy( p + namelen, ext );
269 return next_dll_path( context );
273 /* free the dll path context created by first_dll_path */
274 static inline void free_dll_path( struct dll_path_context *context )
276 free( context->buffer );
280 /* open a library for a given dll, searching in the dll path
281 * 'name' must be the Windows dll name (e.g. "kernel32.dll") */
282 static void *dlopen_dll( const char *name, char *error, int errorsize,
283 int test_only, int *exists )
285 struct dll_path_context context;
286 char *path;
287 void *ret = NULL;
289 *exists = 0;
290 for (path = first_dll_path( name, 0, &context ); path; path = next_dll_path( &context ))
292 if (!test_only && (ret = wine_dlopen( path, RTLD_NOW, error, errorsize ))) break;
293 if ((*exists = file_exists( path ))) break; /* exists but cannot be loaded, return the error */
295 free_dll_path( &context );
296 return ret;
300 /* adjust an array of pointers to make them into RVAs */
301 static inline void fixup_rva_ptrs( void *array, BYTE *base, unsigned int count )
303 void **src = (void **)array;
304 DWORD *dst = (DWORD *)array;
305 while (count--)
307 *dst++ = *src ? (BYTE *)*src - base : 0;
308 src++;
312 /* fixup an array of RVAs by adding the specified delta */
313 static inline void fixup_rva_dwords( DWORD *ptr, int delta, unsigned int count )
315 while (count--)
317 if (*ptr) *ptr += delta;
318 ptr++;
323 /* fixup an array of name/ordinal RVAs by adding the specified delta */
324 static inline void fixup_rva_names( UINT_PTR *ptr, int delta )
326 while (*ptr)
328 if (!(*ptr & IMAGE_ORDINAL_FLAG)) *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 while (dir->Name)
339 fixup_rva_dwords( &dir->u.OriginalFirstThunk, delta, 1 );
340 fixup_rva_dwords( &dir->Name, delta, 1 );
341 fixup_rva_dwords( &dir->FirstThunk, delta, 1 );
342 if (dir->u.OriginalFirstThunk) fixup_rva_names( (UINT_PTR *)(base + dir->u.OriginalFirstThunk), delta );
343 if (dir->FirstThunk) fixup_rva_names( (UINT_PTR *)(base + dir->FirstThunk), delta );
344 dir++;
349 /* fixup RVAs in the export directory */
350 static void fixup_exports( IMAGE_EXPORT_DIRECTORY *dir, BYTE *base, int delta )
352 fixup_rva_dwords( &dir->Name, delta, 1 );
353 fixup_rva_dwords( &dir->AddressOfFunctions, delta, 1 );
354 fixup_rva_dwords( &dir->AddressOfNames, delta, 1 );
355 fixup_rva_dwords( &dir->AddressOfNameOrdinals, delta, 1 );
356 fixup_rva_dwords( (DWORD *)(base + dir->AddressOfNames), delta, dir->NumberOfNames );
357 fixup_rva_ptrs( (base + dir->AddressOfFunctions), base, dir->NumberOfFunctions );
361 /* fixup RVAs in the resource directory */
362 static void fixup_resources( IMAGE_RESOURCE_DIRECTORY *dir, BYTE *root, int delta )
364 IMAGE_RESOURCE_DIRECTORY_ENTRY *entry;
365 int i;
367 entry = (IMAGE_RESOURCE_DIRECTORY_ENTRY *)(dir + 1);
368 for (i = 0; i < dir->NumberOfNamedEntries + dir->NumberOfIdEntries; i++, entry++)
370 void *ptr = root + entry->u2.s2.OffsetToDirectory;
371 if (entry->u2.s2.DataIsDirectory) fixup_resources( ptr, root, delta );
372 else
374 IMAGE_RESOURCE_DATA_ENTRY *data = ptr;
375 fixup_rva_dwords( &data->OffsetToData, delta, 1 );
381 /* map a builtin dll in memory and fixup RVAs */
382 static void *map_dll( const IMAGE_NT_HEADERS *nt_descr )
384 #ifdef HAVE_MMAP
385 IMAGE_DATA_DIRECTORY *dir;
386 IMAGE_DOS_HEADER *dos;
387 IMAGE_NT_HEADERS *nt;
388 IMAGE_SECTION_HEADER *sec;
389 BYTE *addr;
390 DWORD code_start, data_start, data_end;
391 const size_t page_size = sysconf( _SC_PAGESIZE );
392 const size_t page_mask = page_size - 1;
393 int delta, nb_sections = 2; /* code + data */
394 unsigned int i;
396 size_t size = (sizeof(IMAGE_DOS_HEADER)
397 + sizeof(IMAGE_NT_HEADERS)
398 + nb_sections * sizeof(IMAGE_SECTION_HEADER));
400 assert( size <= page_size );
402 /* module address must be aligned on 64K boundary */
403 addr = (BYTE *)((nt_descr->OptionalHeader.ImageBase + 0xffff) & ~0xffff);
404 if (wine_anon_mmap( addr, page_size, PROT_READ|PROT_WRITE, MAP_FIXED ) != addr) return NULL;
406 dos = (IMAGE_DOS_HEADER *)addr;
407 nt = (IMAGE_NT_HEADERS *)(dos + 1);
408 sec = (IMAGE_SECTION_HEADER *)(nt + 1);
410 /* Build the DOS and NT headers */
412 dos->e_magic = IMAGE_DOS_SIGNATURE;
413 dos->e_cblp = 0x90;
414 dos->e_cp = 3;
415 dos->e_cparhdr = (sizeof(*dos)+0xf)/0x10;
416 dos->e_minalloc = 0;
417 dos->e_maxalloc = 0xffff;
418 dos->e_ss = 0x0000;
419 dos->e_sp = 0x00b8;
420 dos->e_lfarlc = sizeof(*dos);
421 dos->e_lfanew = sizeof(*dos);
423 *nt = *nt_descr;
425 delta = (const BYTE *)nt_descr - addr;
426 code_start = page_size;
427 data_start = delta & ~page_mask;
428 data_end = (nt->OptionalHeader.SizeOfImage + delta + page_mask) & ~page_mask;
430 fixup_rva_ptrs( &nt->OptionalHeader.AddressOfEntryPoint, addr, 1 );
432 nt->FileHeader.NumberOfSections = nb_sections;
433 nt->OptionalHeader.BaseOfCode = code_start;
434 #ifndef _WIN64
435 nt->OptionalHeader.BaseOfData = data_start;
436 #endif
437 nt->OptionalHeader.SizeOfCode = data_start - code_start;
438 nt->OptionalHeader.SizeOfInitializedData = data_end - data_start;
439 nt->OptionalHeader.SizeOfUninitializedData = 0;
440 nt->OptionalHeader.SizeOfImage = data_end;
441 nt->OptionalHeader.ImageBase = (ULONG_PTR)addr;
443 /* Build the code section */
445 memcpy( sec->Name, ".text", sizeof(".text") );
446 sec->SizeOfRawData = data_start - code_start;
447 sec->Misc.VirtualSize = sec->SizeOfRawData;
448 sec->VirtualAddress = code_start;
449 sec->PointerToRawData = code_start;
450 sec->Characteristics = (IMAGE_SCN_CNT_CODE | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_MEM_READ);
451 sec++;
453 /* Build the data section */
455 memcpy( sec->Name, ".data", sizeof(".data") );
456 sec->SizeOfRawData = data_end - data_start;
457 sec->Misc.VirtualSize = sec->SizeOfRawData;
458 sec->VirtualAddress = data_start;
459 sec->PointerToRawData = data_start;
460 sec->Characteristics = (IMAGE_SCN_CNT_INITIALIZED_DATA |
461 IMAGE_SCN_MEM_WRITE | IMAGE_SCN_MEM_READ);
462 sec++;
464 for (i = 0; i < nt->OptionalHeader.NumberOfRvaAndSizes; i++)
465 fixup_rva_dwords( &nt->OptionalHeader.DataDirectory[i].VirtualAddress, delta, 1 );
467 /* Build the import directory */
469 dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_IMPORT_DIRECTORY];
470 if (dir->Size)
472 IMAGE_IMPORT_DESCRIPTOR *imports = (void *)(addr + dir->VirtualAddress);
473 fixup_imports( imports, addr, delta );
476 /* Build the resource directory */
478 dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_RESOURCE_DIRECTORY];
479 if (dir->Size)
481 void *ptr = (void *)(addr + dir->VirtualAddress);
482 fixup_resources( ptr, ptr, delta );
485 /* Build the export directory */
487 dir = &nt->OptionalHeader.DataDirectory[IMAGE_FILE_EXPORT_DIRECTORY];
488 if (dir->Size)
490 IMAGE_EXPORT_DIRECTORY *exports = (void *)(addr + dir->VirtualAddress);
491 fixup_exports( exports, addr, delta );
493 return addr;
494 #else /* HAVE_MMAP */
495 return NULL;
496 #endif /* HAVE_MMAP */
500 /***********************************************************************
501 * __wine_get_main_environment
503 * Return an environment pointer to work around lack of environ variable.
504 * Only exported on Mac OS.
506 char **__wine_get_main_environment(void)
508 return environ;
512 /***********************************************************************
513 * __wine_dll_register
515 * Register a built-in DLL descriptor.
517 void __wine_dll_register( const IMAGE_NT_HEADERS *header, const char *filename )
519 if (load_dll_callback) load_dll_callback( map_dll(header), filename );
520 else
522 if (!(header->FileHeader.Characteristics & IMAGE_FILE_DLL))
523 main_exe = header;
524 else
526 assert( nb_dlls < MAX_DLLS );
527 builtin_dlls[nb_dlls].nt = header;
528 builtin_dlls[nb_dlls].filename = filename;
529 nb_dlls++;
535 /***********************************************************************
536 * wine_dll_set_callback
538 * Set the callback function for dll loading, and call it
539 * for all dlls that were implicitly loaded already.
541 void wine_dll_set_callback( load_dll_callback_t load )
543 int i;
544 load_dll_callback = load;
545 for (i = 0; i < nb_dlls; i++)
547 const IMAGE_NT_HEADERS *nt = builtin_dlls[i].nt;
548 if (!nt) continue;
549 builtin_dlls[i].nt = NULL;
550 load_dll_callback( map_dll(nt), builtin_dlls[i].filename );
552 nb_dlls = 0;
553 if (main_exe) load_dll_callback( map_dll(main_exe), "" );
557 /***********************************************************************
558 * wine_dll_load
560 * Load a builtin dll.
562 void *wine_dll_load( const char *filename, char *error, int errorsize, int *file_exists )
564 int i;
566 /* callback must have been set already */
567 assert( load_dll_callback );
569 /* check if we have it in the list */
570 /* this can happen when initializing pre-loaded dlls in wine_dll_set_callback */
571 for (i = 0; i < nb_dlls; i++)
573 if (!builtin_dlls[i].nt) continue;
574 if (!strcmp( builtin_dlls[i].filename, filename ))
576 const IMAGE_NT_HEADERS *nt = builtin_dlls[i].nt;
577 builtin_dlls[i].nt = NULL;
578 load_dll_callback( map_dll(nt), builtin_dlls[i].filename );
579 *file_exists = 1;
580 return (void *)1;
583 return dlopen_dll( filename, error, errorsize, 0, file_exists );
587 /***********************************************************************
588 * wine_dll_unload
590 * Unload a builtin dll.
592 void wine_dll_unload( void *handle )
594 if (handle != (void *)1)
595 wine_dlclose( handle, NULL, 0 );
599 /***********************************************************************
600 * wine_dll_load_main_exe
602 * Try to load the .so for the main exe.
604 void *wine_dll_load_main_exe( const char *name, char *error, int errorsize,
605 int test_only, int *file_exists )
607 return dlopen_dll( name, error, errorsize, test_only, file_exists );
611 /***********************************************************************
612 * wine_dll_enum_load_path
614 * Enumerate the dll load path.
616 const char *wine_dll_enum_load_path( unsigned int index )
618 if (index >= nb_dll_paths) return NULL;
619 return dll_paths[index];
623 /***********************************************************************
624 * wine_dll_get_owner
626 * Retrieve the name of the 32-bit owner dll for a 16-bit dll.
627 * Return 0 if OK, -1 on error.
629 int wine_dll_get_owner( const char *name, char *buffer, int size, int *exists )
631 int ret = -1;
632 char *path;
633 struct dll_path_context context;
635 *exists = 0;
637 for (path = first_dll_path( name, 1, &context ); path; path = next_dll_path( &context ))
639 int fd = open( path, O_RDONLY );
640 if (fd != -1)
642 int res = read( fd, buffer, size - 1 );
643 while (res > 0 && (buffer[res-1] == '\n' || buffer[res-1] == '\r')) res--;
644 buffer[res] = 0;
645 close( fd );
646 *exists = 1;
647 ret = 0;
648 break;
651 free_dll_path( &context );
652 return ret;
656 /***********************************************************************
657 * set_max_limit
659 * Set a user limit to the maximum allowed value.
661 static void set_max_limit( int limit )
663 #ifdef HAVE_SETRLIMIT
664 struct rlimit rlimit;
666 if (!getrlimit( limit, &rlimit ))
668 rlimit.rlim_cur = rlimit.rlim_max;
669 if (setrlimit( limit, &rlimit ) != 0)
671 #if defined(__APPLE__) && defined(RLIMIT_NOFILE) && defined(OPEN_MAX)
672 /* On Leopard, setrlimit(RLIMIT_NOFILE, ...) fails on attempts to set
673 * rlim_cur above OPEN_MAX (even if rlim_max > OPEN_MAX). */
674 if (limit == RLIMIT_NOFILE && rlimit.rlim_cur > OPEN_MAX)
676 rlimit.rlim_cur = OPEN_MAX;
677 setrlimit( limit, &rlimit );
679 #endif
682 #endif
686 #ifdef __APPLE__
687 struct apple_stack_info
689 void *stack;
690 size_t desired_size;
693 /***********************************************************************
694 * apple_alloc_thread_stack
696 * Callback for wine_mmap_enum_reserved_areas to allocate space for
697 * the secondary thread's stack.
699 static int apple_alloc_thread_stack( void *base, size_t size, void *arg )
701 struct apple_stack_info *info = arg;
703 /* For mysterious reasons, putting the thread stack at the very top
704 * of the address space causes subsequent execs to fail, even on the
705 * child side of a fork. Avoid the top 16MB. */
706 char * const limit = (char*)0xff000000;
707 if ((char *)base >= limit) return 0;
708 if (size > limit - (char*)base)
709 size = limit - (char*)base;
710 if (size < info->desired_size) return 0;
711 info->stack = wine_anon_mmap( (char *)base + size - info->desired_size,
712 info->desired_size, PROT_READ|PROT_WRITE, MAP_FIXED );
713 return (info->stack != (void *)-1);
716 /***********************************************************************
717 * apple_create_wine_thread
719 * Spin off a secondary thread to complete Wine initialization, leaving
720 * the original thread for the Mac frameworks.
722 * Invoked as a CFRunLoopSource perform callback.
724 static void apple_create_wine_thread( void *init_func )
726 int success = 0;
727 pthread_t thread;
728 pthread_attr_t attr;
730 if (!pthread_attr_init( &attr ))
732 struct apple_stack_info info;
734 /* Try to put the new thread's stack in the reserved area. If this
735 * fails, just let it go wherever. It'll be a waste of space, but we
736 * can go on. */
737 if (!pthread_attr_getstacksize( &attr, &info.desired_size ) &&
738 wine_mmap_enum_reserved_areas( apple_alloc_thread_stack, &info, 1 ))
740 wine_mmap_remove_reserved_area( info.stack, info.desired_size, 0 );
741 pthread_attr_setstackaddr( &attr, (char*)info.stack + info.desired_size );
744 if (!pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE ) &&
745 !pthread_create( &thread, &attr, init_func, NULL ))
746 success = 1;
748 pthread_attr_destroy( &attr );
751 /* Failure is indicated by returning from wine_init(). Stopping
752 * the run loop allows apple_main_thread() and thus wine_init() to
753 * return. */
754 if (!success)
755 CFRunLoopStop( CFRunLoopGetCurrent() );
759 /***********************************************************************
760 * apple_main_thread
762 * Park the process's original thread in a Core Foundation run loop for
763 * use by the Mac frameworks, especially receiving and handling
764 * distributed notifications. Spin off a new thread for the rest of the
765 * Wine initialization.
767 static void apple_main_thread( void (*init_func)(void) )
769 CFRunLoopSourceContext source_context = { 0 };
770 CFRunLoopSourceRef source;
772 if (!pthread_main_np())
774 init_func();
775 return;
778 /* Multi-processing Services can get confused about the main thread if the
779 * first time it's used is on a secondary thread. Use it here to make sure
780 * that doesn't happen. */
781 MPTaskIsPreemptive(MPCurrentTaskID());
783 /* Give ourselves the best chance of having the distributed notification
784 * center scheduled on this thread's run loop. In theory, it's scheduled
785 * in the first thread to ask for it. */
786 CFNotificationCenterGetDistributedCenter();
788 /* We use this run loop source for two purposes. First, a run loop exits
789 * if it has no more sources scheduled. So, we need at least one source
790 * to keep the run loop running. Second, although it's not critical, it's
791 * preferable for the Wine initialization to not proceed until we know
792 * the run loop is running. So, we signal our source immediately after
793 * adding it and have its callback spin off the Wine thread. */
794 source_context.info = init_func;
795 source_context.perform = apple_create_wine_thread;
796 source = CFRunLoopSourceCreate( NULL, 0, &source_context );
798 if (source)
800 CFRunLoopAddSource( CFRunLoopGetCurrent(), source, kCFRunLoopCommonModes );
801 CFRunLoopSourceSignal( source );
802 CFRelease( source );
804 CFRunLoopRun(); /* Should never return, except on error. */
807 /* If we get here (i.e. return), that indicates failure to our caller. */
809 #endif
812 #ifdef __ANDROID__
814 #ifndef WINE_JAVA_CLASS
815 #define WINE_JAVA_CLASS "org/winehq/wine/WineActivity"
816 #endif
818 static JavaVM *java_vm;
819 static jobject java_object;
821 /* return the Java VM that was used for JNI initialisation */
822 JavaVM *wine_get_java_vm(void)
824 return java_vm;
827 /* return the Java object that called the wine_init method */
828 jobject wine_get_java_object(void)
830 return java_object;
833 /* main Wine initialisation */
834 static jstring wine_init_jni( JNIEnv *env, jobject obj, jobjectArray cmdline, jobjectArray environment )
836 char **argv;
837 char *str;
838 char error[1024];
839 int i, argc, length;
841 /* get the command line array */
843 argc = (*env)->GetArrayLength( env, cmdline );
844 for (i = length = 0; i < argc; i++)
846 jobject str_obj = (*env)->GetObjectArrayElement( env, cmdline, i );
847 length += (*env)->GetStringUTFLength( env, str_obj ) + 1;
850 argv = malloc( (argc + 1) * sizeof(*argv) + length );
851 str = (char *)(argv + argc + 1);
852 for (i = 0; i < argc; i++)
854 jobject str_obj = (*env)->GetObjectArrayElement( env, cmdline, i );
855 length = (*env)->GetStringUTFLength( env, str_obj );
856 (*env)->GetStringUTFRegion( env, str_obj, 0,
857 (*env)->GetStringLength( env, str_obj ), str );
858 argv[i] = str;
859 str[length] = 0;
860 str += length + 1;
862 argv[argc] = NULL;
864 /* set the environment variables */
866 if (environment)
868 int count = (*env)->GetArrayLength( env, environment );
869 for (i = 0; i < count - 1; i += 2)
871 jobject var_obj = (*env)->GetObjectArrayElement( env, environment, i );
872 jobject val_obj = (*env)->GetObjectArrayElement( env, environment, i + 1 );
873 const char *var = (*env)->GetStringUTFChars( env, var_obj, NULL );
875 if (val_obj)
877 const char *val = (*env)->GetStringUTFChars( env, val_obj, NULL );
878 setenv( var, val, 1 );
879 if (!strcmp( var, "LD_LIBRARY_PATH" ))
881 void (*update_func)( const char * ) = dlsym( RTLD_DEFAULT,
882 "android_update_LD_LIBRARY_PATH" );
883 if (update_func) update_func( val );
885 else if (!strcmp( var, "WINEDEBUGLOG" ))
887 int fd = open( val, O_WRONLY | O_CREAT | O_APPEND, 0666 );
888 if (fd != -1)
890 dup2( fd, 2 );
891 close( fd );
894 (*env)->ReleaseStringUTFChars( env, val_obj, val );
896 else unsetenv( var );
898 (*env)->ReleaseStringUTFChars( env, var_obj, var );
902 java_object = (*env)->NewGlobalRef( env, obj );
904 #ifdef __i386__
906 unsigned short java_fs = wine_get_fs();
907 wine_set_fs( 0 );
908 wine_init( argc, argv, error, sizeof(error) );
909 wine_set_fs( java_fs );
911 #else
912 wine_init( argc, argv, error, sizeof(error) );
913 #endif
914 return (*env)->NewStringUTF( env, error );
917 jint JNI_OnLoad( JavaVM *vm, void *reserved )
919 static const JNINativeMethod method =
921 "wine_init", "([Ljava/lang/String;[Ljava/lang/String;)Ljava/lang/String;", wine_init_jni
924 JNIEnv *env;
925 jclass class;
927 java_vm = vm;
928 if ((*vm)->AttachCurrentThread( vm, &env, NULL ) != JNI_OK) return JNI_ERR;
929 if (!(class = (*env)->FindClass( env, WINE_JAVA_CLASS ))) return JNI_ERR;
930 (*env)->RegisterNatives( env, class, &method, 1 );
931 return JNI_VERSION_1_6;
934 #endif /* __ANDROID__ */
936 /***********************************************************************
937 * wine_init
939 * Main Wine initialisation.
941 void wine_init( int argc, char *argv[], char *error, int error_size )
943 struct dll_path_context context;
944 char *path;
945 void *ntdll = NULL;
946 void (*init_func)(void);
948 /* force a few limits that are set too low on some platforms */
949 #ifdef RLIMIT_NOFILE
950 set_max_limit( RLIMIT_NOFILE );
951 #endif
952 #ifdef RLIMIT_AS
953 set_max_limit( RLIMIT_AS );
954 #endif
956 wine_init_argv0_path( argv[0] );
957 build_dll_path();
958 __wine_main_argc = argc;
959 __wine_main_argv = argv;
960 __wine_main_environ = __wine_get_main_environment();
961 mmap_init();
963 for (path = first_dll_path( "ntdll.dll", 0, &context ); path; path = next_dll_path( &context ))
965 if ((ntdll = wine_dlopen( path, RTLD_NOW, error, error_size )))
967 /* if we didn't use the default dll dir, remove it from the search path */
968 if (default_dlldir[0] && context.index < nb_dll_paths + 2) nb_dll_paths--;
969 break;
972 free_dll_path( &context );
974 if (!ntdll) return;
975 if (!(init_func = wine_dlsym( ntdll, "__wine_process_init", error, error_size ))) return;
976 #ifdef __APPLE__
977 apple_main_thread( init_func );
978 #else
979 init_func();
980 #endif
985 * These functions provide wrappers around dlopen() and associated
986 * functions. They work around a bug in glibc 2.1.x where calling
987 * a dl*() function after a previous dl*() function has failed
988 * without a dlerror() call between the two will cause a crash.
989 * They all take a pointer to a buffer that
990 * will receive the error description (from dlerror()). This
991 * parameter may be NULL if the error description is not required.
994 #ifndef RTLD_FIRST
995 #define RTLD_FIRST 0
996 #endif
998 /***********************************************************************
999 * wine_dlopen
1001 void *wine_dlopen( const char *filename, int flag, char *error, size_t errorsize )
1003 #ifdef HAVE_DLOPEN
1004 void *ret;
1005 const char *s;
1007 #ifdef __APPLE__
1008 /* the Mac OS loader pretends to be able to load PE files, so avoid them here */
1009 unsigned char magic[2];
1010 int fd = open( filename, O_RDONLY );
1011 if (fd != -1)
1013 if (pread( fd, magic, 2, 0 ) == 2 && magic[0] == 'M' && magic[1] == 'Z')
1015 if (error && errorsize)
1017 static const char msg[] = "MZ format";
1018 size_t len = min( errorsize, sizeof(msg) );
1019 memcpy( error, msg, len );
1020 error[len - 1] = 0;
1022 close( fd );
1023 return NULL;
1025 close( fd );
1027 #endif
1028 dlerror(); dlerror();
1029 #ifdef __sun
1030 if (strchr( filename, ':' ))
1032 char path[PATH_MAX];
1033 /* Solaris' brain damaged dlopen() treats ':' as a path separator */
1034 realpath( filename, path );
1035 ret = dlopen( path, flag | RTLD_FIRST );
1037 else
1038 #endif
1039 ret = dlopen( filename, flag | RTLD_FIRST );
1040 s = dlerror();
1041 if (error && errorsize)
1043 if (s)
1045 size_t len = strlen(s);
1046 if (len >= errorsize) len = errorsize - 1;
1047 memcpy( error, s, len );
1048 error[len] = 0;
1050 else error[0] = 0;
1052 dlerror();
1053 return ret;
1054 #else
1055 if (error)
1057 static const char msg[] = "dlopen interface not detected by configure";
1058 size_t len = min( errorsize, sizeof(msg) );
1059 memcpy( error, msg, len );
1060 error[len - 1] = 0;
1062 return NULL;
1063 #endif
1066 /***********************************************************************
1067 * wine_dlsym
1069 void *wine_dlsym( void *handle, const char *symbol, char *error, size_t errorsize )
1071 #ifdef HAVE_DLOPEN
1072 void *ret;
1073 const char *s;
1074 dlerror(); dlerror();
1075 ret = dlsym( handle, symbol );
1076 s = dlerror();
1077 if (error && errorsize)
1079 if (s)
1081 size_t len = strlen(s);
1082 if (len >= errorsize) len = errorsize - 1;
1083 memcpy( error, s, len );
1084 error[len] = 0;
1086 else error[0] = 0;
1088 dlerror();
1089 return ret;
1090 #else
1091 if (error)
1093 static const char msg[] = "dlopen interface not detected by configure";
1094 size_t len = min( errorsize, sizeof(msg) );
1095 memcpy( error, msg, len );
1096 error[len - 1] = 0;
1098 return NULL;
1099 #endif
1102 /***********************************************************************
1103 * wine_dlclose
1105 int wine_dlclose( void *handle, char *error, size_t errorsize )
1107 #ifdef HAVE_DLOPEN
1108 int ret;
1109 const char *s;
1110 dlerror(); dlerror();
1111 ret = dlclose( handle );
1112 s = dlerror();
1113 if (error && errorsize)
1115 if (s)
1117 size_t len = strlen(s);
1118 if (len >= errorsize) len = errorsize - 1;
1119 memcpy( error, s, len );
1120 error[len] = 0;
1122 else error[0] = 0;
1124 dlerror();
1125 return ret;
1126 #else
1127 if (error)
1129 static const char msg[] = "dlopen interface not detected by configure";
1130 size_t len = min( errorsize, sizeof(msg) );
1131 memcpy( error, msg, len );
1132 error[len - 1] = 0;
1134 return 1;
1135 #endif