Merge from mainline.
[bpt/emacs.git] / src / unexmacosx.c
1 /* Dump Emacs in Mach-O format for use on Mac OS X.
2 Copyright (C) 2001, 2002, 2003, 2004, 2005,
3 2006, 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
4
5 This file is part of GNU Emacs.
6
7 GNU Emacs is free software: you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation, either version 3 of the License, or
10 (at your option) any later version.
11
12 GNU Emacs is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
19
20 /* Contributed by Andrew Choi (akochoi@mac.com). */
21
22 /* Documentation note.
23
24 Consult the following documents/files for a description of the
25 Mach-O format: the file loader.h, man pages for Mach-O and ld, old
26 NEXTSTEP documents of the Mach-O format. The tool otool dumps the
27 mach header (-h option) and the load commands (-l option) in a
28 Mach-O file. The tool nm on Mac OS X displays the symbol table in
29 a Mach-O file. For examples of unexec for the Mach-O format, see
30 the file unexnext.c in the GNU Emacs distribution, the file
31 unexdyld.c in the Darwin port of GNU Emacs 20.7, and unexdyld.c in
32 the Darwin port of XEmacs 21.1. Also the Darwin Libc source
33 contains the source code for malloc_freezedry and malloc_jumpstart.
34 Read that to see what they do. This file was written completely
35 from scratch, making use of information from the above sources. */
36
37 /* The Mac OS X implementation of unexec makes use of Darwin's `zone'
38 memory allocator. All calls to malloc, realloc, and free in Emacs
39 are redirected to unexec_malloc, unexec_realloc, and unexec_free in
40 this file. When temacs is run, all memory requests are handled in
41 the zone EmacsZone. The Darwin memory allocator library calls
42 maintain the data structures to manage this zone. Dumping writes
43 its contents to data segments of the executable file. When emacs
44 is run, the loader recreates the contents of the zone in memory.
45 However since the initialization routine of the zone memory
46 allocator is run again, this `zone' can no longer be used as a
47 heap. That is why emacs uses the ordinary malloc system call to
48 allocate memory. Also, when a block of memory needs to be
49 reallocated and the new size is larger than the old one, a new
50 block must be obtained by malloc and the old contents copied to
51 it. */
52
53 /* Peculiarity of the Mach-O files generated by ld in Mac OS X
54 (possible causes of future bugs if changed).
55
56 The file offset of the start of the __TEXT segment is zero. Since
57 the Mach header and load commands are located at the beginning of a
58 Mach-O file, copying the contents of the __TEXT segment from the
59 input file overwrites them in the output file. Despite this,
60 unexec works fine as written below because the segment load command
61 for __TEXT appears, and is therefore processed, before all other
62 load commands except the segment load command for __PAGEZERO, which
63 remains unchanged.
64
65 Although the file offset of the start of the __TEXT segment is
66 zero, none of the sections it contains actually start there. In
67 fact, the earliest one starts a few hundred bytes beyond the end of
68 the last load command. The linker option -headerpad controls the
69 minimum size of this padding. Its setting can be changed in
70 s/darwin.h. A value of 0x690, e.g., leaves room for 30 additional
71 load commands for the newly created __DATA segments (at 56 bytes
72 each). Unexec fails if there is not enough room for these new
73 segments.
74
75 The __TEXT segment contains the sections __text, __cstring,
76 __picsymbol_stub, and __const and the __DATA segment contains the
77 sections __data, __la_symbol_ptr, __nl_symbol_ptr, __dyld, __bss,
78 and __common. The other segments do not contain any sections.
79 These sections are copied from the input file to the output file,
80 except for __data, __bss, and __common, which are dumped from
81 memory. The types of the sections __bss and __common are changed
82 from S_ZEROFILL to S_REGULAR. Note that the number of sections and
83 their relative order in the input and output files remain
84 unchanged. Otherwise all n_sect fields in the nlist records in the
85 symbol table (specified by the LC_SYMTAB load command) will have to
86 be changed accordingly.
87 */
88
89 #include <stdio.h>
90 #include <stdlib.h>
91 #include <fcntl.h>
92 #include <stdarg.h>
93 #include <sys/types.h>
94 #include <unistd.h>
95 #include <mach/mach.h>
96 #include <mach-o/loader.h>
97 #include <mach-o/reloc.h>
98 #if defined (__ppc__)
99 #include <mach-o/ppc/reloc.h>
100 #endif
101 #include <config.h>
102 #undef malloc
103 #undef realloc
104 #undef free
105 #ifdef HAVE_MALLOC_MALLOC_H
106 #include <malloc/malloc.h>
107 #else
108 #include <objc/malloc.h>
109 #endif
110
111 #include <assert.h>
112
113 #ifdef _LP64
114 #define mach_header mach_header_64
115 #define segment_command segment_command_64
116 #undef VM_REGION_BASIC_INFO_COUNT
117 #define VM_REGION_BASIC_INFO_COUNT VM_REGION_BASIC_INFO_COUNT_64
118 #undef VM_REGION_BASIC_INFO
119 #define VM_REGION_BASIC_INFO VM_REGION_BASIC_INFO_64
120 #undef LC_SEGMENT
121 #define LC_SEGMENT LC_SEGMENT_64
122 #define vm_region vm_region_64
123 #define section section_64
124 #undef MH_MAGIC
125 #define MH_MAGIC MH_MAGIC_64
126 #endif
127
128 #define VERBOSE 1
129
130 /* Size of buffer used to copy data from the input file to the output
131 file in function unexec_copy. */
132 #define UNEXEC_COPY_BUFSZ 1024
133
134 /* Regions with memory addresses above this value are assumed to be
135 mapped to dynamically loaded libraries and will not be dumped. */
136 #define VM_DATA_TOP (20 * 1024 * 1024)
137
138 /* Type of an element on the list of regions to be dumped. */
139 struct region_t {
140 vm_address_t address;
141 vm_size_t size;
142 vm_prot_t protection;
143 vm_prot_t max_protection;
144
145 struct region_t *next;
146 };
147
148 /* Head and tail of the list of regions to be dumped. */
149 static struct region_t *region_list_head = 0;
150 static struct region_t *region_list_tail = 0;
151
152 /* Pointer to array of load commands. */
153 static struct load_command **lca;
154
155 /* Number of load commands. */
156 static int nlc;
157
158 /* The highest VM address of segments loaded by the input file.
159 Regions with addresses beyond this are assumed to be allocated
160 dynamically and thus require dumping. */
161 static vm_address_t infile_lc_highest_addr = 0;
162
163 /* The lowest file offset used by the all sections in the __TEXT
164 segments. This leaves room at the beginning of the file to store
165 the Mach-O header. Check this value against header size to ensure
166 the added load commands for the new __DATA segments did not
167 overwrite any of the sections in the __TEXT segment. */
168 static unsigned long text_seg_lowest_offset = 0x10000000;
169
170 /* Mach header. */
171 static struct mach_header mh;
172
173 /* Offset at which the next load command should be written. */
174 static unsigned long curr_header_offset = sizeof (struct mach_header);
175
176 /* Offset at which the next segment should be written. */
177 static unsigned long curr_file_offset = 0;
178
179 static unsigned long pagesize;
180 #define ROUNDUP_TO_PAGE_BOUNDARY(x) (((x) + pagesize - 1) & ~(pagesize - 1))
181
182 static int infd, outfd;
183
184 static int in_dumped_exec = 0;
185
186 static malloc_zone_t *emacs_zone;
187
188 /* file offset of input file's data segment */
189 static off_t data_segment_old_fileoff = 0;
190
191 static struct segment_command *data_segment_scp;
192
193 static void unexec_error (const char *format, ...) NO_RETURN;
194
195 /* Read N bytes from infd into memory starting at address DEST.
196 Return true if successful, false otherwise. */
197 static int
198 unexec_read (void *dest, size_t n)
199 {
200 return n == read (infd, dest, n);
201 }
202
203 /* Write COUNT bytes from memory starting at address SRC to outfd
204 starting at offset DEST. Return true if successful, false
205 otherwise. */
206 static int
207 unexec_write (off_t dest, const void *src, size_t count)
208 {
209 if (lseek (outfd, dest, SEEK_SET) != dest)
210 return 0;
211
212 return write (outfd, src, count) == count;
213 }
214
215 /* Write COUNT bytes of zeros to outfd starting at offset DEST.
216 Return true if successful, false otherwise. */
217 static int
218 unexec_write_zero (off_t dest, size_t count)
219 {
220 char buf[UNEXEC_COPY_BUFSZ];
221 ssize_t bytes;
222
223 memset (buf, 0, UNEXEC_COPY_BUFSZ);
224 if (lseek (outfd, dest, SEEK_SET) != dest)
225 return 0;
226
227 while (count > 0)
228 {
229 bytes = count > UNEXEC_COPY_BUFSZ ? UNEXEC_COPY_BUFSZ : count;
230 if (write (outfd, buf, bytes) != bytes)
231 return 0;
232 count -= bytes;
233 }
234
235 return 1;
236 }
237
238 /* Copy COUNT bytes from starting offset SRC in infd to starting
239 offset DEST in outfd. Return true if successful, false
240 otherwise. */
241 static int
242 unexec_copy (off_t dest, off_t src, ssize_t count)
243 {
244 ssize_t bytes_read;
245 ssize_t bytes_to_read;
246
247 char buf[UNEXEC_COPY_BUFSZ];
248
249 if (lseek (infd, src, SEEK_SET) != src)
250 return 0;
251
252 if (lseek (outfd, dest, SEEK_SET) != dest)
253 return 0;
254
255 while (count > 0)
256 {
257 bytes_to_read = count > UNEXEC_COPY_BUFSZ ? UNEXEC_COPY_BUFSZ : count;
258 bytes_read = read (infd, buf, bytes_to_read);
259 if (bytes_read <= 0)
260 return 0;
261 if (write (outfd, buf, bytes_read) != bytes_read)
262 return 0;
263 count -= bytes_read;
264 }
265
266 return 1;
267 }
268
269 /* Debugging and informational messages routines. */
270
271 static void
272 unexec_error (const char *format, ...)
273 {
274 va_list ap;
275
276 va_start (ap, format);
277 fprintf (stderr, "unexec: ");
278 vfprintf (stderr, format, ap);
279 fprintf (stderr, "\n");
280 va_end (ap);
281 exit (1);
282 }
283
284 static void
285 print_prot (vm_prot_t prot)
286 {
287 if (prot == VM_PROT_NONE)
288 printf ("none");
289 else
290 {
291 putchar (prot & VM_PROT_READ ? 'r' : ' ');
292 putchar (prot & VM_PROT_WRITE ? 'w' : ' ');
293 putchar (prot & VM_PROT_EXECUTE ? 'x' : ' ');
294 putchar (' ');
295 }
296 }
297
298 static void
299 print_region (vm_address_t address, vm_size_t size, vm_prot_t prot,
300 vm_prot_t max_prot)
301 {
302 printf ("%#10lx %#8lx ", (long) address, (long) size);
303 print_prot (prot);
304 putchar (' ');
305 print_prot (max_prot);
306 putchar ('\n');
307 }
308
309 static void
310 print_region_list (void)
311 {
312 struct region_t *r;
313
314 printf (" address size prot maxp\n");
315
316 for (r = region_list_head; r; r = r->next)
317 print_region (r->address, r->size, r->protection, r->max_protection);
318 }
319
320 static void
321 print_regions (void)
322 {
323 task_t target_task = mach_task_self ();
324 vm_address_t address = (vm_address_t) 0;
325 vm_size_t size;
326 struct vm_region_basic_info info;
327 mach_msg_type_number_t info_count = VM_REGION_BASIC_INFO_COUNT;
328 mach_port_t object_name;
329
330 printf (" address size prot maxp\n");
331
332 while (vm_region (target_task, &address, &size, VM_REGION_BASIC_INFO,
333 (vm_region_info_t) &info, &info_count, &object_name)
334 == KERN_SUCCESS && info_count == VM_REGION_BASIC_INFO_COUNT)
335 {
336 print_region (address, size, info.protection, info.max_protection);
337
338 if (object_name != MACH_PORT_NULL)
339 mach_port_deallocate (target_task, object_name);
340
341 address += size;
342 }
343 }
344
345 /* Build the list of regions that need to be dumped. Regions with
346 addresses above VM_DATA_TOP are omitted. Adjacent regions with
347 identical protection are merged. Note that non-writable regions
348 cannot be omitted because they some regions created at run time are
349 read-only. */
350 static void
351 build_region_list (void)
352 {
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;
359 struct region_t *r;
360
361 #if VERBOSE
362 printf ("--- List of All Regions ---\n");
363 printf (" address size prot maxp\n");
364 #endif
365
366 while (vm_region (target_task, &address, &size, VM_REGION_BASIC_INFO,
367 (vm_region_info_t) &info, &info_count, &object_name)
368 == KERN_SUCCESS && info_count == VM_REGION_BASIC_INFO_COUNT)
369 {
370 /* Done when we reach addresses of shared libraries, which are
371 loaded in high memory. */
372 if (address >= VM_DATA_TOP)
373 break;
374
375 #if VERBOSE
376 print_region (address, size, info.protection, info.max_protection);
377 #endif
378
379 /* If a region immediately follows the previous one (the one
380 most recently added to the list) and has identical
381 protection, merge it with the latter. Otherwise create a
382 new list element for it. */
383 if (region_list_tail
384 && info.protection == region_list_tail->protection
385 && info.max_protection == region_list_tail->max_protection
386 && region_list_tail->address + region_list_tail->size == address)
387 {
388 region_list_tail->size += size;
389 }
390 else
391 {
392 r = (struct region_t *) malloc (sizeof (struct region_t));
393
394 if (!r)
395 unexec_error ("cannot allocate region structure");
396
397 r->address = address;
398 r->size = size;
399 r->protection = info.protection;
400 r->max_protection = info.max_protection;
401
402 r->next = 0;
403 if (region_list_head == 0)
404 {
405 region_list_head = r;
406 region_list_tail = r;
407 }
408 else
409 {
410 region_list_tail->next = r;
411 region_list_tail = r;
412 }
413
414 /* Deallocate (unused) object name returned by
415 vm_region. */
416 if (object_name != MACH_PORT_NULL)
417 mach_port_deallocate (target_task, object_name);
418 }
419
420 address += size;
421 }
422
423 printf ("--- List of Regions to be Dumped ---\n");
424 print_region_list ();
425 }
426
427
428 #define MAX_UNEXEC_REGIONS 400
429
430 static int num_unexec_regions;
431 typedef struct {
432 vm_range_t range;
433 vm_size_t filesize;
434 } unexec_region_info;
435 static unexec_region_info unexec_regions[MAX_UNEXEC_REGIONS];
436
437 static void
438 unexec_regions_recorder (task_t task, void *rr, unsigned type,
439 vm_range_t *ranges, unsigned num)
440 {
441 vm_address_t p;
442 vm_size_t filesize;
443
444 while (num && num_unexec_regions < MAX_UNEXEC_REGIONS)
445 {
446 /* Subtract the size of trailing null bytes from filesize. It
447 can be smaller than vmsize in segment commands. In such a
448 case, trailing bytes are initialized with zeros. */
449 for (p = ranges->address + ranges->size; p > ranges->address; p--)
450 if (*(((char *) p)-1))
451 break;
452 filesize = p - ranges->address;
453
454 unexec_regions[num_unexec_regions].filesize = filesize;
455 unexec_regions[num_unexec_regions++].range = *ranges;
456 printf ("%#10lx (sz: %#8lx/%#8lx)\n", (long) (ranges->address),
457 (long) filesize, (long) (ranges->size));
458 ranges++; num--;
459 }
460 }
461
462 static kern_return_t
463 unexec_reader (task_t task, vm_address_t address, vm_size_t size, void **ptr)
464 {
465 *ptr = (void *) address;
466 return KERN_SUCCESS;
467 }
468
469 static void
470 find_emacs_zone_regions (void)
471 {
472 num_unexec_regions = 0;
473
474 emacs_zone->introspect->enumerator (mach_task_self(), 0,
475 MALLOC_PTR_REGION_RANGE_TYPE
476 | MALLOC_ADMIN_REGION_RANGE_TYPE,
477 (vm_address_t) emacs_zone,
478 unexec_reader,
479 unexec_regions_recorder);
480
481 if (num_unexec_regions == MAX_UNEXEC_REGIONS)
482 unexec_error ("find_emacs_zone_regions: too many regions");
483 }
484
485 static int
486 unexec_regions_sort_compare (const void *a, const void *b)
487 {
488 vm_address_t aa = ((unexec_region_info *) a)->range.address;
489 vm_address_t bb = ((unexec_region_info *) b)->range.address;
490
491 if (aa < bb)
492 return -1;
493 else if (aa > bb)
494 return 1;
495 else
496 return 0;
497 }
498
499 static void
500 unexec_regions_merge (void)
501 {
502 int i, n;
503 unexec_region_info r;
504 vm_size_t padsize;
505
506 qsort (unexec_regions, num_unexec_regions, sizeof (unexec_regions[0]),
507 &unexec_regions_sort_compare);
508 n = 0;
509 r = unexec_regions[0];
510 padsize = r.range.address & (pagesize - 1);
511 if (padsize)
512 {
513 r.range.address -= padsize;
514 r.range.size += padsize;
515 r.filesize += padsize;
516 }
517 for (i = 1; i < num_unexec_regions; i++)
518 {
519 if (r.range.address + r.range.size == unexec_regions[i].range.address
520 && r.range.size - r.filesize < 2 * pagesize)
521 {
522 r.filesize = r.range.size + unexec_regions[i].filesize;
523 r.range.size += unexec_regions[i].range.size;
524 }
525 else
526 {
527 unexec_regions[n++] = r;
528 r = unexec_regions[i];
529 padsize = r.range.address & (pagesize - 1);
530 if (padsize)
531 {
532 if ((unexec_regions[n-1].range.address
533 + unexec_regions[n-1].range.size) == r.range.address)
534 unexec_regions[n-1].range.size -= padsize;
535
536 r.range.address -= padsize;
537 r.range.size += padsize;
538 r.filesize += padsize;
539 }
540 }
541 }
542 unexec_regions[n++] = r;
543 num_unexec_regions = n;
544 }
545
546
547 /* More informational messages routines. */
548
549 static void
550 print_load_command_name (int lc)
551 {
552 switch (lc)
553 {
554 case LC_SEGMENT:
555 #ifndef _LP64
556 printf ("LC_SEGMENT ");
557 #else
558 printf ("LC_SEGMENT_64 ");
559 #endif
560 break;
561 case LC_LOAD_DYLINKER:
562 printf ("LC_LOAD_DYLINKER ");
563 break;
564 case LC_LOAD_DYLIB:
565 printf ("LC_LOAD_DYLIB ");
566 break;
567 case LC_SYMTAB:
568 printf ("LC_SYMTAB ");
569 break;
570 case LC_DYSYMTAB:
571 printf ("LC_DYSYMTAB ");
572 break;
573 case LC_UNIXTHREAD:
574 printf ("LC_UNIXTHREAD ");
575 break;
576 case LC_PREBOUND_DYLIB:
577 printf ("LC_PREBOUND_DYLIB");
578 break;
579 case LC_TWOLEVEL_HINTS:
580 printf ("LC_TWOLEVEL_HINTS");
581 break;
582 #ifdef LC_UUID
583 case LC_UUID:
584 printf ("LC_UUID ");
585 break;
586 #endif
587 #ifdef LC_DYLD_INFO
588 case LC_DYLD_INFO:
589 printf ("LC_DYLD_INFO ");
590 break;
591 case LC_DYLD_INFO_ONLY:
592 printf ("LC_DYLD_INFO_ONLY");
593 break;
594 #endif
595 default:
596 printf ("unknown ");
597 }
598 }
599
600 static void
601 print_load_command (struct load_command *lc)
602 {
603 print_load_command_name (lc->cmd);
604 printf ("%8d", lc->cmdsize);
605
606 if (lc->cmd == LC_SEGMENT)
607 {
608 struct segment_command *scp;
609 struct section *sectp;
610 int j;
611
612 scp = (struct segment_command *) lc;
613 printf (" %-16.16s %#10lx %#8lx\n",
614 scp->segname, (long) (scp->vmaddr), (long) (scp->vmsize));
615
616 sectp = (struct section *) (scp + 1);
617 for (j = 0; j < scp->nsects; j++)
618 {
619 printf (" %-16.16s %#10lx %#8lx\n",
620 sectp->sectname, (long) (sectp->addr), (long) (sectp->size));
621 sectp++;
622 }
623 }
624 else
625 printf ("\n");
626 }
627
628 /* Read header and load commands from input file. Store the latter in
629 the global array lca. Store the total number of load commands in
630 global variable nlc. */
631 static void
632 read_load_commands (void)
633 {
634 int i;
635
636 if (!unexec_read (&mh, sizeof (struct mach_header)))
637 unexec_error ("cannot read mach-o header");
638
639 if (mh.magic != MH_MAGIC)
640 unexec_error ("input file not in Mach-O format");
641
642 if (mh.filetype != MH_EXECUTE)
643 unexec_error ("input Mach-O file is not an executable object file");
644
645 #if VERBOSE
646 printf ("--- Header Information ---\n");
647 printf ("Magic = 0x%08x\n", mh.magic);
648 printf ("CPUType = %d\n", mh.cputype);
649 printf ("CPUSubType = %d\n", mh.cpusubtype);
650 printf ("FileType = 0x%x\n", mh.filetype);
651 printf ("NCmds = %d\n", mh.ncmds);
652 printf ("SizeOfCmds = %d\n", mh.sizeofcmds);
653 printf ("Flags = 0x%08x\n", mh.flags);
654 #endif
655
656 nlc = mh.ncmds;
657 lca = (struct load_command **) malloc (nlc * sizeof (struct load_command *));
658
659 for (i = 0; i < nlc; i++)
660 {
661 struct load_command lc;
662 /* Load commands are variable-size: so read the command type and
663 size first and then read the rest. */
664 if (!unexec_read (&lc, sizeof (struct load_command)))
665 unexec_error ("cannot read load command");
666 lca[i] = (struct load_command *) malloc (lc.cmdsize);
667 memcpy (lca[i], &lc, sizeof (struct load_command));
668 if (!unexec_read (lca[i] + 1, lc.cmdsize - sizeof (struct load_command)))
669 unexec_error ("cannot read content of load command");
670 if (lc.cmd == LC_SEGMENT)
671 {
672 struct segment_command *scp = (struct segment_command *) lca[i];
673
674 if (scp->vmaddr + scp->vmsize > infile_lc_highest_addr)
675 infile_lc_highest_addr = scp->vmaddr + scp->vmsize;
676
677 if (strncmp (scp->segname, SEG_TEXT, 16) == 0)
678 {
679 struct section *sectp = (struct section *) (scp + 1);
680 int j;
681
682 for (j = 0; j < scp->nsects; j++)
683 if (sectp->offset < text_seg_lowest_offset)
684 text_seg_lowest_offset = sectp->offset;
685 }
686 }
687 }
688
689 printf ("Highest address of load commands in input file: %#8lx\n",
690 (unsigned long)infile_lc_highest_addr);
691
692 printf ("Lowest offset of all sections in __TEXT segment: %#8lx\n",
693 text_seg_lowest_offset);
694
695 printf ("--- List of Load Commands in Input File ---\n");
696 printf ("# cmd cmdsize name address size\n");
697
698 for (i = 0; i < nlc; i++)
699 {
700 printf ("%1d ", i);
701 print_load_command (lca[i]);
702 }
703 }
704
705 /* Copy a LC_SEGMENT load command other than the __DATA segment from
706 the input file to the output file, adjusting the file offset of the
707 segment and the file offsets of sections contained in it. */
708 static void
709 copy_segment (struct load_command *lc)
710 {
711 struct segment_command *scp = (struct segment_command *) lc;
712 unsigned long old_fileoff = scp->fileoff;
713 struct section *sectp;
714 int j;
715
716 scp->fileoff = curr_file_offset;
717
718 sectp = (struct section *) (scp + 1);
719 for (j = 0; j < scp->nsects; j++)
720 {
721 sectp->offset += curr_file_offset - old_fileoff;
722 sectp++;
723 }
724
725 printf ("Writing segment %-16.16s @ %#8lx (%#8lx/%#8lx @ %#10lx)\n",
726 scp->segname, (long) (scp->fileoff), (long) (scp->filesize),
727 (long) (scp->vmsize), (long) (scp->vmaddr));
728
729 if (!unexec_copy (scp->fileoff, old_fileoff, scp->filesize))
730 unexec_error ("cannot copy segment from input to output file");
731 curr_file_offset += ROUNDUP_TO_PAGE_BOUNDARY (scp->filesize);
732
733 if (!unexec_write (curr_header_offset, lc, lc->cmdsize))
734 unexec_error ("cannot write load command to header");
735
736 curr_header_offset += lc->cmdsize;
737 }
738
739 /* Copy a LC_SEGMENT load command for the __DATA segment in the input
740 file to the output file. We assume that only one such segment load
741 command exists in the input file and it contains the sections
742 __data, __bss, __common, __la_symbol_ptr, __nl_symbol_ptr, and
743 __dyld. The first three of these should be dumped from memory and
744 the rest should be copied from the input file. Note that the
745 sections __bss and __common contain no data in the input file
746 because their flag fields have the value S_ZEROFILL. Dumping these
747 from memory makes it necessary to adjust file offset fields in
748 subsequently dumped load commands. Then, create new __DATA segment
749 load commands for regions on the region list other than the one
750 corresponding to the __DATA segment in the input file. */
751 static void
752 copy_data_segment (struct load_command *lc)
753 {
754 struct segment_command *scp = (struct segment_command *) lc;
755 struct section *sectp;
756 int j;
757 unsigned long header_offset, old_file_offset;
758
759 /* The new filesize of the segment is set to its vmsize because data
760 blocks for segments must start at region boundaries. Note that
761 this may leave unused locations at the end of the segment data
762 block because the total of the sizes of all sections in the
763 segment is generally smaller than vmsize. */
764 scp->filesize = scp->vmsize;
765
766 printf ("Writing segment %-16.16s @ %#8lx (%#8lx/%#8lx @ %#10lx)\n",
767 scp->segname, curr_file_offset, (long)(scp->filesize),
768 (long)(scp->vmsize), (long) (scp->vmaddr));
769
770 /* Offsets in the output file for writing the next section structure
771 and segment data block, respectively. */
772 header_offset = curr_header_offset + sizeof (struct segment_command);
773
774 sectp = (struct section *) (scp + 1);
775 for (j = 0; j < scp->nsects; j++)
776 {
777 old_file_offset = sectp->offset;
778 sectp->offset = sectp->addr - scp->vmaddr + curr_file_offset;
779 /* The __data section is dumped from memory. The __bss and
780 __common sections are also dumped from memory but their flag
781 fields require changing (from S_ZEROFILL to S_REGULAR). The
782 other three kinds of sections are just copied from the input
783 file. */
784 if (strncmp (sectp->sectname, SECT_DATA, 16) == 0)
785 {
786 if (!unexec_write (sectp->offset, (void *) sectp->addr, sectp->size))
787 unexec_error ("cannot write section %s", SECT_DATA);
788 if (!unexec_write (header_offset, sectp, sizeof (struct section)))
789 unexec_error ("cannot write section %s's header", SECT_DATA);
790 }
791 else if (strncmp (sectp->sectname, SECT_COMMON, 16) == 0)
792 {
793 sectp->flags = S_REGULAR;
794 if (!unexec_write (sectp->offset, (void *) sectp->addr, sectp->size))
795 unexec_error ("cannot write section %s", sectp->sectname);
796 if (!unexec_write (header_offset, sectp, sizeof (struct section)))
797 unexec_error ("cannot write section %s's header", sectp->sectname);
798 }
799 else if (strncmp (sectp->sectname, SECT_BSS, 16) == 0)
800 {
801 extern char *my_endbss_static;
802 unsigned long my_size;
803
804 sectp->flags = S_REGULAR;
805
806 /* Clear uninitialized local variables in statically linked
807 libraries. In particular, function pointers stored by
808 libSystemStub.a, which is introduced in Mac OS X 10.4 for
809 binary compatibility with respect to long double, are
810 cleared so that they will be reinitialized when the
811 dumped binary is executed on other versions of OS. */
812 my_size = (unsigned long)my_endbss_static - sectp->addr;
813 if (!(sectp->addr <= (unsigned long)my_endbss_static
814 && my_size <= sectp->size))
815 unexec_error ("my_endbss_static is not in section %s",
816 sectp->sectname);
817 if (!unexec_write (sectp->offset, (void *) sectp->addr, my_size))
818 unexec_error ("cannot write section %s", sectp->sectname);
819 if (!unexec_write_zero (sectp->offset + my_size,
820 sectp->size - my_size))
821 unexec_error ("cannot write section %s", sectp->sectname);
822 if (!unexec_write (header_offset, sectp, sizeof (struct section)))
823 unexec_error ("cannot write section %s's header", sectp->sectname);
824 }
825 else if (strncmp (sectp->sectname, "__la_symbol_ptr", 16) == 0
826 || strncmp (sectp->sectname, "__nl_symbol_ptr", 16) == 0
827 || strncmp (sectp->sectname, "__la_sym_ptr2", 16) == 0
828 || strncmp (sectp->sectname, "__dyld", 16) == 0
829 || strncmp (sectp->sectname, "__const", 16) == 0
830 || strncmp (sectp->sectname, "__cfstring", 16) == 0
831 || strncmp (sectp->sectname, "__gcc_except_tab", 16) == 0
832 || strncmp (sectp->sectname, "__program_vars", 16) == 0
833 || strncmp (sectp->sectname, "__objc_", 7) == 0)
834 {
835 if (!unexec_copy (sectp->offset, old_file_offset, sectp->size))
836 unexec_error ("cannot copy section %s", sectp->sectname);
837 if (!unexec_write (header_offset, sectp, sizeof (struct section)))
838 unexec_error ("cannot write section %s's header", sectp->sectname);
839 }
840 else
841 unexec_error ("unrecognized section name in __DATA segment");
842
843 printf (" section %-16.16s at %#8lx - %#8lx (sz: %#8lx)\n",
844 sectp->sectname, (long) (sectp->offset),
845 (long) (sectp->offset + sectp->size), (long) (sectp->size));
846
847 header_offset += sizeof (struct section);
848 sectp++;
849 }
850
851 curr_file_offset += ROUNDUP_TO_PAGE_BOUNDARY (scp->filesize);
852
853 if (!unexec_write (curr_header_offset, scp, sizeof (struct segment_command)))
854 unexec_error ("cannot write header of __DATA segment");
855 curr_header_offset += lc->cmdsize;
856
857 /* Create new __DATA segment load commands for regions on the region
858 list that do not corresponding to any segment load commands in
859 the input file.
860 */
861 for (j = 0; j < num_unexec_regions; j++)
862 {
863 struct segment_command sc;
864
865 sc.cmd = LC_SEGMENT;
866 sc.cmdsize = sizeof (struct segment_command);
867 strncpy (sc.segname, SEG_DATA, 16);
868 sc.vmaddr = unexec_regions[j].range.address;
869 sc.vmsize = unexec_regions[j].range.size;
870 sc.fileoff = curr_file_offset;
871 sc.filesize = unexec_regions[j].filesize;
872 sc.maxprot = VM_PROT_READ | VM_PROT_WRITE;
873 sc.initprot = VM_PROT_READ | VM_PROT_WRITE;
874 sc.nsects = 0;
875 sc.flags = 0;
876
877 printf ("Writing segment %-16.16s @ %#8lx (%#8lx/%#8lx @ %#10lx)\n",
878 sc.segname, (long) (sc.fileoff), (long) (sc.filesize),
879 (long) (sc.vmsize), (long) (sc.vmaddr));
880
881 if (!unexec_write (sc.fileoff, (void *) sc.vmaddr, sc.filesize))
882 unexec_error ("cannot write new __DATA segment");
883 curr_file_offset += ROUNDUP_TO_PAGE_BOUNDARY (sc.filesize);
884
885 if (!unexec_write (curr_header_offset, &sc, sc.cmdsize))
886 unexec_error ("cannot write new __DATA segment's header");
887 curr_header_offset += sc.cmdsize;
888 mh.ncmds++;
889 }
890 }
891
892 /* Copy a LC_SYMTAB load command from the input file to the output
893 file, adjusting the file offset fields. */
894 static void
895 copy_symtab (struct load_command *lc, long delta)
896 {
897 struct symtab_command *stp = (struct symtab_command *) lc;
898
899 stp->symoff += delta;
900 stp->stroff += delta;
901
902 printf ("Writing LC_SYMTAB command\n");
903
904 if (!unexec_write (curr_header_offset, lc, lc->cmdsize))
905 unexec_error ("cannot write symtab command to header");
906
907 curr_header_offset += lc->cmdsize;
908 }
909
910 /* Fix up relocation entries. */
911 static void
912 unrelocate (const char *name, off_t reloff, int nrel, vm_address_t base)
913 {
914 int i, unreloc_count;
915 struct relocation_info reloc_info;
916 struct scattered_relocation_info *sc_reloc_info
917 = (struct scattered_relocation_info *) &reloc_info;
918 vm_address_t location;
919
920 for (unreloc_count = 0, i = 0; i < nrel; i++)
921 {
922 if (lseek (infd, reloff, L_SET) != reloff)
923 unexec_error ("unrelocate: %s:%d cannot seek to reloc_info", name, i);
924 if (!unexec_read (&reloc_info, sizeof (reloc_info)))
925 unexec_error ("unrelocate: %s:%d cannot read reloc_info", name, i);
926 reloff += sizeof (reloc_info);
927
928 if (sc_reloc_info->r_scattered == 0)
929 switch (reloc_info.r_type)
930 {
931 case GENERIC_RELOC_VANILLA:
932 location = base + reloc_info.r_address;
933 if (location >= data_segment_scp->vmaddr
934 && location < (data_segment_scp->vmaddr
935 + data_segment_scp->vmsize))
936 {
937 off_t src_off = data_segment_old_fileoff
938 + (location - data_segment_scp->vmaddr);
939 off_t dst_off = data_segment_scp->fileoff
940 + (location - data_segment_scp->vmaddr);
941
942 if (!unexec_copy (dst_off, src_off, 1 << reloc_info.r_length))
943 unexec_error ("unrelocate: %s:%d cannot copy original value",
944 name, i);
945 unreloc_count++;
946 }
947 break;
948 default:
949 unexec_error ("unrelocate: %s:%d cannot handle type = %d",
950 name, i, reloc_info.r_type);
951 }
952 else
953 switch (sc_reloc_info->r_type)
954 {
955 #if defined (__ppc__)
956 case PPC_RELOC_PB_LA_PTR:
957 /* nothing to do for prebound lazy pointer */
958 break;
959 #endif
960 default:
961 unexec_error ("unrelocate: %s:%d cannot handle scattered type = %d",
962 name, i, sc_reloc_info->r_type);
963 }
964 }
965
966 if (nrel > 0)
967 printf ("Fixed up %d/%d %s relocation entries in data segment.\n",
968 unreloc_count, nrel, name);
969 }
970
971 #if __ppc64__
972 /* Rebase r_address in the relocation table. */
973 static void
974 rebase_reloc_address (off_t reloff, int nrel, long linkedit_delta, long diff)
975 {
976 int i;
977 struct relocation_info reloc_info;
978 struct scattered_relocation_info *sc_reloc_info
979 = (struct scattered_relocation_info *) &reloc_info;
980
981 for (i = 0; i < nrel; i++, reloff += sizeof (reloc_info))
982 {
983 if (lseek (infd, reloff - linkedit_delta, L_SET)
984 != reloff - linkedit_delta)
985 unexec_error ("rebase_reloc_table: cannot seek to reloc_info");
986 if (!unexec_read (&reloc_info, sizeof (reloc_info)))
987 unexec_error ("rebase_reloc_table: cannot read reloc_info");
988
989 if (sc_reloc_info->r_scattered == 0
990 && reloc_info.r_type == GENERIC_RELOC_VANILLA)
991 {
992 reloc_info.r_address -= diff;
993 if (!unexec_write (reloff, &reloc_info, sizeof (reloc_info)))
994 unexec_error ("rebase_reloc_table: cannot write reloc_info");
995 }
996 }
997 }
998 #endif
999
1000 /* Copy a LC_DYSYMTAB load command from the input file to the output
1001 file, adjusting the file offset fields. */
1002 static void
1003 copy_dysymtab (struct load_command *lc, long delta)
1004 {
1005 struct dysymtab_command *dstp = (struct dysymtab_command *) lc;
1006 vm_address_t base;
1007
1008 #ifdef _LP64
1009 #if __ppc64__
1010 {
1011 int i;
1012
1013 base = 0;
1014 for (i = 0; i < nlc; i++)
1015 if (lca[i]->cmd == LC_SEGMENT)
1016 {
1017 struct segment_command *scp = (struct segment_command *) lca[i];
1018
1019 if (scp->vmaddr + scp->vmsize > 0x100000000
1020 && (scp->initprot & VM_PROT_WRITE) != 0)
1021 {
1022 base = data_segment_scp->vmaddr;
1023 break;
1024 }
1025 }
1026 }
1027 #else
1028 /* First writable segment address. */
1029 base = data_segment_scp->vmaddr;
1030 #endif
1031 #else
1032 /* First segment address in the file (unless MH_SPLIT_SEGS set). */
1033 base = 0;
1034 #endif
1035
1036 unrelocate ("local", dstp->locreloff, dstp->nlocrel, base);
1037 unrelocate ("external", dstp->extreloff, dstp->nextrel, base);
1038
1039 if (dstp->nextrel > 0) {
1040 dstp->extreloff += delta;
1041 }
1042
1043 if (dstp->nlocrel > 0) {
1044 dstp->locreloff += delta;
1045 }
1046
1047 if (dstp->nindirectsyms > 0)
1048 dstp->indirectsymoff += delta;
1049
1050 printf ("Writing LC_DYSYMTAB command\n");
1051
1052 if (!unexec_write (curr_header_offset, lc, lc->cmdsize))
1053 unexec_error ("cannot write symtab command to header");
1054
1055 curr_header_offset += lc->cmdsize;
1056
1057 #if __ppc64__
1058 /* Check if the relocation base needs to be changed. */
1059 if (base == 0)
1060 {
1061 vm_address_t newbase = 0;
1062 int i;
1063
1064 for (i = 0; i < num_unexec_regions; i++)
1065 if (unexec_regions[i].range.address + unexec_regions[i].range.size
1066 > 0x100000000)
1067 {
1068 newbase = data_segment_scp->vmaddr;
1069 break;
1070 }
1071
1072 if (newbase)
1073 {
1074 rebase_reloc_address (dstp->locreloff, dstp->nlocrel, delta, newbase);
1075 rebase_reloc_address (dstp->extreloff, dstp->nextrel, delta, newbase);
1076 }
1077 }
1078 #endif
1079 }
1080
1081 /* Copy a LC_TWOLEVEL_HINTS load command from the input file to the output
1082 file, adjusting the file offset fields. */
1083 static void
1084 copy_twolevelhints (struct load_command *lc, long delta)
1085 {
1086 struct twolevel_hints_command *tlhp = (struct twolevel_hints_command *) lc;
1087
1088 if (tlhp->nhints > 0) {
1089 tlhp->offset += delta;
1090 }
1091
1092 printf ("Writing LC_TWOLEVEL_HINTS command\n");
1093
1094 if (!unexec_write (curr_header_offset, lc, lc->cmdsize))
1095 unexec_error ("cannot write two level hint command to header");
1096
1097 curr_header_offset += lc->cmdsize;
1098 }
1099
1100 #ifdef LC_DYLD_INFO
1101 /* Copy a LC_DYLD_INFO(_ONLY) load command from the input file to the output
1102 file, adjusting the file offset fields. */
1103 static void
1104 copy_dyld_info (struct load_command *lc, long delta)
1105 {
1106 struct dyld_info_command *dip = (struct dyld_info_command *) lc;
1107
1108 if (dip->rebase_off > 0)
1109 dip->rebase_off += delta;
1110 if (dip->bind_off > 0)
1111 dip->bind_off += delta;
1112 if (dip->weak_bind_off > 0)
1113 dip->weak_bind_off += delta;
1114 if (dip->lazy_bind_off > 0)
1115 dip->lazy_bind_off += delta;
1116 if (dip->export_off > 0)
1117 dip->export_off += delta;
1118
1119 printf ("Writing ");
1120 print_load_command_name (lc->cmd);
1121 printf (" command\n");
1122
1123 if (!unexec_write (curr_header_offset, lc, lc->cmdsize))
1124 unexec_error ("cannot write dyld info command to header");
1125
1126 curr_header_offset += lc->cmdsize;
1127 }
1128 #endif
1129
1130 /* Copy other kinds of load commands from the input file to the output
1131 file, ones that do not require adjustments of file offsets. */
1132 static void
1133 copy_other (struct load_command *lc)
1134 {
1135 printf ("Writing ");
1136 print_load_command_name (lc->cmd);
1137 printf (" command\n");
1138
1139 if (!unexec_write (curr_header_offset, lc, lc->cmdsize))
1140 unexec_error ("cannot write symtab command to header");
1141
1142 curr_header_offset += lc->cmdsize;
1143 }
1144
1145 /* Loop through all load commands and dump them. Then write the Mach
1146 header. */
1147 static void
1148 dump_it (void)
1149 {
1150 int i;
1151 long linkedit_delta = 0;
1152
1153 printf ("--- Load Commands written to Output File ---\n");
1154
1155 for (i = 0; i < nlc; i++)
1156 switch (lca[i]->cmd)
1157 {
1158 case LC_SEGMENT:
1159 {
1160 struct segment_command *scp = (struct segment_command *) lca[i];
1161 if (strncmp (scp->segname, SEG_DATA, 16) == 0)
1162 {
1163 /* save data segment file offset and segment_command for
1164 unrelocate */
1165 if (data_segment_old_fileoff)
1166 unexec_error ("cannot handle multiple DATA segments"
1167 " in input file");
1168 data_segment_old_fileoff = scp->fileoff;
1169 data_segment_scp = scp;
1170
1171 copy_data_segment (lca[i]);
1172 }
1173 else
1174 {
1175 if (strncmp (scp->segname, SEG_LINKEDIT, 16) == 0)
1176 {
1177 if (linkedit_delta)
1178 unexec_error ("cannot handle multiple LINKEDIT segments"
1179 " in input file");
1180 linkedit_delta = curr_file_offset - scp->fileoff;
1181 }
1182
1183 copy_segment (lca[i]);
1184 }
1185 }
1186 break;
1187 case LC_SYMTAB:
1188 copy_symtab (lca[i], linkedit_delta);
1189 break;
1190 case LC_DYSYMTAB:
1191 copy_dysymtab (lca[i], linkedit_delta);
1192 break;
1193 case LC_TWOLEVEL_HINTS:
1194 copy_twolevelhints (lca[i], linkedit_delta);
1195 break;
1196 #ifdef LC_DYLD_INFO
1197 case LC_DYLD_INFO:
1198 case LC_DYLD_INFO_ONLY:
1199 copy_dyld_info (lca[i], linkedit_delta);
1200 break;
1201 #endif
1202 default:
1203 copy_other (lca[i]);
1204 break;
1205 }
1206
1207 if (curr_header_offset > text_seg_lowest_offset)
1208 unexec_error ("not enough room for load commands for new __DATA segments");
1209
1210 printf ("%ld unused bytes follow Mach-O header\n",
1211 text_seg_lowest_offset - curr_header_offset);
1212
1213 mh.sizeofcmds = curr_header_offset - sizeof (struct mach_header);
1214 if (!unexec_write (0, &mh, sizeof (struct mach_header)))
1215 unexec_error ("cannot write final header contents");
1216 }
1217
1218 /* Take a snapshot of Emacs and make a Mach-O format executable file
1219 from it. The file names of the output and input files are outfile
1220 and infile, respectively. The three other parameters are
1221 ignored. */
1222 int
1223 unexec (const char *outfile, const char *infile)
1224 {
1225 if (in_dumped_exec)
1226 unexec_error ("Unexec from a dumped executable is not supported.");
1227
1228 pagesize = getpagesize ();
1229 infd = open (infile, O_RDONLY, 0);
1230 if (infd < 0)
1231 {
1232 unexec_error ("cannot open input file `%s'", infile);
1233 }
1234
1235 outfd = open (outfile, O_WRONLY | O_TRUNC | O_CREAT, 0755);
1236 if (outfd < 0)
1237 {
1238 close (infd);
1239 unexec_error ("cannot open output file `%s'", outfile);
1240 }
1241
1242 build_region_list ();
1243 read_load_commands ();
1244
1245 find_emacs_zone_regions ();
1246 unexec_regions_merge ();
1247
1248 in_dumped_exec = 1;
1249
1250 dump_it ();
1251
1252 close (outfd);
1253 return 0;
1254 }
1255
1256
1257 void
1258 unexec_init_emacs_zone (void)
1259 {
1260 emacs_zone = malloc_create_zone (0, 0);
1261 malloc_set_zone_name (emacs_zone, "EmacsZone");
1262 }
1263
1264 #ifndef MACOSX_MALLOC_MULT16
1265 #define MACOSX_MALLOC_MULT16 1
1266 #endif
1267
1268 typedef struct unexec_malloc_header {
1269 union {
1270 char c[8];
1271 size_t size;
1272 } u;
1273 } unexec_malloc_header_t;
1274
1275 #if MACOSX_MALLOC_MULT16
1276
1277 #define ptr_in_unexec_regions(p) ((((vm_address_t) (p)) & 8) != 0)
1278
1279 #else
1280
1281 int
1282 ptr_in_unexec_regions (void *ptr)
1283 {
1284 int i;
1285
1286 for (i = 0; i < num_unexec_regions; i++)
1287 if ((vm_address_t) ptr - unexec_regions[i].range.address
1288 < unexec_regions[i].range.size)
1289 return 1;
1290
1291 return 0;
1292 }
1293
1294 #endif
1295
1296 void *
1297 unexec_malloc (size_t size)
1298 {
1299 if (in_dumped_exec)
1300 {
1301 void *p;
1302
1303 p = malloc (size);
1304 #if MACOSX_MALLOC_MULT16
1305 assert (((vm_address_t) p % 16) == 0);
1306 #endif
1307 return p;
1308 }
1309 else
1310 {
1311 unexec_malloc_header_t *ptr;
1312
1313 ptr = (unexec_malloc_header_t *)
1314 malloc_zone_malloc (emacs_zone, size + sizeof (unexec_malloc_header_t));
1315 ptr->u.size = size;
1316 ptr++;
1317 #if MACOSX_MALLOC_MULT16
1318 assert (((vm_address_t) ptr % 16) == 8);
1319 #endif
1320 return (void *) ptr;
1321 }
1322 }
1323
1324 void *
1325 unexec_realloc (void *old_ptr, size_t new_size)
1326 {
1327 if (in_dumped_exec)
1328 {
1329 void *p;
1330
1331 if (ptr_in_unexec_regions (old_ptr))
1332 {
1333 size_t old_size = ((unexec_malloc_header_t *) old_ptr)[-1].u.size;
1334 size_t size = new_size > old_size ? old_size : new_size;
1335
1336 p = (size_t *) malloc (new_size);
1337 if (size)
1338 memcpy (p, old_ptr, size);
1339 }
1340 else
1341 {
1342 p = realloc (old_ptr, new_size);
1343 }
1344 #if MACOSX_MALLOC_MULT16
1345 assert (((vm_address_t) p % 16) == 0);
1346 #endif
1347 return p;
1348 }
1349 else
1350 {
1351 unexec_malloc_header_t *ptr;
1352
1353 ptr = (unexec_malloc_header_t *)
1354 malloc_zone_realloc (emacs_zone, (unexec_malloc_header_t *) old_ptr - 1,
1355 new_size + sizeof (unexec_malloc_header_t));
1356 ptr->u.size = new_size;
1357 ptr++;
1358 #if MACOSX_MALLOC_MULT16
1359 assert (((vm_address_t) ptr % 16) == 8);
1360 #endif
1361 return (void *) ptr;
1362 }
1363 }
1364
1365 void
1366 unexec_free (void *ptr)
1367 {
1368 if (ptr == NULL)
1369 return;
1370 if (in_dumped_exec)
1371 {
1372 if (!ptr_in_unexec_regions (ptr))
1373 free (ptr);
1374 }
1375 else
1376 malloc_zone_free (emacs_zone, (unexec_malloc_header_t *) ptr - 1);
1377 }
1378