winmm/tests: Add MCI_DGV_WINDOW_STATE tests.
[wine.git] / loader / preloader_mac.c
blob01a41f08d8c1eabcf97395afa70ede13187190c2
1 /*
2 * Preloader for macOS
4 * Copyright (C) 1995,96,97,98,99,2000,2001,2002 Free Software Foundation, Inc.
5 * Copyright (C) 2004 Mike McCormack for CodeWeavers
6 * Copyright (C) 2004 Alexandre Julliard
7 * Copyright (C) 2017 Michael Müller
8 * Copyright (C) 2017 Sebastian Lackner
10 * This library is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU Lesser General Public
12 * License as published by the Free Software Foundation; either
13 * version 2.1 of the License, or (at your option) any later version.
15 * This library is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with this library; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
25 #ifdef __APPLE__
27 #include "config.h"
29 #include <stdarg.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <string.h>
33 #include <sys/types.h>
34 #include <sys/stat.h>
35 #include <fcntl.h>
36 #include <sys/mman.h>
37 #ifdef HAVE_SYS_SYSCALL_H
38 # include <sys/syscall.h>
39 #endif
40 #include <unistd.h>
41 #include <dlfcn.h>
42 #ifdef HAVE_MACH_O_LOADER_H
43 #include <mach/thread_status.h>
44 #include <mach-o/loader.h>
45 #include <mach-o/ldsyms.h>
46 #endif
48 #include "wine/asm.h"
49 #include "main.h"
51 /* Rosetta on Apple Silicon allocates memory starting at 0x100000000 (the 4GB line)
52 * before the preloader runs, which prevents any nonrelocatable EXEs with that
53 * base address from running.
55 * This empty linker section forces Rosetta's allocations (currently ~132 MB)
56 * to start at 0x114000000, and they should end below 0x120000000.
58 #if defined(__x86_64__)
59 __asm__(".zerofill WINE_4GB_RESERVE,WINE_4GB_RESERVE,___wine_4gb_reserve,0x14000000");
60 #endif
62 #ifndef LC_MAIN
63 #define LC_MAIN 0x80000028
64 struct entry_point_command
66 uint32_t cmd;
67 uint32_t cmdsize;
68 uint64_t entryoff;
69 uint64_t stacksize;
71 #endif
73 static struct wine_preload_info preload_info[] =
75 /* On macOS, we allocate the low 64k area in two steps because PAGEZERO
76 * might not always be available. */
77 #ifdef __i386__
78 { (void *)0x00000000, 0x00001000 }, /* first page */
79 { (void *)0x00001000, 0x0000f000 }, /* low 64k */
80 { (void *)0x00010000, 0x00100000 }, /* DOS area */
81 { (void *)0x00110000, 0x67ef0000 }, /* low memory area */
82 { (void *)0x7f000000, 0x03000000 }, /* top-down allocations + shared heap + virtual heap */
83 #else /* __i386__ */
84 { (void *)0x000000010000, 0x00100000 }, /* DOS area */
85 { (void *)0x000000110000, 0x67ef0000 }, /* low memory area */
86 { (void *)0x00007ff00000, 0x000f0000 }, /* shared user data */
87 { (void *)0x000100000000, 0x14000000 }, /* WINE_4GB_RESERVE section */
88 { (void *)0x7ffd00000000, 0x01ff0000 }, /* top-down allocations + virtual heap */
89 #endif /* __i386__ */
90 { 0, 0 }, /* PE exe range set with WINEPRELOADRESERVE */
91 { 0, 0 } /* end of list */
95 * These functions are only called when file is compiled with -fstack-protector.
96 * They are normally provided by libc's startup files, but since we
97 * build the preloader with "-nostartfiles -nodefaultlibs", we have to
98 * provide our own versions, otherwise the linker fails.
100 void *__stack_chk_guard = 0;
101 void __stack_chk_fail_local(void) { return; }
102 void __stack_chk_fail(void) { return; }
104 #ifdef __i386__
106 static const size_t page_size = 0x1000;
107 static const size_t page_mask = 0xfff;
108 #define target_mach_header mach_header
109 #define target_segment_command segment_command
110 #define TARGET_LC_SEGMENT LC_SEGMENT
111 #define target_thread_state_t i386_thread_state_t
112 #ifdef __DARWIN_UNIX03
113 #define target_thread_ip(x) (x)->__eip
114 #else
115 #define target_thread_ip(x) (x)->eip
116 #endif
118 #define SYSCALL_FUNC( name, nr ) \
119 __ASM_GLOBAL_FUNC( name, \
120 "\tmovl $" #nr ",%eax\n" \
121 "\tint $0x80\n" \
122 "\tjnb 1f\n" \
123 "\tmovl $-1,%eax\n" \
124 "1:\tret\n" )
126 #define SYSCALL_NOERR( name, nr ) \
127 __ASM_GLOBAL_FUNC( name, \
128 "\tmovl $" #nr ",%eax\n" \
129 "\tint $0x80\n" \
130 "\tret\n" )
132 __ASM_GLOBAL_FUNC( start,
133 __ASM_CFI("\t.cfi_undefined %eip\n")
134 /* The first 16 bytes are used as a function signature on i386 */
135 "\t.byte 0x6a,0x00\n" /* pushl $0 */
136 "\t.byte 0x89,0xe5\n" /* movl %esp,%ebp */
137 "\t.byte 0x83,0xe4,0xf0\n" /* andl $-16,%esp */
138 "\t.byte 0x83,0xec,0x10\n" /* subl $16,%esp */
139 "\t.byte 0x8b,0x5d,0x04\n" /* movl 4(%ebp),%ebx */
140 "\t.byte 0x89,0x5c,0x24,0x00\n" /* movl %ebx,0(%esp) */
142 "\tleal 4(%ebp),%eax\n"
143 "\tmovl %eax,0(%esp)\n" /* stack */
144 "\tleal 8(%esp),%eax\n"
145 "\tmovl %eax,4(%esp)\n" /* &is_unix_thread */
146 "\tmovl $0,(%eax)\n"
147 "\tcall _wld_start\n"
149 "\tmovl 4(%ebp),%edi\n"
150 "\tdecl %edi\n" /* argc */
151 "\tleal 12(%ebp),%esi\n" /* argv */
152 "\tleal 4(%esi,%edi,4),%edx\n" /* env */
153 "\tmovl %edx,%ecx\n" /* apple data */
154 "1:\tmovl (%ecx),%ebx\n"
155 "\tadd $4,%ecx\n"
156 "\torl %ebx,%ebx\n"
157 "\tjnz 1b\n"
159 "\tcmpl $0,8(%esp)\n"
160 "\tjne 2f\n"
162 /* LC_MAIN */
163 "\tmovl %edi,0(%esp)\n" /* argc */
164 "\tmovl %esi,4(%esp)\n" /* argv */
165 "\tmovl %edx,8(%esp)\n" /* env */
166 "\tmovl %ecx,12(%esp)\n" /* apple data */
167 "\tcall *%eax\n"
168 "\tmovl %eax,(%esp)\n"
169 "\tcall _wld_exit\n"
170 "\thlt\n"
172 /* LC_UNIXTHREAD */
173 "2:\tmovl (%ecx),%ebx\n"
174 "\tadd $4,%ecx\n"
175 "\torl %ebx,%ebx\n"
176 "\tjnz 2b\n"
178 "\tsubl %ebp,%ecx\n"
179 "\tsubl $8,%ecx\n"
180 "\tleal 4(%ebp),%esp\n"
181 "\tsubl %ecx,%esp\n"
183 "\tmovl %edi,(%esp)\n" /* argc */
184 "\tleal 4(%esp),%edi\n"
185 "\tshrl $2,%ecx\n"
186 "\tcld\n"
187 "\trep; movsd\n" /* argv, ... */
189 "\tmovl $0,%ebp\n"
190 "\tjmpl *%eax\n" )
192 #elif defined(__x86_64__)
194 static const size_t page_size = 0x1000;
195 static const size_t page_mask = 0xfff;
196 #define target_mach_header mach_header_64
197 #define target_segment_command segment_command_64
198 #define TARGET_LC_SEGMENT LC_SEGMENT_64
199 #define target_thread_state_t x86_thread_state64_t
200 #ifdef __DARWIN_UNIX03
201 #define target_thread_ip(x) (x)->__rip
202 #else
203 #define target_thread_ip(x) (x)->rip
204 #endif
206 #define SYSCALL_FUNC( name, nr ) \
207 __ASM_GLOBAL_FUNC( name, \
208 "\tmovq %rcx, %r10\n" \
209 "\tmovq $(" #nr "|0x2000000),%rax\n" \
210 "\tsyscall\n" \
211 "\tjnb 1f\n" \
212 "\tmovq $-1,%rax\n" \
213 "1:\tret\n" )
215 #define SYSCALL_NOERR( name, nr ) \
216 __ASM_GLOBAL_FUNC( name, \
217 "\tmovq %rcx, %r10\n" \
218 "\tmovq $(" #nr "|0x2000000),%rax\n" \
219 "\tsyscall\n" \
220 "\tret\n" )
222 __ASM_GLOBAL_FUNC( start,
223 __ASM_CFI("\t.cfi_undefined %rip\n")
224 "\tpushq $0\n"
225 "\tmovq %rsp,%rbp\n"
226 "\tandq $-16,%rsp\n"
227 "\tsubq $16,%rsp\n"
229 "\tleaq 8(%rbp),%rdi\n" /* stack */
230 "\tmovq %rsp,%rsi\n" /* &is_unix_thread */
231 "\tmovq $0,(%rsi)\n"
232 "\tcall _wld_start\n"
234 "\tmovq 8(%rbp),%rdi\n"
235 "\tdec %rdi\n" /* argc */
236 "\tleaq 24(%rbp),%rsi\n" /* argv */
237 "\tleaq 8(%rsi,%rdi,8),%rdx\n" /* env */
238 "\tmovq %rdx,%rcx\n" /* apple data */
239 "1:\tmovq (%rcx),%r8\n"
240 "\taddq $8,%rcx\n"
241 "\torq %r8,%r8\n"
242 "\tjnz 1b\n"
244 "\tcmpl $0,0(%rsp)\n"
245 "\tjne 2f\n"
247 /* LC_MAIN */
248 "\taddq $16,%rsp\n"
249 "\tcall *%rax\n"
250 "\tmovq %rax,%rdi\n"
251 "\tcall _wld_exit\n"
252 "\thlt\n"
254 /* LC_UNIXTHREAD */
255 "2:\tmovq (%rcx),%r8\n"
256 "\taddq $8,%rcx\n"
257 "\torq %r8,%r8\n"
258 "\tjnz 2b\n"
260 "\tsubq %rbp,%rcx\n"
261 "\tsubq $16,%rcx\n"
262 "\tleaq 8(%rbp),%rsp\n"
263 "\tsubq %rcx,%rsp\n"
265 "\tmovq %rdi,(%rsp)\n" /* argc */
266 "\tleaq 8(%rsp),%rdi\n"
267 "\tshrq $3,%rcx\n"
268 "\tcld\n"
269 "\trep; movsq\n" /* argv, ... */
271 "\tmovq $0,%rbp\n"
272 "\tjmpq *%rax\n" )
274 #else
275 #error preloader not implemented for this CPU
276 #endif
278 void wld_exit( int code ) __attribute__((noreturn));
279 SYSCALL_NOERR( wld_exit, 1 /* SYS_exit */ );
281 ssize_t wld_write( int fd, const void *buffer, size_t len );
282 SYSCALL_FUNC( wld_write, 4 /* SYS_write */ );
284 void *wld_mmap( void *start, size_t len, int prot, int flags, int fd, off_t offset );
285 SYSCALL_FUNC( wld_mmap, 197 /* SYS_mmap */ );
287 void *wld_munmap( void *start, size_t len );
288 SYSCALL_FUNC( wld_munmap, 73 /* SYS_munmap */ );
290 int wld_mincore( void *addr, size_t length, unsigned char *vec );
291 SYSCALL_FUNC( wld_mincore, 78 /* SYS_mincore */ );
293 static intptr_t (*p_dyld_get_image_slide)( const struct target_mach_header* mh );
295 #define MAKE_FUNCPTR(f) static typeof(f) * p##f
296 MAKE_FUNCPTR(dlopen);
297 MAKE_FUNCPTR(dlsym);
298 MAKE_FUNCPTR(dladdr);
299 #undef MAKE_FUNCPTR
301 extern int _dyld_func_lookup( const char *dyld_func_name, void **address );
303 /* replacement for libc functions */
305 static int wld_strncmp( const char *str1, const char *str2, size_t len )
307 if (len <= 0) return 0;
308 while ((--len > 0) && *str1 && (*str1 == *str2)) { str1++; str2++; }
309 return *str1 - *str2;
313 * wld_printf - just the basics
315 * %x prints a hex number
316 * %s prints a string
317 * %p prints a pointer
319 static int wld_vsprintf(char *buffer, const char *fmt, va_list args )
321 static const char hex_chars[16] = "0123456789abcdef";
322 const char *p = fmt;
323 char *str = buffer;
324 int i;
326 while( *p )
328 if( *p == '%' )
330 p++;
331 if( *p == 'x' )
333 unsigned int x = va_arg( args, unsigned int );
334 for (i = 2*sizeof(x) - 1; i >= 0; i--)
335 *str++ = hex_chars[(x>>(i*4))&0xf];
337 else if (p[0] == 'l' && p[1] == 'x')
339 unsigned long x = va_arg( args, unsigned long );
340 for (i = 2*sizeof(x) - 1; i >= 0; i--)
341 *str++ = hex_chars[(x>>(i*4))&0xf];
342 p++;
344 else if( *p == 'p' )
346 unsigned long x = (unsigned long)va_arg( args, void * );
347 for (i = 2*sizeof(x) - 1; i >= 0; i--)
348 *str++ = hex_chars[(x>>(i*4))&0xf];
350 else if( *p == 's' )
352 char *s = va_arg( args, char * );
353 while(*s)
354 *str++ = *s++;
356 else if( *p == 0 )
357 break;
358 p++;
360 *str++ = *p++;
362 *str = 0;
363 return str - buffer;
366 static __attribute__((format(printf,1,2))) void wld_printf(const char *fmt, ... )
368 va_list args;
369 char buffer[256];
370 int len;
372 va_start( args, fmt );
373 len = wld_vsprintf(buffer, fmt, args );
374 va_end( args );
375 wld_write(2, buffer, len);
378 static __attribute__((noreturn,format(printf,1,2))) void fatal_error(const char *fmt, ... )
380 va_list args;
381 char buffer[256];
382 int len;
384 va_start( args, fmt );
385 len = wld_vsprintf(buffer, fmt, args );
386 va_end( args );
387 wld_write(2, buffer, len);
388 wld_exit(1);
391 static int preloader_overlaps_range( const void *start, const void *end )
393 intptr_t slide = p_dyld_get_image_slide(&_mh_execute_header);
394 struct load_command *cmd = (struct load_command*)(&_mh_execute_header + 1);
395 int i;
397 for (i = 0; i < _mh_execute_header.ncmds; ++i)
399 if (cmd->cmd == TARGET_LC_SEGMENT)
401 struct target_segment_command *seg = (struct target_segment_command*)cmd;
402 const void *seg_start = (const void*)(seg->vmaddr + slide);
403 const void *seg_end = (const char*)seg_start + seg->vmsize;
404 static const char reserved_segname[] = "WINE_4GB_RESERVE";
406 if (!wld_strncmp( seg->segname, reserved_segname, sizeof(reserved_segname)-1 ))
407 continue;
409 if (end > seg_start && start <= seg_end)
411 char segname[sizeof(seg->segname) + 1];
412 memcpy(segname, seg->segname, sizeof(seg->segname));
413 segname[sizeof(segname) - 1] = 0;
414 wld_printf( "WINEPRELOADRESERVE range %p-%p overlaps preloader %s segment %p-%p\n",
415 start, end, segname, seg_start, seg_end );
416 return 1;
419 cmd = (struct load_command*)((char*)cmd + cmd->cmdsize);
422 return 0;
426 * preload_reserve
428 * Reserve a range specified in string format
430 static void preload_reserve( const char *str )
432 const char *p;
433 unsigned long result = 0;
434 void *start = NULL, *end = NULL;
435 int i, first = 1;
437 for (p = str; *p; p++)
439 if (*p >= '0' && *p <= '9') result = result * 16 + *p - '0';
440 else if (*p >= 'a' && *p <= 'f') result = result * 16 + *p - 'a' + 10;
441 else if (*p >= 'A' && *p <= 'F') result = result * 16 + *p - 'A' + 10;
442 else if (*p == '-')
444 if (!first) goto error;
445 start = (void *)(result & ~page_mask);
446 result = 0;
447 first = 0;
449 else goto error;
451 if (!first) end = (void *)((result + page_mask) & ~page_mask);
452 else if (result) goto error; /* single value '0' is allowed */
454 /* sanity checks */
455 if (end <= start || preloader_overlaps_range(start, end))
456 start = end = NULL;
458 /* check for overlap with low memory areas */
459 for (i = 0; preload_info[i].size; i++)
461 if ((char *)preload_info[i].addr > (char *)0x00110000) break;
462 if ((char *)end <= (char *)preload_info[i].addr + preload_info[i].size)
464 start = end = NULL;
465 break;
467 if ((char *)start < (char *)preload_info[i].addr + preload_info[i].size)
468 start = (char *)preload_info[i].addr + preload_info[i].size;
471 while (preload_info[i].size) i++;
472 preload_info[i].addr = start;
473 preload_info[i].size = (char *)end - (char *)start;
474 return;
476 error:
477 fatal_error( "invalid WINEPRELOADRESERVE value '%s'\n", str );
480 /* remove a range from the preload list */
481 static void remove_preload_range( int i )
483 while (preload_info[i].size)
485 preload_info[i].addr = preload_info[i+1].addr;
486 preload_info[i].size = preload_info[i+1].size;
487 i++;
491 static void *get_entry_point( struct target_mach_header *mh, intptr_t slide, int *unix_thread )
493 struct entry_point_command *entry;
494 target_thread_state_t *state;
495 struct load_command *cmd;
496 int i;
498 /* try LC_MAIN first */
499 cmd = (struct load_command *)(mh + 1);
500 for (i = 0; i < mh->ncmds; i++)
502 if (cmd->cmd == LC_MAIN)
504 *unix_thread = FALSE;
505 entry = (struct entry_point_command *)cmd;
506 return (char *)mh + entry->entryoff;
508 cmd = (struct load_command *)((char *)cmd + cmd->cmdsize);
511 /* then try LC_UNIXTHREAD */
512 cmd = (struct load_command *)(mh + 1);
513 for (i = 0; i < mh->ncmds; i++)
515 if (cmd->cmd == LC_UNIXTHREAD)
517 *unix_thread = TRUE;
518 state = (target_thread_state_t *)((char *)cmd + 16);
519 return (void *)(target_thread_ip(state) + slide);
521 cmd = (struct load_command *)((char *)cmd + cmd->cmdsize);
524 return NULL;
527 static int is_region_empty( struct wine_preload_info *info )
529 unsigned char vec[1024];
530 size_t pos, size, block = 1024 * page_size;
531 int i;
533 for (pos = 0; pos < info->size; pos += size)
535 size = (pos + block <= info->size) ? block : (info->size - pos);
536 if (wld_mincore( (char *)info->addr + pos, size, vec ) == -1)
538 if (size <= page_size) continue;
539 block = page_size; size = 0; /* retry with smaller block size */
541 else
543 for (i = 0; i < size / page_size; i++)
544 if (vec[i] & 1) return 0;
548 return 1;
551 static int map_region( struct wine_preload_info *info )
553 int flags = MAP_PRIVATE | MAP_ANON;
554 void *ret;
556 if (!info->addr) flags |= MAP_FIXED;
558 for (;;)
560 ret = wld_mmap( info->addr, info->size, PROT_NONE, flags, -1, 0 );
561 if (ret == info->addr) return 1;
562 if (ret != (void *)-1) wld_munmap( ret, info->size );
563 if (flags & MAP_FIXED) break;
565 /* Some versions of macOS ignore the address hint passed to mmap -
566 * use mincore() to check if its empty and then use MAP_FIXED */
567 if (!is_region_empty( info )) break;
568 flags |= MAP_FIXED;
571 /* don't warn for zero page */
572 if (info->addr >= (void *)0x1000)
573 wld_printf( "preloader: Warning: failed to reserve range %p-%p\n",
574 info->addr, (char *)info->addr + info->size );
575 return 0;
578 static inline void get_dyld_func( const char *name, void **func )
580 _dyld_func_lookup( name, func );
581 if (!*func) fatal_error( "Failed to get function pointer for %s\n", name );
584 #define LOAD_POSIX_DYLD_FUNC(f) get_dyld_func( "__dyld_" #f, (void **)&p##f )
585 #define LOAD_MACHO_DYLD_FUNC(f) get_dyld_func( "_" #f, (void **)&p##f )
587 void *wld_start( void *stack, int *is_unix_thread )
589 struct wine_preload_info builtin_dlls = { (void *)0x7a000000, 0x02000000 };
590 struct wine_preload_info **wine_main_preload_info;
591 char **argv, **p, *reserve = NULL;
592 struct target_mach_header *mh;
593 void *mod, *entry;
594 int *pargc, i;
595 Dl_info info;
597 pargc = stack;
598 argv = (char **)pargc + 1;
599 if (*pargc < 2) fatal_error( "Usage: %s wine_binary [args]\n", argv[0] );
601 /* skip over the parameters */
602 p = argv + *pargc + 1;
604 /* skip over the environment */
605 while (*p)
607 static const char res[] = "WINEPRELOADRESERVE=";
608 if (!wld_strncmp( *p, res, sizeof(res)-1 )) reserve = *p + sizeof(res) - 1;
609 p++;
612 LOAD_POSIX_DYLD_FUNC( dlopen );
613 LOAD_POSIX_DYLD_FUNC( dlsym );
614 LOAD_POSIX_DYLD_FUNC( dladdr );
615 LOAD_MACHO_DYLD_FUNC( _dyld_get_image_slide );
617 /* reserve memory that Wine needs */
618 if (reserve) preload_reserve( reserve );
619 for (i = 0; preload_info[i].size; i++)
621 if (!map_region( &preload_info[i] ))
623 remove_preload_range( i );
624 i--;
628 if (!map_region( &builtin_dlls ))
629 builtin_dlls.size = 0;
631 /* load the main binary */
632 if (!(mod = pdlopen( argv[1], RTLD_NOW )))
633 fatal_error( "%s: could not load binary\n", argv[1] );
635 if (builtin_dlls.size)
636 wld_munmap( builtin_dlls.addr, builtin_dlls.size );
638 /* store pointer to the preload info into the appropriate main binary variable */
639 wine_main_preload_info = pdlsym( mod, "wine_main_preload_info" );
640 if (wine_main_preload_info) *wine_main_preload_info = preload_info;
641 else wld_printf( "wine_main_preload_info not found\n" );
643 if (!pdladdr( wine_main_preload_info, &info ) || !(mh = info.dli_fbase))
644 fatal_error( "%s: could not find mach header\n", argv[1] );
645 if (!(entry = get_entry_point( mh, p_dyld_get_image_slide(mh), is_unix_thread )))
646 fatal_error( "%s: could not find entry point\n", argv[1] );
648 return entry;
651 #endif /* __APPLE__ */