custom-buffer-style doc fix
[emacs.git] / src / unexmacosx.c
blobbdacc8b540bcc9c1e2790b60cb2f633f996f3cb3
1 /* Dump Emacs in Mach-O format for use on Mac OS X.
2 Copyright (C) 2001-2016 Free Software Foundation, Inc.
4 This file is part of GNU Emacs.
6 GNU Emacs is free software: you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation, either version 3 of the License, or (at
9 your option) any later version.
11 GNU Emacs 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
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
19 /* Contributed by Andrew Choi (akochoi@mac.com). */
21 /* Documentation note.
23 Consult the following documents/files for a description of the
24 Mach-O format: the file loader.h, man pages for Mach-O and ld, old
25 NEXTSTEP documents of the Mach-O format. The tool otool dumps the
26 mach header (-h option) and the load commands (-l option) in a
27 Mach-O file. The tool nm on Mac OS X displays the symbol table in
28 a Mach-O file. For examples of unexec for the Mach-O format, see
29 the file unexnext.c in the GNU Emacs distribution, the file
30 unexdyld.c in the Darwin port of GNU Emacs 20.7, and unexdyld.c in
31 the Darwin port of XEmacs 21.1. Also the Darwin Libc source
32 contains the source code for malloc_freezedry and malloc_jumpstart.
33 Read that to see what they do. This file was written completely
34 from scratch, making use of information from the above sources. */
36 /* The Mac OS X implementation of unexec makes use of Darwin's `zone'
37 memory allocator. All calls to malloc, realloc, and free in Emacs
38 are redirected to unexec_malloc, unexec_realloc, and unexec_free in
39 this file. When temacs is run, all memory requests are handled in
40 the zone EmacsZone. The Darwin memory allocator library calls
41 maintain the data structures to manage this zone. Dumping writes
42 its contents to data segments of the executable file. When emacs
43 is run, the loader recreates the contents of the zone in memory.
44 However since the initialization routine of the zone memory
45 allocator is run again, this `zone' can no longer be used as a
46 heap. That is why emacs uses the ordinary malloc system call to
47 allocate memory. Also, when a block of memory needs to be
48 reallocated and the new size is larger than the old one, a new
49 block must be obtained by malloc and the old contents copied to
50 it. */
52 /* Peculiarity of the Mach-O files generated by ld in Mac OS X
53 (possible causes of future bugs if changed).
55 The file offset of the start of the __TEXT segment is zero. Since
56 the Mach header and load commands are located at the beginning of a
57 Mach-O file, copying the contents of the __TEXT segment from the
58 input file overwrites them in the output file. Despite this,
59 unexec works fine as written below because the segment load command
60 for __TEXT appears, and is therefore processed, before all other
61 load commands except the segment load command for __PAGEZERO, which
62 remains unchanged.
64 Although the file offset of the start of the __TEXT segment is
65 zero, none of the sections it contains actually start there. In
66 fact, the earliest one starts a few hundred bytes beyond the end of
67 the last load command. The linker option -headerpad controls the
68 minimum size of this padding. Its setting can be changed in
69 s/darwin.h. A value of 0x690, e.g., leaves room for 30 additional
70 load commands for the newly created __DATA segments (at 56 bytes
71 each). Unexec fails if there is not enough room for these new
72 segments.
74 The __TEXT segment contains the sections __text, __cstring,
75 __picsymbol_stub, and __const and the __DATA segment contains the
76 sections __data, __la_symbol_ptr, __nl_symbol_ptr, __dyld, __bss,
77 and __common. The other segments do not contain any sections.
78 These sections are copied from the input file to the output file,
79 except for __data, __bss, and __common, which are dumped from
80 memory. The types of the sections __bss and __common are changed
81 from S_ZEROFILL to S_REGULAR. Note that the number of sections and
82 their relative order in the input and output files remain
83 unchanged. Otherwise all n_sect fields in the nlist records in the
84 symbol table (specified by the LC_SYMTAB load command) will have to
85 be changed accordingly.
88 /* config.h #define:s malloc/realloc/free and then includes stdlib.h.
89 We want the undefined versions, but if config.h includes stdlib.h
90 with the #define:s in place, the prototypes will be wrong and we get
91 warnings. To prevent that, include stdlib.h before config.h. */
93 #include <stdlib.h>
94 #include <config.h>
95 #undef malloc
96 #undef realloc
97 #undef free
99 #include "unexec.h"
100 #include "lisp.h"
102 #include <errno.h>
103 #include <stdio.h>
104 #include <fcntl.h>
105 #include <stdarg.h>
106 #include <stdint.h>
107 #include <sys/types.h>
108 #include <unistd.h>
109 #include <mach/mach.h>
110 #include <mach/vm_map.h>
111 #include <mach-o/loader.h>
112 #include <mach-o/reloc.h>
113 #ifdef HAVE_MALLOC_MALLOC_H
114 #include <malloc/malloc.h>
115 #else
116 #include <objc/malloc.h>
117 #endif
119 #include <assert.h>
121 /* LC_DATA_IN_CODE is not defined in mach-o/loader.h on OS X 10.7.
122 But it is used if we build with "Command Line Tools for Xcode 4.5
123 (OS X Lion) - September 2012". */
124 #ifndef LC_DATA_IN_CODE
125 #define LC_DATA_IN_CODE 0x29 /* table of non-instructions in __text */
126 #endif
128 #ifdef _LP64
129 #define mach_header mach_header_64
130 #define segment_command segment_command_64
131 #undef VM_REGION_BASIC_INFO_COUNT
132 #define VM_REGION_BASIC_INFO_COUNT VM_REGION_BASIC_INFO_COUNT_64
133 #undef VM_REGION_BASIC_INFO
134 #define VM_REGION_BASIC_INFO VM_REGION_BASIC_INFO_64
135 #undef LC_SEGMENT
136 #define LC_SEGMENT LC_SEGMENT_64
137 #define vm_region vm_region_64
138 #define section section_64
139 #undef MH_MAGIC
140 #define MH_MAGIC MH_MAGIC_64
141 #endif
143 #define VERBOSE 1
145 /* Size of buffer used to copy data from the input file to the output
146 file in function unexec_copy. */
147 #define UNEXEC_COPY_BUFSZ 1024
149 /* Regions with memory addresses above this value are assumed to be
150 mapped to dynamically loaded libraries and will not be dumped. */
151 #define VM_DATA_TOP (20 * 1024 * 1024)
153 /* Type of an element on the list of regions to be dumped. */
154 struct region_t {
155 vm_address_t address;
156 vm_size_t size;
157 vm_prot_t protection;
158 vm_prot_t max_protection;
160 struct region_t *next;
163 /* Head and tail of the list of regions to be dumped. */
164 static struct region_t *region_list_head = 0;
165 static struct region_t *region_list_tail = 0;
167 /* Pointer to array of load commands. */
168 static struct load_command **lca;
170 /* Number of load commands. */
171 static int nlc;
173 /* The highest VM address of segments loaded by the input file.
174 Regions with addresses beyond this are assumed to be allocated
175 dynamically and thus require dumping. */
176 static vm_address_t infile_lc_highest_addr = 0;
178 /* The lowest file offset used by the all sections in the __TEXT
179 segments. This leaves room at the beginning of the file to store
180 the Mach-O header. Check this value against header size to ensure
181 the added load commands for the new __DATA segments did not
182 overwrite any of the sections in the __TEXT segment. */
183 static unsigned long text_seg_lowest_offset = 0x10000000;
185 /* Mach header. */
186 static struct mach_header mh;
188 /* Offset at which the next load command should be written. */
189 static unsigned long curr_header_offset = sizeof (struct mach_header);
191 /* Offset at which the next segment should be written. */
192 static unsigned long curr_file_offset = 0;
194 static unsigned long pagesize;
195 #define ROUNDUP_TO_PAGE_BOUNDARY(x) (((x) + pagesize - 1) & ~(pagesize - 1))
197 static int infd, outfd;
199 static int in_dumped_exec = 0;
201 static malloc_zone_t *emacs_zone;
203 /* file offset of input file's data segment */
204 static off_t data_segment_old_fileoff = 0;
206 static struct segment_command *data_segment_scp;
208 /* Read N bytes from infd into memory starting at address DEST.
209 Return true if successful, false otherwise. */
210 static int
211 unexec_read (void *dest, size_t n)
213 return n == read (infd, dest, n);
216 /* Write COUNT bytes from memory starting at address SRC to outfd
217 starting at offset DEST. Return true if successful, false
218 otherwise. */
219 static int
220 unexec_write (off_t dest, const void *src, size_t count)
222 task_t task = mach_task_self();
223 if (task == MACH_PORT_NULL || task == MACH_PORT_DEAD)
224 return false;
226 if (lseek (outfd, dest, SEEK_SET) != dest)
227 return 0;
229 /* We use the Mach virtual memory API to read our process memory
230 because using src directly would be undefined behavior and fails
231 under Address Sanitizer. */
232 bool success = false;
233 vm_offset_t data;
234 mach_msg_type_number_t data_count;
235 if (vm_read (task, (uintptr_t) src, count, &data, &data_count)
236 == KERN_SUCCESS)
238 success =
239 write (outfd, (const void *) (uintptr_t) data, data_count) == count;
240 vm_deallocate (task, data, data_count);
242 return success;
245 /* Write COUNT bytes of zeros to outfd starting at offset DEST.
246 Return true if successful, false otherwise. */
247 static int
248 unexec_write_zero (off_t dest, size_t count)
250 char buf[UNEXEC_COPY_BUFSZ];
251 ssize_t bytes;
253 memset (buf, 0, UNEXEC_COPY_BUFSZ);
254 if (lseek (outfd, dest, SEEK_SET) != dest)
255 return 0;
257 while (count > 0)
259 bytes = count > UNEXEC_COPY_BUFSZ ? UNEXEC_COPY_BUFSZ : count;
260 if (write (outfd, buf, bytes) != bytes)
261 return 0;
262 count -= bytes;
265 return 1;
268 /* Copy COUNT bytes from starting offset SRC in infd to starting
269 offset DEST in outfd. Return true if successful, false
270 otherwise. */
271 static int
272 unexec_copy (off_t dest, off_t src, ssize_t count)
274 ssize_t bytes_read;
275 ssize_t bytes_to_read;
277 char buf[UNEXEC_COPY_BUFSZ];
279 if (lseek (infd, src, SEEK_SET) != src)
280 return 0;
282 if (lseek (outfd, dest, SEEK_SET) != dest)
283 return 0;
285 while (count > 0)
287 bytes_to_read = count > UNEXEC_COPY_BUFSZ ? UNEXEC_COPY_BUFSZ : count;
288 bytes_read = read (infd, buf, bytes_to_read);
289 if (bytes_read <= 0)
290 return 0;
291 if (write (outfd, buf, bytes_read) != bytes_read)
292 return 0;
293 count -= bytes_read;
296 return 1;
299 /* Debugging and informational messages routines. */
301 static _Noreturn void
302 unexec_error (const char *format, ...)
304 va_list ap;
306 va_start (ap, format);
307 fprintf (stderr, "unexec: ");
308 vfprintf (stderr, format, ap);
309 fprintf (stderr, "\n");
310 va_end (ap);
311 exit (1);
314 static void
315 print_prot (vm_prot_t prot)
317 if (prot == VM_PROT_NONE)
318 printf ("none");
319 else
321 putchar (prot & VM_PROT_READ ? 'r' : ' ');
322 putchar (prot & VM_PROT_WRITE ? 'w' : ' ');
323 putchar (prot & VM_PROT_EXECUTE ? 'x' : ' ');
324 putchar (' ');
328 static void
329 print_region (vm_address_t address, vm_size_t size, vm_prot_t prot,
330 vm_prot_t max_prot)
332 printf ("%#10lx %#8lx ", (long) address, (long) size);
333 print_prot (prot);
334 putchar (' ');
335 print_prot (max_prot);
336 putchar ('\n');
339 static void
340 print_region_list (void)
342 struct region_t *r;
344 printf (" address size prot maxp\n");
346 for (r = region_list_head; r; r = r->next)
347 print_region (r->address, r->size, r->protection, r->max_protection);
350 static void
351 print_regions (void)
353 task_t target_task = mach_task_self ();
354 vm_address_t address = (vm_address_t) 0;
355 vm_size_t size;
356 struct vm_region_basic_info info;
357 mach_msg_type_number_t info_count = VM_REGION_BASIC_INFO_COUNT;
358 mach_port_t object_name;
360 printf (" address size prot maxp\n");
362 while (vm_region (target_task, &address, &size, VM_REGION_BASIC_INFO,
363 (vm_region_info_t) &info, &info_count, &object_name)
364 == KERN_SUCCESS && info_count == VM_REGION_BASIC_INFO_COUNT)
366 print_region (address, size, info.protection, info.max_protection);
368 if (object_name != MACH_PORT_NULL)
369 mach_port_deallocate (target_task, object_name);
371 address += size;
375 /* Build the list of regions that need to be dumped. Regions with
376 addresses above VM_DATA_TOP are omitted. Adjacent regions with
377 identical protection are merged. Note that non-writable regions
378 cannot be omitted because they some regions created at run time are
379 read-only. */
380 static void
381 build_region_list (void)
383 task_t target_task = mach_task_self ();
384 vm_address_t address = (vm_address_t) 0;
385 vm_size_t size;
386 struct vm_region_basic_info info;
387 mach_msg_type_number_t info_count = VM_REGION_BASIC_INFO_COUNT;
388 mach_port_t object_name;
389 struct region_t *r;
391 #if VERBOSE
392 printf ("--- List of All Regions ---\n");
393 printf (" address size prot maxp\n");
394 #endif
396 while (vm_region (target_task, &address, &size, VM_REGION_BASIC_INFO,
397 (vm_region_info_t) &info, &info_count, &object_name)
398 == KERN_SUCCESS && info_count == VM_REGION_BASIC_INFO_COUNT)
400 /* Done when we reach addresses of shared libraries, which are
401 loaded in high memory. */
402 if (address >= VM_DATA_TOP)
403 break;
405 #if VERBOSE
406 print_region (address, size, info.protection, info.max_protection);
407 #endif
409 /* If a region immediately follows the previous one (the one
410 most recently added to the list) and has identical
411 protection, merge it with the latter. Otherwise create a
412 new list element for it. */
413 if (region_list_tail
414 && info.protection == region_list_tail->protection
415 && info.max_protection == region_list_tail->max_protection
416 && region_list_tail->address + region_list_tail->size == address)
418 region_list_tail->size += size;
420 else
422 r = malloc (sizeof *r);
424 if (!r)
425 unexec_error ("cannot allocate region structure");
427 r->address = address;
428 r->size = size;
429 r->protection = info.protection;
430 r->max_protection = info.max_protection;
432 r->next = 0;
433 if (region_list_head == 0)
435 region_list_head = r;
436 region_list_tail = r;
438 else
440 region_list_tail->next = r;
441 region_list_tail = r;
444 /* Deallocate (unused) object name returned by
445 vm_region. */
446 if (object_name != MACH_PORT_NULL)
447 mach_port_deallocate (target_task, object_name);
450 address += size;
453 printf ("--- List of Regions to be Dumped ---\n");
454 print_region_list ();
458 #define MAX_UNEXEC_REGIONS 400
460 static int num_unexec_regions;
461 typedef struct {
462 vm_range_t range;
463 vm_size_t filesize;
464 } unexec_region_info;
465 static unexec_region_info unexec_regions[MAX_UNEXEC_REGIONS];
467 static void
468 unexec_regions_recorder (task_t task, void *rr, unsigned type,
469 vm_range_t *ranges, unsigned num)
471 vm_address_t p;
472 vm_size_t filesize;
474 while (num && num_unexec_regions < MAX_UNEXEC_REGIONS)
476 /* Subtract the size of trailing null bytes from filesize. It
477 can be smaller than vmsize in segment commands. In such a
478 case, trailing bytes are initialized with zeros. */
479 for (p = ranges->address + ranges->size; p > ranges->address; p--)
480 if (*(((char *) p)-1))
481 break;
482 filesize = p - ranges->address;
484 unexec_regions[num_unexec_regions].filesize = filesize;
485 unexec_regions[num_unexec_regions++].range = *ranges;
486 printf ("%#10lx (sz: %#8lx/%#8lx)\n", (long) (ranges->address),
487 (long) filesize, (long) (ranges->size));
488 ranges++; num--;
492 static kern_return_t
493 unexec_reader (task_t task, vm_address_t address, vm_size_t size, void **ptr)
495 *ptr = (void *) address;
496 return KERN_SUCCESS;
499 static void
500 find_emacs_zone_regions (void)
502 num_unexec_regions = 0;
504 emacs_zone->introspect->enumerator (mach_task_self (), 0,
505 MALLOC_PTR_REGION_RANGE_TYPE
506 | MALLOC_ADMIN_REGION_RANGE_TYPE,
507 (vm_address_t) emacs_zone,
508 unexec_reader,
509 unexec_regions_recorder);
511 if (num_unexec_regions == MAX_UNEXEC_REGIONS)
512 unexec_error ("find_emacs_zone_regions: too many regions");
515 static int
516 unexec_regions_sort_compare (const void *a, const void *b)
518 vm_address_t aa = ((unexec_region_info *) a)->range.address;
519 vm_address_t bb = ((unexec_region_info *) b)->range.address;
521 if (aa < bb)
522 return -1;
523 else if (aa > bb)
524 return 1;
525 else
526 return 0;
529 static void
530 unexec_regions_merge (void)
532 int i, n;
533 unexec_region_info r;
534 vm_size_t padsize;
536 qsort (unexec_regions, num_unexec_regions, sizeof (unexec_regions[0]),
537 &unexec_regions_sort_compare);
538 n = 0;
539 r = unexec_regions[0];
540 padsize = r.range.address & (pagesize - 1);
541 if (padsize)
543 r.range.address -= padsize;
544 r.range.size += padsize;
545 r.filesize += padsize;
547 for (i = 1; i < num_unexec_regions; i++)
549 if (r.range.address + r.range.size == unexec_regions[i].range.address
550 && r.range.size - r.filesize < 2 * pagesize)
552 r.filesize = r.range.size + unexec_regions[i].filesize;
553 r.range.size += unexec_regions[i].range.size;
555 else
557 unexec_regions[n++] = r;
558 r = unexec_regions[i];
559 padsize = r.range.address & (pagesize - 1);
560 if (padsize)
562 if ((unexec_regions[n-1].range.address
563 + unexec_regions[n-1].range.size) == r.range.address)
564 unexec_regions[n-1].range.size -= padsize;
566 r.range.address -= padsize;
567 r.range.size += padsize;
568 r.filesize += padsize;
572 unexec_regions[n++] = r;
573 num_unexec_regions = n;
577 /* More informational messages routines. */
579 static void
580 print_load_command_name (int lc)
582 switch (lc)
584 case LC_SEGMENT:
585 #ifndef _LP64
586 printf ("LC_SEGMENT ");
587 #else
588 printf ("LC_SEGMENT_64 ");
589 #endif
590 break;
591 case LC_LOAD_DYLINKER:
592 printf ("LC_LOAD_DYLINKER ");
593 break;
594 case LC_LOAD_DYLIB:
595 printf ("LC_LOAD_DYLIB ");
596 break;
597 case LC_SYMTAB:
598 printf ("LC_SYMTAB ");
599 break;
600 case LC_DYSYMTAB:
601 printf ("LC_DYSYMTAB ");
602 break;
603 case LC_UNIXTHREAD:
604 printf ("LC_UNIXTHREAD ");
605 break;
606 case LC_PREBOUND_DYLIB:
607 printf ("LC_PREBOUND_DYLIB");
608 break;
609 case LC_TWOLEVEL_HINTS:
610 printf ("LC_TWOLEVEL_HINTS");
611 break;
612 #ifdef LC_UUID
613 case LC_UUID:
614 printf ("LC_UUID ");
615 break;
616 #endif
617 #ifdef LC_DYLD_INFO
618 case LC_DYLD_INFO:
619 printf ("LC_DYLD_INFO ");
620 break;
621 case LC_DYLD_INFO_ONLY:
622 printf ("LC_DYLD_INFO_ONLY");
623 break;
624 #endif
625 #ifdef LC_VERSION_MIN_MACOSX
626 case LC_VERSION_MIN_MACOSX:
627 printf ("LC_VERSION_MIN_MACOSX");
628 break;
629 #endif
630 #ifdef LC_FUNCTION_STARTS
631 case LC_FUNCTION_STARTS:
632 printf ("LC_FUNCTION_STARTS");
633 break;
634 #endif
635 #ifdef LC_MAIN
636 case LC_MAIN:
637 printf ("LC_MAIN ");
638 break;
639 #endif
640 #ifdef LC_DATA_IN_CODE
641 case LC_DATA_IN_CODE:
642 printf ("LC_DATA_IN_CODE ");
643 break;
644 #endif
645 #ifdef LC_SOURCE_VERSION
646 case LC_SOURCE_VERSION:
647 printf ("LC_SOURCE_VERSION");
648 break;
649 #endif
650 #ifdef LC_DYLIB_CODE_SIGN_DRS
651 case LC_DYLIB_CODE_SIGN_DRS:
652 printf ("LC_DYLIB_CODE_SIGN_DRS");
653 break;
654 #endif
655 default:
656 printf ("unknown ");
660 static void
661 print_load_command (struct load_command *lc)
663 print_load_command_name (lc->cmd);
664 printf ("%8d", lc->cmdsize);
666 if (lc->cmd == LC_SEGMENT)
668 struct segment_command *scp;
669 struct section *sectp;
670 int j;
672 scp = (struct segment_command *) lc;
673 printf (" %-16.16s %#10lx %#8lx\n",
674 scp->segname, (long) (scp->vmaddr), (long) (scp->vmsize));
676 sectp = (struct section *) (scp + 1);
677 for (j = 0; j < scp->nsects; j++)
679 printf (" %-16.16s %#10lx %#8lx\n",
680 sectp->sectname, (long) (sectp->addr), (long) (sectp->size));
681 sectp++;
684 else
685 printf ("\n");
688 /* Read header and load commands from input file. Store the latter in
689 the global array lca. Store the total number of load commands in
690 global variable nlc. */
691 static void
692 read_load_commands (void)
694 int i;
696 if (!unexec_read (&mh, sizeof (struct mach_header)))
697 unexec_error ("cannot read mach-o header");
699 if (mh.magic != MH_MAGIC)
700 unexec_error ("input file not in Mach-O format");
702 if (mh.filetype != MH_EXECUTE)
703 unexec_error ("input Mach-O file is not an executable object file");
705 #if VERBOSE
706 printf ("--- Header Information ---\n");
707 printf ("Magic = 0x%08x\n", mh.magic);
708 printf ("CPUType = %d\n", mh.cputype);
709 printf ("CPUSubType = %d\n", mh.cpusubtype);
710 printf ("FileType = 0x%x\n", mh.filetype);
711 printf ("NCmds = %d\n", mh.ncmds);
712 printf ("SizeOfCmds = %d\n", mh.sizeofcmds);
713 printf ("Flags = 0x%08x\n", mh.flags);
714 #endif
716 nlc = mh.ncmds;
717 lca = malloc (nlc * sizeof *lca);
719 for (i = 0; i < nlc; i++)
721 struct load_command lc;
722 /* Load commands are variable-size: so read the command type and
723 size first and then read the rest. */
724 if (!unexec_read (&lc, sizeof (struct load_command)))
725 unexec_error ("cannot read load command");
726 lca[i] = malloc (lc.cmdsize);
727 memcpy (lca[i], &lc, sizeof (struct load_command));
728 if (!unexec_read (lca[i] + 1, lc.cmdsize - sizeof (struct load_command)))
729 unexec_error ("cannot read content of load command");
730 if (lc.cmd == LC_SEGMENT)
732 struct segment_command *scp = (struct segment_command *) lca[i];
734 if (scp->vmaddr + scp->vmsize > infile_lc_highest_addr)
735 infile_lc_highest_addr = scp->vmaddr + scp->vmsize;
737 if (strncmp (scp->segname, SEG_TEXT, 16) == 0)
739 struct section *sectp = (struct section *) (scp + 1);
740 int j;
742 for (j = 0; j < scp->nsects; j++)
743 if (sectp->offset < text_seg_lowest_offset)
744 text_seg_lowest_offset = sectp->offset;
749 printf ("Highest address of load commands in input file: %#8lx\n",
750 (unsigned long)infile_lc_highest_addr);
752 printf ("Lowest offset of all sections in __TEXT segment: %#8lx\n",
753 text_seg_lowest_offset);
755 printf ("--- List of Load Commands in Input File ---\n");
756 printf ("# cmd cmdsize name address size\n");
758 for (i = 0; i < nlc; i++)
760 printf ("%1d ", i);
761 print_load_command (lca[i]);
765 /* Copy a LC_SEGMENT load command other than the __DATA segment from
766 the input file to the output file, adjusting the file offset of the
767 segment and the file offsets of sections contained in it. */
768 static void
769 copy_segment (struct load_command *lc)
771 struct segment_command *scp = (struct segment_command *) lc;
772 unsigned long old_fileoff = scp->fileoff;
773 struct section *sectp;
774 int j;
776 scp->fileoff = curr_file_offset;
778 sectp = (struct section *) (scp + 1);
779 for (j = 0; j < scp->nsects; j++)
781 sectp->offset += curr_file_offset - old_fileoff;
782 sectp++;
785 printf ("Writing segment %-16.16s @ %#8lx (%#8lx/%#8lx @ %#10lx)\n",
786 scp->segname, (long) (scp->fileoff), (long) (scp->filesize),
787 (long) (scp->vmsize), (long) (scp->vmaddr));
789 if (!unexec_copy (scp->fileoff, old_fileoff, scp->filesize))
790 unexec_error ("cannot copy segment from input to output file");
791 curr_file_offset += ROUNDUP_TO_PAGE_BOUNDARY (scp->filesize);
793 if (!unexec_write (curr_header_offset, lc, lc->cmdsize))
794 unexec_error ("cannot write load command to header");
796 curr_header_offset += lc->cmdsize;
799 /* Copy a LC_SEGMENT load command for the __DATA segment in the input
800 file to the output file. We assume that only one such segment load
801 command exists in the input file and it contains the sections
802 __data, __bss, __common, __la_symbol_ptr, __nl_symbol_ptr, and
803 __dyld. The first three of these should be dumped from memory and
804 the rest should be copied from the input file. Note that the
805 sections __bss and __common contain no data in the input file
806 because their flag fields have the value S_ZEROFILL. Dumping these
807 from memory makes it necessary to adjust file offset fields in
808 subsequently dumped load commands. Then, create new __DATA segment
809 load commands for regions on the region list other than the one
810 corresponding to the __DATA segment in the input file. */
811 static void
812 copy_data_segment (struct load_command *lc)
814 struct segment_command *scp = (struct segment_command *) lc;
815 struct section *sectp;
816 int j;
817 unsigned long header_offset, old_file_offset;
819 /* The new filesize of the segment is set to its vmsize because data
820 blocks for segments must start at region boundaries. Note that
821 this may leave unused locations at the end of the segment data
822 block because the total of the sizes of all sections in the
823 segment is generally smaller than vmsize. */
824 scp->filesize = scp->vmsize;
826 printf ("Writing segment %-16.16s @ %#8lx (%#8lx/%#8lx @ %#10lx)\n",
827 scp->segname, curr_file_offset, (long)(scp->filesize),
828 (long)(scp->vmsize), (long) (scp->vmaddr));
830 /* Offsets in the output file for writing the next section structure
831 and segment data block, respectively. */
832 header_offset = curr_header_offset + sizeof (struct segment_command);
834 sectp = (struct section *) (scp + 1);
835 for (j = 0; j < scp->nsects; j++)
837 old_file_offset = sectp->offset;
838 sectp->offset = sectp->addr - scp->vmaddr + curr_file_offset;
839 /* The __data section is dumped from memory. The __bss and
840 __common sections are also dumped from memory but their flag
841 fields require changing (from S_ZEROFILL to S_REGULAR). The
842 other three kinds of sections are just copied from the input
843 file. */
844 if (strncmp (sectp->sectname, SECT_DATA, 16) == 0)
846 unsigned long my_size;
848 /* The __data section is basically dumped from memory. But
849 initialized data in statically linked libraries are
850 copied from the input file. In particular,
851 add_image_hook.names and add_image_hook.pointers stored
852 by libarclite_macosx.a, are restored so that they will be
853 reinitialized when the dumped binary is executed. */
854 my_size = (unsigned long)my_edata - sectp->addr;
855 if (!(sectp->addr <= (unsigned long)my_edata
856 && my_size <= sectp->size))
857 unexec_error ("my_edata is not in section %s", SECT_DATA);
858 if (!unexec_write (sectp->offset, (void *) sectp->addr, my_size))
859 unexec_error ("cannot write section %s", SECT_DATA);
860 if (!unexec_copy (sectp->offset + my_size, old_file_offset + my_size,
861 sectp->size - my_size))
862 unexec_error ("cannot copy section %s", SECT_DATA);
863 if (!unexec_write (header_offset, sectp, sizeof (struct section)))
864 unexec_error ("cannot write section %s's header", SECT_DATA);
866 else if (strncmp (sectp->sectname, SECT_COMMON, 16) == 0)
868 sectp->flags = S_REGULAR;
869 if (!unexec_write (sectp->offset, (void *) sectp->addr, sectp->size))
870 unexec_error ("cannot write section %.16s", sectp->sectname);
871 if (!unexec_write (header_offset, sectp, sizeof (struct section)))
872 unexec_error ("cannot write section %.16s's header", sectp->sectname);
874 else if (strncmp (sectp->sectname, SECT_BSS, 16) == 0)
876 unsigned long my_size;
878 sectp->flags = S_REGULAR;
880 /* Clear uninitialized local variables in statically linked
881 libraries. In particular, function pointers stored by
882 libSystemStub.a, which is introduced in Mac OS X 10.4 for
883 binary compatibility with respect to long double, are
884 cleared so that they will be reinitialized when the
885 dumped binary is executed on other versions of OS. */
886 my_size = (unsigned long)my_endbss_static - sectp->addr;
887 if (!(sectp->addr <= (unsigned long)my_endbss_static
888 && my_size <= sectp->size))
889 unexec_error ("my_endbss_static is not in section %.16s",
890 sectp->sectname);
891 if (!unexec_write (sectp->offset, (void *) sectp->addr, my_size))
892 unexec_error ("cannot write section %.16s", sectp->sectname);
893 if (!unexec_write_zero (sectp->offset + my_size,
894 sectp->size - my_size))
895 unexec_error ("cannot write section %.16s", sectp->sectname);
896 if (!unexec_write (header_offset, sectp, sizeof (struct section)))
897 unexec_error ("cannot write section %.16s's header", sectp->sectname);
899 else if (strncmp (sectp->sectname, "__bss", 5) == 0
900 || strncmp (sectp->sectname, "__pu_bss", 8) == 0)
902 sectp->flags = S_REGULAR;
904 /* These sections are produced by GCC 4.6+.
906 FIXME: We possibly ought to clear uninitialized local
907 variables in statically linked libraries like for
908 SECT_BSS (__bss) above, but setting up the markers we
909 need in lastfile.c would be rather messy. See
910 darwin_output_aligned_bss () in gcc/config/darwin.c for
911 the root of the problem, keeping in mind that the
912 sections are numbered by their alignment in GCC 4.6, but
913 by log2(alignment) in GCC 4.7. */
915 if (!unexec_write (sectp->offset, (void *) sectp->addr, sectp->size))
916 unexec_error ("cannot copy section %.16s", sectp->sectname);
917 if (!unexec_write (header_offset, sectp, sizeof (struct section)))
918 unexec_error ("cannot write section %.16s's header", sectp->sectname);
920 else if (strncmp (sectp->sectname, "__la_symbol_ptr", 16) == 0
921 || strncmp (sectp->sectname, "__nl_symbol_ptr", 16) == 0
922 || strncmp (sectp->sectname, "__got", 16) == 0
923 || strncmp (sectp->sectname, "__la_sym_ptr2", 16) == 0
924 || strncmp (sectp->sectname, "__dyld", 16) == 0
925 || strncmp (sectp->sectname, "__const", 16) == 0
926 || strncmp (sectp->sectname, "__cfstring", 16) == 0
927 || strncmp (sectp->sectname, "__gcc_except_tab", 16) == 0
928 || strncmp (sectp->sectname, "__program_vars", 16) == 0
929 || strncmp (sectp->sectname, "__mod_init_func", 16) == 0
930 || strncmp (sectp->sectname, "__mod_term_func", 16) == 0
931 || strncmp (sectp->sectname, "__static_data", 16) == 0
932 || strncmp (sectp->sectname, "__objc_", 7) == 0)
934 if (!unexec_copy (sectp->offset, old_file_offset, sectp->size))
935 unexec_error ("cannot copy section %.16s", sectp->sectname);
936 if (!unexec_write (header_offset, sectp, sizeof (struct section)))
937 unexec_error ("cannot write section %.16s's header", sectp->sectname);
939 else
940 unexec_error ("unrecognized section %.16s in __DATA segment",
941 sectp->sectname);
943 printf (" section %-16.16s at %#8lx - %#8lx (sz: %#8lx)\n",
944 sectp->sectname, (long) (sectp->offset),
945 (long) (sectp->offset + sectp->size), (long) (sectp->size));
947 header_offset += sizeof (struct section);
948 sectp++;
951 curr_file_offset += ROUNDUP_TO_PAGE_BOUNDARY (scp->filesize);
953 if (!unexec_write (curr_header_offset, scp, sizeof (struct segment_command)))
954 unexec_error ("cannot write header of __DATA segment");
955 curr_header_offset += lc->cmdsize;
957 /* Create new __DATA segment load commands for regions on the region
958 list that do not corresponding to any segment load commands in
959 the input file.
961 for (j = 0; j < num_unexec_regions; j++)
963 struct segment_command sc;
965 sc.cmd = LC_SEGMENT;
966 sc.cmdsize = sizeof (struct segment_command);
967 strncpy (sc.segname, SEG_DATA, 16);
968 sc.vmaddr = unexec_regions[j].range.address;
969 sc.vmsize = unexec_regions[j].range.size;
970 sc.fileoff = curr_file_offset;
971 sc.filesize = unexec_regions[j].filesize;
972 sc.maxprot = VM_PROT_READ | VM_PROT_WRITE;
973 sc.initprot = VM_PROT_READ | VM_PROT_WRITE;
974 sc.nsects = 0;
975 sc.flags = 0;
977 printf ("Writing segment %-16.16s @ %#8lx (%#8lx/%#8lx @ %#10lx)\n",
978 sc.segname, (long) (sc.fileoff), (long) (sc.filesize),
979 (long) (sc.vmsize), (long) (sc.vmaddr));
981 if (!unexec_write (sc.fileoff, (void *) sc.vmaddr, sc.filesize))
982 unexec_error ("cannot write new __DATA segment");
983 curr_file_offset += ROUNDUP_TO_PAGE_BOUNDARY (sc.filesize);
985 if (!unexec_write (curr_header_offset, &sc, sc.cmdsize))
986 unexec_error ("cannot write new __DATA segment's header");
987 curr_header_offset += sc.cmdsize;
988 mh.ncmds++;
992 /* Copy a LC_SYMTAB load command from the input file to the output
993 file, adjusting the file offset fields. */
994 static void
995 copy_symtab (struct load_command *lc, long delta)
997 struct symtab_command *stp = (struct symtab_command *) lc;
999 stp->symoff += delta;
1000 stp->stroff += delta;
1002 printf ("Writing LC_SYMTAB command\n");
1004 if (!unexec_write (curr_header_offset, lc, lc->cmdsize))
1005 unexec_error ("cannot write symtab command to header");
1007 curr_header_offset += lc->cmdsize;
1010 /* Fix up relocation entries. */
1011 static void
1012 unrelocate (const char *name, off_t reloff, int nrel, vm_address_t base)
1014 int i, unreloc_count;
1015 struct relocation_info reloc_info;
1016 struct scattered_relocation_info *sc_reloc_info
1017 = (struct scattered_relocation_info *) &reloc_info;
1018 vm_address_t location;
1020 for (unreloc_count = 0, i = 0; i < nrel; i++)
1022 if (lseek (infd, reloff, L_SET) != reloff)
1023 unexec_error ("unrelocate: %s:%d cannot seek to reloc_info", name, i);
1024 if (!unexec_read (&reloc_info, sizeof (reloc_info)))
1025 unexec_error ("unrelocate: %s:%d cannot read reloc_info", name, i);
1026 reloff += sizeof (reloc_info);
1028 if (sc_reloc_info->r_scattered == 0)
1029 switch (reloc_info.r_type)
1031 case GENERIC_RELOC_VANILLA:
1032 location = base + reloc_info.r_address;
1033 if (location >= data_segment_scp->vmaddr
1034 && location < (data_segment_scp->vmaddr
1035 + data_segment_scp->vmsize))
1037 off_t src_off = data_segment_old_fileoff
1038 + (location - data_segment_scp->vmaddr);
1039 off_t dst_off = data_segment_scp->fileoff
1040 + (location - data_segment_scp->vmaddr);
1042 if (!unexec_copy (dst_off, src_off, 1 << reloc_info.r_length))
1043 unexec_error ("unrelocate: %s:%d cannot copy original value",
1044 name, i);
1045 unreloc_count++;
1047 break;
1048 default:
1049 unexec_error ("unrelocate: %s:%d cannot handle type = %d",
1050 name, i, reloc_info.r_type);
1052 else
1053 unexec_error ("unrelocate: %s:%d cannot handle scattered type = %d",
1054 name, i, sc_reloc_info->r_type);
1057 if (nrel > 0)
1058 printf ("Fixed up %d/%d %s relocation entries in data segment.\n",
1059 unreloc_count, nrel, name);
1062 /* Copy a LC_DYSYMTAB load command from the input file to the output
1063 file, adjusting the file offset fields. */
1064 static void
1065 copy_dysymtab (struct load_command *lc, long delta)
1067 struct dysymtab_command *dstp = (struct dysymtab_command *) lc;
1068 vm_address_t base;
1070 #ifdef _LP64
1071 /* First writable segment address. */
1072 base = data_segment_scp->vmaddr;
1073 #else
1074 /* First segment address in the file (unless MH_SPLIT_SEGS set). */
1075 base = 0;
1076 #endif
1078 unrelocate ("local", dstp->locreloff, dstp->nlocrel, base);
1079 unrelocate ("external", dstp->extreloff, dstp->nextrel, base);
1081 if (dstp->nextrel > 0) {
1082 dstp->extreloff += delta;
1085 if (dstp->nlocrel > 0) {
1086 dstp->locreloff += delta;
1089 if (dstp->nindirectsyms > 0)
1090 dstp->indirectsymoff += delta;
1092 printf ("Writing LC_DYSYMTAB command\n");
1094 if (!unexec_write (curr_header_offset, lc, lc->cmdsize))
1095 unexec_error ("cannot write symtab command to header");
1097 curr_header_offset += lc->cmdsize;
1100 /* Copy a LC_TWOLEVEL_HINTS load command from the input file to the output
1101 file, adjusting the file offset fields. */
1102 static void
1103 copy_twolevelhints (struct load_command *lc, long delta)
1105 struct twolevel_hints_command *tlhp = (struct twolevel_hints_command *) lc;
1107 if (tlhp->nhints > 0) {
1108 tlhp->offset += delta;
1111 printf ("Writing LC_TWOLEVEL_HINTS command\n");
1113 if (!unexec_write (curr_header_offset, lc, lc->cmdsize))
1114 unexec_error ("cannot write two level hint command to header");
1116 curr_header_offset += lc->cmdsize;
1119 #ifdef LC_DYLD_INFO
1120 /* Copy a LC_DYLD_INFO(_ONLY) load command from the input file to the output
1121 file, adjusting the file offset fields. */
1122 static void
1123 copy_dyld_info (struct load_command *lc, long delta)
1125 struct dyld_info_command *dip = (struct dyld_info_command *) lc;
1127 if (dip->rebase_off > 0)
1128 dip->rebase_off += delta;
1129 if (dip->bind_off > 0)
1130 dip->bind_off += delta;
1131 if (dip->weak_bind_off > 0)
1132 dip->weak_bind_off += delta;
1133 if (dip->lazy_bind_off > 0)
1134 dip->lazy_bind_off += delta;
1135 if (dip->export_off > 0)
1136 dip->export_off += delta;
1138 printf ("Writing ");
1139 print_load_command_name (lc->cmd);
1140 printf (" command\n");
1142 if (!unexec_write (curr_header_offset, lc, lc->cmdsize))
1143 unexec_error ("cannot write dyld info command to header");
1145 curr_header_offset += lc->cmdsize;
1147 #endif
1149 #ifdef LC_FUNCTION_STARTS
1150 /* Copy a LC_FUNCTION_STARTS/LC_DATA_IN_CODE/LC_DYLIB_CODE_SIGN_DRS
1151 load command from the input file to the output file, adjusting the
1152 data offset field. */
1153 static void
1154 copy_linkedit_data (struct load_command *lc, long delta)
1156 struct linkedit_data_command *ldp = (struct linkedit_data_command *) lc;
1158 if (ldp->dataoff > 0)
1159 ldp->dataoff += delta;
1161 printf ("Writing ");
1162 print_load_command_name (lc->cmd);
1163 printf (" command\n");
1165 if (!unexec_write (curr_header_offset, lc, lc->cmdsize))
1166 unexec_error ("cannot write linkedit data command to header");
1168 curr_header_offset += lc->cmdsize;
1170 #endif
1172 /* Copy other kinds of load commands from the input file to the output
1173 file, ones that do not require adjustments of file offsets. */
1174 static void
1175 copy_other (struct load_command *lc)
1177 printf ("Writing ");
1178 print_load_command_name (lc->cmd);
1179 printf (" command\n");
1181 if (!unexec_write (curr_header_offset, lc, lc->cmdsize))
1182 unexec_error ("cannot write symtab command to header");
1184 curr_header_offset += lc->cmdsize;
1187 /* Loop through all load commands and dump them. Then write the Mach
1188 header. */
1189 static void
1190 dump_it (void)
1192 int i;
1193 long linkedit_delta = 0;
1195 printf ("--- Load Commands written to Output File ---\n");
1197 for (i = 0; i < nlc; i++)
1198 switch (lca[i]->cmd)
1200 case LC_SEGMENT:
1202 struct segment_command *scp = (struct segment_command *) lca[i];
1203 if (strncmp (scp->segname, SEG_DATA, 16) == 0)
1205 /* save data segment file offset and segment_command for
1206 unrelocate */
1207 if (data_segment_old_fileoff)
1208 unexec_error ("cannot handle multiple DATA segments"
1209 " in input file");
1210 data_segment_old_fileoff = scp->fileoff;
1211 data_segment_scp = scp;
1213 copy_data_segment (lca[i]);
1215 else
1217 if (strncmp (scp->segname, SEG_LINKEDIT, 16) == 0)
1219 if (linkedit_delta)
1220 unexec_error ("cannot handle multiple LINKEDIT segments"
1221 " in input file");
1222 linkedit_delta = curr_file_offset - scp->fileoff;
1225 copy_segment (lca[i]);
1228 break;
1229 case LC_SYMTAB:
1230 copy_symtab (lca[i], linkedit_delta);
1231 break;
1232 case LC_DYSYMTAB:
1233 copy_dysymtab (lca[i], linkedit_delta);
1234 break;
1235 case LC_TWOLEVEL_HINTS:
1236 copy_twolevelhints (lca[i], linkedit_delta);
1237 break;
1238 #ifdef LC_DYLD_INFO
1239 case LC_DYLD_INFO:
1240 case LC_DYLD_INFO_ONLY:
1241 copy_dyld_info (lca[i], linkedit_delta);
1242 break;
1243 #endif
1244 #ifdef LC_FUNCTION_STARTS
1245 case LC_FUNCTION_STARTS:
1246 #ifdef LC_DATA_IN_CODE
1247 case LC_DATA_IN_CODE:
1248 #endif
1249 #ifdef LC_DYLIB_CODE_SIGN_DRS
1250 case LC_DYLIB_CODE_SIGN_DRS:
1251 #endif
1252 copy_linkedit_data (lca[i], linkedit_delta);
1253 break;
1254 #endif
1255 default:
1256 copy_other (lca[i]);
1257 break;
1260 if (curr_header_offset > text_seg_lowest_offset)
1261 unexec_error ("not enough room for load commands for new __DATA segments"
1262 " (increase headerpad_extra in configure.in to at least %lX)",
1263 num_unexec_regions * sizeof (struct segment_command));
1265 printf ("%ld unused bytes follow Mach-O header\n",
1266 text_seg_lowest_offset - curr_header_offset);
1268 mh.sizeofcmds = curr_header_offset - sizeof (struct mach_header);
1269 if (!unexec_write (0, &mh, sizeof (struct mach_header)))
1270 unexec_error ("cannot write final header contents");
1273 /* Take a snapshot of Emacs and make a Mach-O format executable file
1274 from it. The file names of the output and input files are outfile
1275 and infile, respectively. The three other parameters are
1276 ignored. */
1277 void
1278 unexec (const char *outfile, const char *infile)
1280 if (in_dumped_exec)
1281 unexec_error ("Unexec from a dumped executable is not supported.");
1283 pagesize = getpagesize ();
1284 infd = emacs_open (infile, O_RDONLY, 0);
1285 if (infd < 0)
1287 unexec_error ("%s: %s", infile, strerror (errno));
1290 outfd = emacs_open (outfile, O_WRONLY | O_TRUNC | O_CREAT, 0777);
1291 if (outfd < 0)
1293 emacs_close (infd);
1294 unexec_error ("%s: %s", outfile, strerror (errno));
1297 build_region_list ();
1298 read_load_commands ();
1300 find_emacs_zone_regions ();
1301 unexec_regions_merge ();
1303 in_dumped_exec = 1;
1305 dump_it ();
1307 emacs_close (outfd);
1311 void
1312 unexec_init_emacs_zone (void)
1314 emacs_zone = malloc_create_zone (0, 0);
1315 malloc_set_zone_name (emacs_zone, "EmacsZone");
1318 #ifndef MACOSX_MALLOC_MULT16
1319 #define MACOSX_MALLOC_MULT16 1
1320 #endif
1322 typedef struct unexec_malloc_header {
1323 union {
1324 char c[8];
1325 size_t size;
1326 } u;
1327 } unexec_malloc_header_t;
1329 #if MACOSX_MALLOC_MULT16
1331 #define ptr_in_unexec_regions(p) ((((vm_address_t) (p)) & 8) != 0)
1333 #else
1336 ptr_in_unexec_regions (void *ptr)
1338 int i;
1340 for (i = 0; i < num_unexec_regions; i++)
1341 if ((vm_address_t) ptr - unexec_regions[i].range.address
1342 < unexec_regions[i].range.size)
1343 return 1;
1345 return 0;
1348 #endif
1350 void *
1351 unexec_malloc (size_t size)
1353 if (in_dumped_exec)
1355 void *p;
1357 p = malloc (size);
1358 #if MACOSX_MALLOC_MULT16
1359 assert (((vm_address_t) p % 16) == 0);
1360 #endif
1361 return p;
1363 else
1365 unexec_malloc_header_t *ptr;
1367 ptr = (unexec_malloc_header_t *)
1368 malloc_zone_malloc (emacs_zone, size + sizeof (unexec_malloc_header_t));
1369 ptr->u.size = size;
1370 ptr++;
1371 #if MACOSX_MALLOC_MULT16
1372 assert (((vm_address_t) ptr % 16) == 8);
1373 #endif
1374 return (void *) ptr;
1378 void *
1379 unexec_realloc (void *old_ptr, size_t new_size)
1381 if (in_dumped_exec)
1383 void *p;
1385 if (ptr_in_unexec_regions (old_ptr))
1387 size_t old_size = ((unexec_malloc_header_t *) old_ptr)[-1].u.size;
1388 size_t size = new_size > old_size ? old_size : new_size;
1390 p = malloc (new_size);
1391 if (size)
1392 memcpy (p, old_ptr, size);
1394 else
1396 p = realloc (old_ptr, new_size);
1398 #if MACOSX_MALLOC_MULT16
1399 assert (((vm_address_t) p % 16) == 0);
1400 #endif
1401 return p;
1403 else
1405 unexec_malloc_header_t *ptr;
1407 ptr = (unexec_malloc_header_t *)
1408 malloc_zone_realloc (emacs_zone, (unexec_malloc_header_t *) old_ptr - 1,
1409 new_size + sizeof (unexec_malloc_header_t));
1410 ptr->u.size = new_size;
1411 ptr++;
1412 #if MACOSX_MALLOC_MULT16
1413 assert (((vm_address_t) ptr % 16) == 8);
1414 #endif
1415 return (void *) ptr;
1419 void
1420 unexec_free (void *ptr)
1422 if (ptr == NULL)
1423 return;
1424 if (in_dumped_exec)
1426 if (!ptr_in_unexec_regions (ptr))
1427 free (ptr);
1429 else
1430 malloc_zone_free (emacs_zone, (unexec_malloc_header_t *) ptr - 1);