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
22 #include "wine/port.h"
31 #include <sys/types.h>
32 #ifdef HAVE_SYS_MMAN_H
35 #ifdef HAVE_SYS_RESOURCE_H
36 # include <sys/resource.h>
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>
50 #undef GetCurrentThread
52 #include <mach-o/getsect.h>
54 extern char **environ
;
61 #define NONAMELESSUNION
62 #define NONAMELESSSTRUCT
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 */
86 const IMAGE_NT_HEADERS
*nt
; /* NT header */
87 const char *filename
; /* DLL file name */
88 } builtin_dlls
[MAX_DLLS
];
92 static const IMAGE_NT_HEADERS
*main_exe
;
94 typedef void (*load_dll_callback_t
)( void *, const char * );
95 static load_dll_callback_t load_dll_callback
;
97 extern const char *build_dir
;
98 static const char *default_dlldir
;
99 static const char **dll_paths
;
100 static unsigned int nb_dll_paths
;
101 static int dll_path_maxlen
;
103 extern void *wine_anon_mmap( void *start
, size_t size
, int prot
, int flags
);
104 extern void wine_init_argv0_path( const char *argv0
);
105 extern void wine_init( int argc
, char *argv
[], char *error
, int error_size
);
106 extern void mmap_init(void);
107 extern const char *get_dlldir( const char **default_dlldir
);
109 /* build the dll load path from the WINEDLLPATH variable */
110 static void build_dll_path(void)
113 char *p
, *path
= getenv( "WINEDLLPATH" );
114 const char *dlldir
= get_dlldir( &default_dlldir
);
118 /* count how many path elements we need */
123 while (*p
== ':') p
++;
126 while (*p
&& *p
!= ':') p
++;
130 dll_paths
= malloc( (count
+2) * sizeof(*dll_paths
) );
135 dll_path_maxlen
= strlen(dlldir
);
136 dll_paths
[nb_dll_paths
++] = dlldir
;
140 dll_path_maxlen
= strlen(build_dir
) + sizeof("/programs");
148 while (*p
== ':') *p
++ = 0;
150 dll_paths
[nb_dll_paths
] = p
;
151 while (*p
&& *p
!= ':') p
++;
152 if (p
- dll_paths
[nb_dll_paths
] > dll_path_maxlen
)
153 dll_path_maxlen
= p
- dll_paths
[nb_dll_paths
];
158 /* append default dll dir (if not empty) to path */
159 if ((len
= strlen(default_dlldir
)) > 0)
161 if (len
> dll_path_maxlen
) dll_path_maxlen
= len
;
162 dll_paths
[nb_dll_paths
++] = default_dlldir
;
166 static inline char *prepend( char *buffer
, const char *str
, size_t len
)
168 return memcpy( buffer
- len
, str
, len
);
171 /* get a filename from the next entry in the dll path */
172 static char *next_dll_path( struct dll_path_context
*context
)
174 unsigned int index
= context
->index
++;
175 int namelen
= context
->namelen
;
176 char *path
= context
->name
;
180 case 0: /* try dlls dir with subdir prefix */
181 if (namelen
> 4 && !memcmp( context
->name
+ namelen
- 4, ".dll", 4 )) namelen
-= 4;
182 if (!context
->win16
) path
= prepend( path
, context
->name
, namelen
);
183 path
= prepend( path
, "/dlls", sizeof("/dlls") - 1 );
184 path
= prepend( path
, build_dir
, strlen(build_dir
) );
186 case 1: /* try programs dir with subdir prefix */
189 if (namelen
> 4 && !memcmp( context
->name
+ namelen
- 4, ".exe", 4 )) namelen
-= 4;
190 path
= prepend( path
, context
->name
, namelen
);
191 path
= prepend( path
, "/programs", sizeof("/programs") - 1 );
192 path
= prepend( path
, build_dir
, strlen(build_dir
) );
199 if (index
>= nb_dll_paths
) return NULL
;
200 path
= prepend( path
, dll_paths
[index
], strlen( dll_paths
[index
] ));
206 /* get a filename from the first entry in the dll path */
207 static char *first_dll_path( const char *name
, int win16
, struct dll_path_context
*context
)
210 int namelen
= strlen( name
);
211 const char *ext
= win16
? "16" : ".so";
213 context
->buffer
= malloc( dll_path_maxlen
+ 2 * namelen
+ strlen(ext
) + 3 );
214 context
->index
= build_dir
? 0 : 2; /* if no build dir skip all the build dir magic cases */
215 context
->name
= context
->buffer
+ dll_path_maxlen
+ namelen
+ 1;
216 context
->namelen
= namelen
+ 1;
217 context
->win16
= win16
;
219 /* store the name at the end of the buffer, followed by extension */
222 memcpy( p
, name
, namelen
);
223 strcpy( p
+ namelen
, ext
);
224 return next_dll_path( context
);
228 /* free the dll path context created by first_dll_path */
229 static inline void free_dll_path( struct dll_path_context
*context
)
231 free( context
->buffer
);
235 /* adjust an array of pointers to make them into RVAs */
236 static inline void fixup_rva_ptrs( void *array
, BYTE
*base
, unsigned int count
)
238 void **src
= (void **)array
;
239 DWORD
*dst
= (DWORD
*)array
;
242 *dst
++ = *src
? (BYTE
*)*src
- base
: 0;
247 /* fixup an array of RVAs by adding the specified delta */
248 static inline void fixup_rva_dwords( DWORD
*ptr
, int delta
, unsigned int count
)
252 if (*ptr
) *ptr
+= delta
;
258 /* fixup an array of name/ordinal RVAs by adding the specified delta */
259 static inline void fixup_rva_names( UINT_PTR
*ptr
, int delta
)
263 if (!(*ptr
& IMAGE_ORDINAL_FLAG
)) *ptr
+= delta
;
269 /* fixup RVAs in the import directory */
270 static void fixup_imports( IMAGE_IMPORT_DESCRIPTOR
*dir
, BYTE
*base
, int delta
)
274 fixup_rva_dwords( &dir
->u
.OriginalFirstThunk
, delta
, 1 );
275 fixup_rva_dwords( &dir
->Name
, delta
, 1 );
276 fixup_rva_dwords( &dir
->FirstThunk
, delta
, 1 );
277 if (dir
->u
.OriginalFirstThunk
) fixup_rva_names( (UINT_PTR
*)(base
+ dir
->u
.OriginalFirstThunk
), delta
);
278 if (dir
->FirstThunk
) fixup_rva_names( (UINT_PTR
*)(base
+ dir
->FirstThunk
), delta
);
284 /* fixup RVAs in the export directory */
285 static void fixup_exports( IMAGE_EXPORT_DIRECTORY
*dir
, BYTE
*base
, int delta
)
287 fixup_rva_dwords( &dir
->Name
, delta
, 1 );
288 fixup_rva_dwords( &dir
->AddressOfFunctions
, delta
, 1 );
289 fixup_rva_dwords( &dir
->AddressOfNames
, delta
, 1 );
290 fixup_rva_dwords( &dir
->AddressOfNameOrdinals
, delta
, 1 );
291 fixup_rva_dwords( (DWORD
*)(base
+ dir
->AddressOfNames
), delta
, dir
->NumberOfNames
);
292 fixup_rva_ptrs( (base
+ dir
->AddressOfFunctions
), base
, dir
->NumberOfFunctions
);
296 /* fixup RVAs in the resource directory */
297 static void fixup_resources( IMAGE_RESOURCE_DIRECTORY
*dir
, BYTE
*root
, int delta
)
299 IMAGE_RESOURCE_DIRECTORY_ENTRY
*entry
;
302 entry
= (IMAGE_RESOURCE_DIRECTORY_ENTRY
*)(dir
+ 1);
303 for (i
= 0; i
< dir
->NumberOfNamedEntries
+ dir
->NumberOfIdEntries
; i
++, entry
++)
305 void *ptr
= root
+ entry
->u2
.s2
.OffsetToDirectory
;
306 if (entry
->u2
.s2
.DataIsDirectory
) fixup_resources( ptr
, root
, delta
);
309 IMAGE_RESOURCE_DATA_ENTRY
*data
= ptr
;
310 fixup_rva_dwords( &data
->OffsetToData
, delta
, 1 );
316 /* map a builtin dll in memory and fixup RVAs */
317 static void *map_dll( const IMAGE_NT_HEADERS
*nt_descr
)
319 IMAGE_DATA_DIRECTORY
*dir
;
320 IMAGE_DOS_HEADER
*dos
;
321 IMAGE_NT_HEADERS
*nt
;
322 IMAGE_SECTION_HEADER
*sec
;
324 DWORD code_start
, code_end
, data_start
, data_end
;
325 const size_t page_size
= sysconf( _SC_PAGESIZE
);
326 const size_t page_mask
= page_size
- 1;
327 int delta
, nb_sections
= 2; /* code + data */
331 unsigned long data_size
;
334 size_t size
= (sizeof(IMAGE_DOS_HEADER
)
335 + sizeof(IMAGE_NT_HEADERS
)
336 + nb_sections
* sizeof(IMAGE_SECTION_HEADER
));
338 assert( size
<= page_size
);
340 /* module address must be aligned on 64K boundary */
341 addr
= (BYTE
*)((nt_descr
->OptionalHeader
.ImageBase
+ 0xffff) & ~0xffff);
342 if (wine_anon_mmap( addr
, page_size
, PROT_READ
|PROT_WRITE
, MAP_FIXED
) != addr
) return NULL
;
344 dos
= (IMAGE_DOS_HEADER
*)addr
;
345 nt
= (IMAGE_NT_HEADERS
*)(dos
+ 1);
346 sec
= (IMAGE_SECTION_HEADER
*)(nt
+ 1);
348 /* Build the DOS and NT headers */
350 dos
->e_magic
= IMAGE_DOS_SIGNATURE
;
353 dos
->e_cparhdr
= (sizeof(*dos
)+0xf)/0x10;
355 dos
->e_maxalloc
= 0xffff;
358 dos
->e_lfarlc
= sizeof(*dos
);
359 dos
->e_lfanew
= sizeof(*dos
);
363 delta
= (const BYTE
*)nt_descr
- addr
;
364 code_start
= page_size
;
365 data_start
= delta
& ~page_mask
;
367 /* Need the mach_header, not the PE header, to give to getsegmentdata(3) */
369 code_end
= getsegmentdata(dli
.dli_fbase
, "__DATA", &data_size
) - addr
;
370 data_end
= (code_end
+ data_size
+ page_mask
) & ~page_mask
;
372 code_end
= data_start
;
373 data_end
= (nt
->OptionalHeader
.SizeOfImage
+ delta
+ page_mask
) & ~page_mask
;
376 fixup_rva_ptrs( &nt
->OptionalHeader
.AddressOfEntryPoint
, addr
, 1 );
378 nt
->FileHeader
.NumberOfSections
= nb_sections
;
379 nt
->OptionalHeader
.BaseOfCode
= code_start
;
381 nt
->OptionalHeader
.BaseOfData
= data_start
;
383 nt
->OptionalHeader
.SizeOfCode
= code_end
- code_start
;
384 nt
->OptionalHeader
.SizeOfInitializedData
= data_end
- data_start
;
385 nt
->OptionalHeader
.SizeOfUninitializedData
= 0;
386 nt
->OptionalHeader
.SizeOfImage
= data_end
;
387 nt
->OptionalHeader
.ImageBase
= (ULONG_PTR
)addr
;
389 /* Build the code section */
391 memcpy( sec
->Name
, ".text", sizeof(".text") );
392 sec
->SizeOfRawData
= code_end
- code_start
;
393 sec
->Misc
.VirtualSize
= sec
->SizeOfRawData
;
394 sec
->VirtualAddress
= code_start
;
395 sec
->PointerToRawData
= code_start
;
396 sec
->Characteristics
= (IMAGE_SCN_CNT_CODE
| IMAGE_SCN_MEM_EXECUTE
| IMAGE_SCN_MEM_READ
);
399 /* Build the data section */
401 memcpy( sec
->Name
, ".data", sizeof(".data") );
402 sec
->SizeOfRawData
= data_end
- data_start
;
403 sec
->Misc
.VirtualSize
= sec
->SizeOfRawData
;
404 sec
->VirtualAddress
= data_start
;
405 sec
->PointerToRawData
= data_start
;
406 sec
->Characteristics
= (IMAGE_SCN_CNT_INITIALIZED_DATA
|
407 IMAGE_SCN_MEM_WRITE
| IMAGE_SCN_MEM_READ
);
410 for (i
= 0; i
< nt
->OptionalHeader
.NumberOfRvaAndSizes
; i
++)
411 fixup_rva_dwords( &nt
->OptionalHeader
.DataDirectory
[i
].VirtualAddress
, delta
, 1 );
413 /* Build the import directory */
415 dir
= &nt
->OptionalHeader
.DataDirectory
[IMAGE_FILE_IMPORT_DIRECTORY
];
418 IMAGE_IMPORT_DESCRIPTOR
*imports
= (void *)(addr
+ dir
->VirtualAddress
);
419 fixup_imports( imports
, addr
, delta
);
422 /* Build the resource directory */
424 dir
= &nt
->OptionalHeader
.DataDirectory
[IMAGE_FILE_RESOURCE_DIRECTORY
];
427 void *ptr
= (void *)(addr
+ dir
->VirtualAddress
);
428 fixup_resources( ptr
, ptr
, delta
);
431 /* Build the export directory */
433 dir
= &nt
->OptionalHeader
.DataDirectory
[IMAGE_FILE_EXPORT_DIRECTORY
];
436 IMAGE_EXPORT_DIRECTORY
*exports
= (void *)(addr
+ dir
->VirtualAddress
);
437 fixup_exports( exports
, addr
, delta
);
443 /***********************************************************************
444 * __wine_get_main_environment
446 * Return an environment pointer to work around lack of environ variable.
447 * Only exported on Mac OS.
449 char **__wine_get_main_environment(void)
455 /***********************************************************************
456 * __wine_dll_register
458 * Register a built-in DLL descriptor.
460 void __wine_dll_register( const IMAGE_NT_HEADERS
*header
, const char *filename
)
462 if (load_dll_callback
) load_dll_callback( map_dll(header
), filename
);
465 if (!(header
->FileHeader
.Characteristics
& IMAGE_FILE_DLL
))
469 assert( nb_dlls
< MAX_DLLS
);
470 builtin_dlls
[nb_dlls
].nt
= header
;
471 builtin_dlls
[nb_dlls
].filename
= filename
;
478 /***********************************************************************
479 * wine_dll_set_callback
481 * Set the callback function for dll loading, and call it
482 * for all dlls that were implicitly loaded already.
484 void wine_dll_set_callback( load_dll_callback_t load
)
487 load_dll_callback
= load
;
488 for (i
= 0; i
< nb_dlls
; i
++)
490 const IMAGE_NT_HEADERS
*nt
= builtin_dlls
[i
].nt
;
492 builtin_dlls
[i
].nt
= NULL
;
493 load_dll_callback( map_dll(nt
), builtin_dlls
[i
].filename
);
496 if (main_exe
) load_dll_callback( map_dll(main_exe
), "" );
500 #ifdef __ASM_OBSOLETE
502 /***********************************************************************
503 * wine_dll_enum_load_path
505 * Enumerate the dll load path.
507 const char *wine_dll_enum_load_path_obsolete( unsigned int index
)
509 if (index
>= nb_dll_paths
) return NULL
;
510 return dll_paths
[index
];
515 * These functions provide wrappers around dlopen() and associated
516 * functions. They work around a bug in glibc 2.1.x where calling
517 * a dl*() function after a previous dl*() function has failed
518 * without a dlerror() call between the two will cause a crash.
519 * They all take a pointer to a buffer that
520 * will receive the error description (from dlerror()). This
521 * parameter may be NULL if the error description is not required.
528 /***********************************************************************
531 void *wine_dlopen_obsolete( const char *filename
, int flag
, char *error
, size_t errorsize
)
537 /* the Mac OS loader pretends to be able to load PE files, so avoid them here */
538 unsigned char magic
[2];
539 int fd
= open( filename
, O_RDONLY
);
542 if (pread( fd
, magic
, 2, 0 ) == 2 && magic
[0] == 'M' && magic
[1] == 'Z')
544 if (error
&& errorsize
)
546 static const char msg
[] = "MZ format";
547 size_t len
= min( errorsize
, sizeof(msg
) );
548 memcpy( error
, msg
, len
);
557 dlerror(); dlerror();
559 if (strchr( filename
, ':' ))
562 /* Solaris' brain damaged dlopen() treats ':' as a path separator */
563 realpath( filename
, path
);
564 ret
= dlopen( path
, flag
| RTLD_FIRST
);
568 ret
= dlopen( filename
, flag
| RTLD_FIRST
);
570 if (error
&& errorsize
)
574 size_t len
= strlen(s
);
575 if (len
>= errorsize
) len
= errorsize
- 1;
576 memcpy( error
, s
, len
);
585 /***********************************************************************
588 void *wine_dlsym_obsolete( void *handle
, const char *symbol
, char *error
, size_t errorsize
)
592 dlerror(); dlerror();
593 ret
= dlsym( handle
, symbol
);
595 if (error
&& errorsize
)
599 size_t len
= strlen(s
);
600 if (len
>= errorsize
) len
= errorsize
- 1;
601 memcpy( error
, s
, len
);
610 /***********************************************************************
613 int wine_dlclose_obsolete( void *handle
, char *error
, size_t errorsize
)
617 dlerror(); dlerror();
618 ret
= dlclose( handle
);
620 if (error
&& errorsize
)
624 size_t len
= strlen(s
);
625 if (len
>= errorsize
) len
= errorsize
- 1;
626 memcpy( error
, s
, len
);
636 /* check if the library is the correct architecture */
637 /* only returns false for a valid library of the wrong arch */
638 static int check_library_arch( int fd
)
641 struct /* Mach-O header */
644 unsigned int cputype
;
647 if (read( fd
, &header
, sizeof(header
) ) != sizeof(header
)) return 1;
648 if (header
.magic
!= 0xfeedface) return 1;
649 if (sizeof(void *) == sizeof(int)) return !(header
.cputype
>> 24);
650 else return (header
.cputype
>> 24) == 1; /* CPU_ARCH_ABI64 */
652 struct /* ELF header */
654 unsigned char magic
[4];
657 unsigned char version
;
660 if (read( fd
, &header
, sizeof(header
) ) != sizeof(header
)) return 1;
661 if (memcmp( header
.magic
, "\177ELF", 4 )) return 1;
662 if (header
.version
!= 1 /* EV_CURRENT */) return 1;
663 #ifdef WORDS_BIGENDIAN
664 if (header
.data
!= 2 /* ELFDATA2MSB */) return 1;
666 if (header
.data
!= 1 /* ELFDATA2LSB */) return 1;
668 if (sizeof(void *) == sizeof(int)) return header
.class == 1; /* ELFCLASS32 */
669 else return header
.class == 2; /* ELFCLASS64 */
673 /* check if a given file can be opened */
674 static int file_exists( const char *name
)
677 int fd
= open( name
, O_RDONLY
);
680 ret
= check_library_arch( fd
);
686 /* open a library for a given dll, searching in the dll path
687 * 'name' must be the Windows dll name (e.g. "kernel32.dll") */
688 static void *dlopen_dll( const char *name
, char *error
, int errorsize
,
689 int test_only
, int *exists
)
691 struct dll_path_context context
;
696 for (path
= first_dll_path( name
, 0, &context
); path
; path
= next_dll_path( &context
))
698 if (!test_only
&& (ret
= wine_dlopen_obsolete( path
, RTLD_NOW
, error
, errorsize
))) break;
699 if ((*exists
= file_exists( path
))) break; /* exists but cannot be loaded, return the error */
701 free_dll_path( &context
);
706 /***********************************************************************
709 * Load a builtin dll.
711 void *wine_dll_load_obsolete( const char *filename
, char *error
, int errorsize
, int *file_exists
)
715 /* callback must have been set already */
716 assert( load_dll_callback
);
718 /* check if we have it in the list */
719 /* this can happen when initializing pre-loaded dlls in wine_dll_set_callback */
720 for (i
= 0; i
< nb_dlls
; i
++)
722 if (!builtin_dlls
[i
].nt
) continue;
723 if (!strcmp( builtin_dlls
[i
].filename
, filename
))
725 const IMAGE_NT_HEADERS
*nt
= builtin_dlls
[i
].nt
;
726 builtin_dlls
[i
].nt
= NULL
;
727 load_dll_callback( map_dll(nt
), builtin_dlls
[i
].filename
);
732 return dlopen_dll( filename
, error
, errorsize
, 0, file_exists
);
736 /***********************************************************************
739 * Unload a builtin dll.
741 void wine_dll_unload_obsolete( void *handle
)
743 if (handle
!= (void *)1)
744 wine_dlclose_obsolete( handle
, NULL
, 0 );
748 /***********************************************************************
749 * wine_dll_load_main_exe
751 * Try to load the .so for the main exe.
753 void *wine_dll_load_main_exe_obsolete( const char *name
, char *error
, int errorsize
,
754 int test_only
, int *file_exists
)
756 return dlopen_dll( name
, error
, errorsize
, test_only
, file_exists
);
760 /***********************************************************************
763 * Retrieve the name of the 32-bit owner dll for a 16-bit dll.
764 * Return 0 if OK, -1 on error.
766 int wine_dll_get_owner_obsolete( const char *name
, char *buffer
, int size
, int *exists
)
770 struct dll_path_context context
;
774 for (path
= first_dll_path( name
, 1, &context
); path
; path
= next_dll_path( &context
))
776 int fd
= open( path
, O_RDONLY
);
779 int res
= read( fd
, buffer
, size
- 1 );
780 while (res
> 0 && (buffer
[res
-1] == '\n' || buffer
[res
-1] == '\r')) res
--;
788 free_dll_path( &context
);
792 __ASM_OBSOLETE(wine_dlopen
);
793 __ASM_OBSOLETE(wine_dlsym
);
794 __ASM_OBSOLETE(wine_dlclose
);
795 __ASM_OBSOLETE(wine_dll_enum_load_path
);
796 __ASM_OBSOLETE(wine_dll_get_owner
);
797 __ASM_OBSOLETE(wine_dll_load
);
798 __ASM_OBSOLETE(wine_dll_load_main_exe
);
799 __ASM_OBSOLETE(wine_dll_unload
);
801 #endif /* __ASM_OBSOLETE */
803 /***********************************************************************
806 * Set a user limit to the maximum allowed value.
808 static void set_max_limit( int limit
)
810 struct rlimit rlimit
;
812 if (!getrlimit( limit
, &rlimit
))
814 rlimit
.rlim_cur
= rlimit
.rlim_max
;
815 if (setrlimit( limit
, &rlimit
) != 0)
817 #if defined(__APPLE__) && defined(RLIMIT_NOFILE) && defined(OPEN_MAX)
818 /* On Leopard, setrlimit(RLIMIT_NOFILE, ...) fails on attempts to set
819 * rlim_cur above OPEN_MAX (even if rlim_max > OPEN_MAX). */
820 if (limit
== RLIMIT_NOFILE
&& rlimit
.rlim_cur
> OPEN_MAX
)
822 rlimit
.rlim_cur
= OPEN_MAX
;
823 setrlimit( limit
, &rlimit
);
832 struct apple_stack_info
838 /***********************************************************************
839 * apple_alloc_thread_stack
841 * Callback for wine_mmap_enum_reserved_areas to allocate space for
842 * the secondary thread's stack.
845 static int apple_alloc_thread_stack( void *base
, size_t size
, void *arg
)
847 struct apple_stack_info
*info
= arg
;
849 /* For mysterious reasons, putting the thread stack at the very top
850 * of the address space causes subsequent execs to fail, even on the
851 * child side of a fork. Avoid the top 16MB. */
852 char * const limit
= (char*)0xff000000;
853 if ((char *)base
>= limit
) return 0;
854 if (size
> limit
- (char*)base
)
855 size
= limit
- (char*)base
;
856 if (size
< info
->desired_size
) return 0;
857 info
->stack
= wine_anon_mmap( (char *)base
+ size
- info
->desired_size
,
858 info
->desired_size
, PROT_READ
|PROT_WRITE
, MAP_FIXED
);
859 return (info
->stack
!= (void *)-1);
863 /***********************************************************************
864 * apple_create_wine_thread
866 * Spin off a secondary thread to complete Wine initialization, leaving
867 * the original thread for the Mac frameworks.
869 * Invoked as a CFRunLoopSource perform callback.
871 static void apple_create_wine_thread( void *init_func
)
877 if (!pthread_attr_init( &attr
))
880 struct apple_stack_info info
;
882 /* Try to put the new thread's stack in the reserved area. If this
883 * fails, just let it go wherever. It'll be a waste of space, but we
885 if (!pthread_attr_getstacksize( &attr
, &info
.desired_size
) &&
886 wine_mmap_enum_reserved_areas( apple_alloc_thread_stack
, &info
, 1 ))
888 wine_mmap_remove_reserved_area( info
.stack
, info
.desired_size
, 0 );
889 pthread_attr_setstackaddr( &attr
, (char*)info
.stack
+ info
.desired_size
);
893 if (!pthread_attr_setdetachstate( &attr
, PTHREAD_CREATE_JOINABLE
) &&
894 !pthread_create( &thread
, &attr
, init_func
, NULL
))
897 pthread_attr_destroy( &attr
);
900 /* Failure is indicated by returning from wine_init(). Stopping
901 * the run loop allows apple_main_thread() and thus wine_init() to
904 CFRunLoopStop( CFRunLoopGetCurrent() );
908 /***********************************************************************
911 * Park the process's original thread in a Core Foundation run loop for
912 * use by the Mac frameworks, especially receiving and handling
913 * distributed notifications. Spin off a new thread for the rest of the
914 * Wine initialization.
916 static void apple_main_thread( void (*init_func
)(void) )
918 CFRunLoopSourceContext source_context
= { 0 };
919 CFRunLoopSourceRef source
;
921 if (!pthread_main_np())
927 /* Multi-processing Services can get confused about the main thread if the
928 * first time it's used is on a secondary thread. Use it here to make sure
929 * that doesn't happen. */
930 MPTaskIsPreemptive(MPCurrentTaskID());
932 /* Give ourselves the best chance of having the distributed notification
933 * center scheduled on this thread's run loop. In theory, it's scheduled
934 * in the first thread to ask for it. */
935 CFNotificationCenterGetDistributedCenter();
937 /* We use this run loop source for two purposes. First, a run loop exits
938 * if it has no more sources scheduled. So, we need at least one source
939 * to keep the run loop running. Second, although it's not critical, it's
940 * preferable for the Wine initialization to not proceed until we know
941 * the run loop is running. So, we signal our source immediately after
942 * adding it and have its callback spin off the Wine thread. */
943 source_context
.info
= init_func
;
944 source_context
.perform
= apple_create_wine_thread
;
945 source
= CFRunLoopSourceCreate( NULL
, 0, &source_context
);
949 CFRunLoopAddSource( CFRunLoopGetCurrent(), source
, kCFRunLoopCommonModes
);
950 CFRunLoopSourceSignal( source
);
953 CFRunLoopRun(); /* Should never return, except on error. */
956 /* If we get here (i.e. return), that indicates failure to our caller. */
963 #ifndef WINE_JAVA_CLASS
964 #define WINE_JAVA_CLASS "org/winehq/wine/WineActivity"
967 static JavaVM
*java_vm
;
968 static jobject java_object
;
970 /* return the Java VM that was used for JNI initialisation */
971 JavaVM
*wine_get_java_vm(void)
976 /* return the Java object that called the wine_init method */
977 jobject
wine_get_java_object(void)
982 /* main Wine initialisation */
983 static jstring
wine_init_jni( JNIEnv
*env
, jobject obj
, jobjectArray cmdline
, jobjectArray environment
)
990 /* get the command line array */
992 argc
= (*env
)->GetArrayLength( env
, cmdline
);
993 for (i
= length
= 0; i
< argc
; i
++)
995 jobject str_obj
= (*env
)->GetObjectArrayElement( env
, cmdline
, i
);
996 length
+= (*env
)->GetStringUTFLength( env
, str_obj
) + 1;
999 argv
= malloc( (argc
+ 1) * sizeof(*argv
) + length
);
1000 str
= (char *)(argv
+ argc
+ 1);
1001 for (i
= 0; i
< argc
; i
++)
1003 jobject str_obj
= (*env
)->GetObjectArrayElement( env
, cmdline
, i
);
1004 length
= (*env
)->GetStringUTFLength( env
, str_obj
);
1005 (*env
)->GetStringUTFRegion( env
, str_obj
, 0,
1006 (*env
)->GetStringLength( env
, str_obj
), str
);
1013 /* set the environment variables */
1017 int count
= (*env
)->GetArrayLength( env
, environment
);
1018 for (i
= 0; i
< count
- 1; i
+= 2)
1020 jobject var_obj
= (*env
)->GetObjectArrayElement( env
, environment
, i
);
1021 jobject val_obj
= (*env
)->GetObjectArrayElement( env
, environment
, i
+ 1 );
1022 const char *var
= (*env
)->GetStringUTFChars( env
, var_obj
, NULL
);
1026 const char *val
= (*env
)->GetStringUTFChars( env
, val_obj
, NULL
);
1027 setenv( var
, val
, 1 );
1028 if (!strcmp( var
, "LD_LIBRARY_PATH" ))
1030 void (*update_func
)( const char * ) = dlsym( RTLD_DEFAULT
,
1031 "android_update_LD_LIBRARY_PATH" );
1032 if (update_func
) update_func( val
);
1034 else if (!strcmp( var
, "WINEDEBUGLOG" ))
1036 int fd
= open( val
, O_WRONLY
| O_CREAT
| O_APPEND
, 0666 );
1043 (*env
)->ReleaseStringUTFChars( env
, val_obj
, val
);
1045 else unsetenv( var
);
1047 (*env
)->ReleaseStringUTFChars( env
, var_obj
, var
);
1051 java_object
= (*env
)->NewGlobalRef( env
, obj
);
1055 unsigned short java_fs
;
1056 __asm__( "mov %%fs,%0" : "=r" (java_fs
) );
1057 __asm__( "mov %0,%%fs" :: "r" (0) );
1058 wine_init( argc
, argv
, error
, sizeof(error
) );
1059 __asm__( "mov %0,%%fs" :: "r" (java_fs
) );
1062 wine_init( argc
, argv
, error
, sizeof(error
) );
1064 return (*env
)->NewStringUTF( env
, error
);
1067 jint
JNI_OnLoad( JavaVM
*vm
, void *reserved
)
1069 static const JNINativeMethod method
=
1071 "wine_init", "([Ljava/lang/String;[Ljava/lang/String;)Ljava/lang/String;", wine_init_jni
1078 if ((*vm
)->AttachCurrentThread( vm
, &env
, NULL
) != JNI_OK
) return JNI_ERR
;
1079 if (!(class = (*env
)->FindClass( env
, WINE_JAVA_CLASS
))) return JNI_ERR
;
1080 (*env
)->RegisterNatives( env
, class, &method
, 1 );
1081 return JNI_VERSION_1_6
;
1084 #endif /* __ANDROID__ */
1086 /***********************************************************************
1089 * Main Wine initialisation.
1091 void wine_init( int argc
, char *argv
[], char *error
, int error_size
)
1093 struct dll_path_context context
;
1096 void (*init_func
)(void);
1098 /* force a few limits that are set too low on some platforms */
1099 #ifdef RLIMIT_NOFILE
1100 set_max_limit( RLIMIT_NOFILE
);
1103 set_max_limit( RLIMIT_AS
);
1106 wine_init_argv0_path( argv
[0] );
1108 __wine_main_argc
= argc
;
1109 __wine_main_argv
= argv
;
1110 __wine_main_environ
= __wine_get_main_environment();
1113 for (path
= first_dll_path( "ntdll.dll", 0, &context
); path
; path
= next_dll_path( &context
))
1115 if ((ntdll
= dlopen( path
, RTLD_NOW
)))
1117 /* if we didn't use the default dll dir, remove it from the search path */
1118 if (default_dlldir
[0] && context
.index
< nb_dll_paths
+ 2) nb_dll_paths
--;
1122 free_dll_path( &context
);
1124 if (!ntdll
|| !(init_func
= dlsym( ntdll
, "__wine_process_init" )))
1126 if (error
&& error_size
)
1128 const char *s
= dlerror();
1131 size_t len
= min( strlen(s
), error_size
- 1 );
1132 memcpy( error
, s
, len
);
1140 apple_main_thread( init_func
);