unexmacosx.c 42.3 KB
Newer Older
1
/* Dump Emacs in Mach-O format for use on Mac OS X.
Paul Eggert's avatar
Paul Eggert committed
2
   Copyright (C) 2001-2016 Free Software Foundation, Inc.
3 4 5

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 9
the Free Software Foundation, either version 3 of the License, or (at
your option) any later version.
10 11 12 13 14 15 16

GNU Emacs is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

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/>.  */
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68

/* Contributed by Andrew Choi (akochoi@mac.com).  */

/* Documentation note.

   Consult the following documents/files for a description of the
   Mach-O format: the file loader.h, man pages for Mach-O and ld, old
   NEXTSTEP documents of the Mach-O format.  The tool otool dumps the
   mach header (-h option) and the load commands (-l option) in a
   Mach-O file.  The tool nm on Mac OS X displays the symbol table in
   a Mach-O file.  For examples of unexec for the Mach-O format, see
   the file unexnext.c in the GNU Emacs distribution, the file
   unexdyld.c in the Darwin port of GNU Emacs 20.7, and unexdyld.c in
   the Darwin port of XEmacs 21.1.  Also the Darwin Libc source
   contains the source code for malloc_freezedry and malloc_jumpstart.
   Read that to see what they do.  This file was written completely
   from scratch, making use of information from the above sources.  */

/* The Mac OS X implementation of unexec makes use of Darwin's `zone'
   memory allocator.  All calls to malloc, realloc, and free in Emacs
   are redirected to unexec_malloc, unexec_realloc, and unexec_free in
   this file.  When temacs is run, all memory requests are handled in
   the zone EmacsZone.  The Darwin memory allocator library calls
   maintain the data structures to manage this zone.  Dumping writes
   its contents to data segments of the executable file.  When emacs
   is run, the loader recreates the contents of the zone in memory.
   However since the initialization routine of the zone memory
   allocator is run again, this `zone' can no longer be used as a
   heap.  That is why emacs uses the ordinary malloc system call to
   allocate memory.  Also, when a block of memory needs to be
   reallocated and the new size is larger than the old one, a new
   block must be obtained by malloc and the old contents copied to
   it.  */

/* Peculiarity of the Mach-O files generated by ld in Mac OS X
   (possible causes of future bugs if changed).

   The file offset of the start of the __TEXT segment is zero.  Since
   the Mach header and load commands are located at the beginning of a
   Mach-O file, copying the contents of the __TEXT segment from the
   input file overwrites them in the output file.  Despite this,
   unexec works fine as written below because the segment load command
   for __TEXT appears, and is therefore processed, before all other
   load commands except the segment load command for __PAGEZERO, which
   remains unchanged.

   Although the file offset of the start of the __TEXT segment is
   zero, none of the sections it contains actually start there.  In
   fact, the earliest one starts a few hundred bytes beyond the end of
   the last load command.  The linker option -headerpad controls the
   minimum size of this padding.  Its setting can be changed in
69 70 71 72
   s/darwin.h.  A value of 0x690, e.g., leaves room for 30 additional
   load commands for the newly created __DATA segments (at 56 bytes
   each).  Unexec fails if there is not enough room for these new
   segments.
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87

   The __TEXT segment contains the sections __text, __cstring,
   __picsymbol_stub, and __const and the __DATA segment contains the
   sections __data, __la_symbol_ptr, __nl_symbol_ptr, __dyld, __bss,
   and __common.  The other segments do not contain any sections.
   These sections are copied from the input file to the output file,
   except for __data, __bss, and __common, which are dumped from
   memory.  The types of the sections __bss and __common are changed
   from S_ZEROFILL to S_REGULAR.  Note that the number of sections and
   their relative order in the input and output files remain
   unchanged.  Otherwise all n_sect fields in the nlist records in the
   symbol table (specified by the LC_SYMTAB load command) will have to
   be changed accordingly.
*/

88
/* Enable GNU extensions in gnulib replacement headers.  */
89 90
#define _GNU_SOURCE 1

91 92 93 94 95
/* config.h #define:s malloc/realloc/free and then includes stdlib.h.
   We want the undefined versions, but if config.h includes stdlib.h
   with the #define:s in place, the prototypes will be wrong and we get
   warnings.  To prevent that, include stdlib.h before config.h.  */

96
#include <stdlib.h>
97 98 99 100
#include <config.h>
#undef malloc
#undef realloc
#undef free
101 102

#include "unexec.h"
103
#include "lisp.h"
104

105
#include <errno.h>
106 107 108
#include <stdio.h>
#include <fcntl.h>
#include <stdarg.h>
109
#include <stdint.h>
110
#include <sys/types.h>
111 112
#include <unistd.h>
#include <mach/mach.h>
113
#include <mach/vm_map.h>
114
#include <mach-o/loader.h>
115
#include <mach-o/reloc.h>
116
#ifdef HAVE_MALLOC_MALLOC_H
117 118
#include <malloc/malloc.h>
#else
119
#include <objc/malloc.h>
120 121
#endif

YAMAMOTO Mitsuharu's avatar
YAMAMOTO Mitsuharu committed
122 123
#include <assert.h>

124 125
/* LC_DATA_IN_CODE is not defined in mach-o/loader.h on OS X 10.7.
   But it is used if we build with "Command Line Tools for Xcode 4.5
Paul Eggert's avatar
Paul Eggert committed
126
   (OS X Lion) - September 2012".  */
127 128 129 130
#ifndef LC_DATA_IN_CODE
#define LC_DATA_IN_CODE 0x29 /* table of non-instructions in __text */
#endif

131 132 133 134 135 136 137 138 139 140 141 142 143 144
#ifdef _LP64
#define mach_header			mach_header_64
#define segment_command			segment_command_64
#undef  VM_REGION_BASIC_INFO_COUNT
#define VM_REGION_BASIC_INFO_COUNT	VM_REGION_BASIC_INFO_COUNT_64
#undef  VM_REGION_BASIC_INFO
#define VM_REGION_BASIC_INFO		VM_REGION_BASIC_INFO_64
#undef  LC_SEGMENT
#define LC_SEGMENT			LC_SEGMENT_64
#define vm_region			vm_region_64
#define section				section_64
#undef MH_MAGIC
#define MH_MAGIC			MH_MAGIC_64
#endif
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166

#define VERBOSE 1

/* Size of buffer used to copy data from the input file to the output
   file in function unexec_copy.  */
#define UNEXEC_COPY_BUFSZ 1024

/* Regions with memory addresses above this value are assumed to be
   mapped to dynamically loaded libraries and will not be dumped.  */
#define VM_DATA_TOP (20 * 1024 * 1024)

/* Type of an element on the list of regions to be dumped.  */
struct region_t {
  vm_address_t address;
  vm_size_t size;
  vm_prot_t protection;
  vm_prot_t max_protection;

  struct region_t *next;
};

/* Head and tail of the list of regions to be dumped.  */
167 168
static struct region_t *region_list_head = 0;
static struct region_t *region_list_tail = 0;
169 170

/* Pointer to array of load commands.  */
171
static struct load_command **lca;
172 173

/* Number of load commands.  */
174
static int nlc;
175 176 177 178

/* The highest VM address of segments loaded by the input file.
   Regions with addresses beyond this are assumed to be allocated
   dynamically and thus require dumping.  */
179
static vm_address_t infile_lc_highest_addr = 0;
180 181 182 183 184 185

/* The lowest file offset used by the all sections in the __TEXT
   segments.  This leaves room at the beginning of the file to store
   the Mach-O header.  Check this value against header size to ensure
   the added load commands for the new __DATA segments did not
   overwrite any of the sections in the __TEXT segment.  */
186
static unsigned long text_seg_lowest_offset = 0x10000000;
187 188

/* Mach header.  */
189
static struct mach_header mh;
190 191

/* Offset at which the next load command should be written.  */
192
static unsigned long curr_header_offset = sizeof (struct mach_header);
193

194 195 196 197 198
/* Offset at which the next segment should be written.  */
static unsigned long curr_file_offset = 0;

static unsigned long pagesize;
#define ROUNDUP_TO_PAGE_BOUNDARY(x)	(((x) + pagesize - 1) & ~(pagesize - 1))
199

200
static int infd, outfd;
201

202
static int in_dumped_exec = 0;
203

204
static malloc_zone_t *emacs_zone;
205

206
/* file offset of input file's data segment */
207
static off_t data_segment_old_fileoff = 0;
208

209
static struct segment_command *data_segment_scp;
210

211
/* Read N bytes from infd into memory starting at address DEST.
212 213 214 215 216 217 218
   Return true if successful, false otherwise.  */
static int
unexec_read (void *dest, size_t n)
{
  return n == read (infd, dest, n);
}

219 220 221
/* Write COUNT bytes from memory starting at address SRC to outfd
   starting at offset DEST.  Return true if successful, false
   otherwise.  */
222 223 224
static int
unexec_write (off_t dest, const void *src, size_t count)
{
225 226 227 228
  task_t task = mach_task_self();
  if (task == MACH_PORT_NULL || task == MACH_PORT_DEAD)
    return false;

229 230 231
  if (lseek (outfd, dest, SEEK_SET) != dest)
    return 0;

232 233 234 235 236 237 238 239 240 241 242 243 244 245
  /* We use the Mach virtual memory API to read our process memory
     because using src directly would be undefined behavior and fails
     under Address Sanitizer.  */
  bool success = false;
  vm_offset_t data;
  mach_msg_type_number_t data_count;
  if (vm_read (task, (uintptr_t) src, count, &data, &data_count)
      == KERN_SUCCESS)
    {
      success =
        write (outfd, (const void *) (uintptr_t) data, data_count) == count;
      vm_deallocate (task, data, data_count);
    }
  return success;
246 247
}

248 249 250 251 252 253 254 255
/* Write COUNT bytes of zeros to outfd starting at offset DEST.
   Return true if successful, false otherwise.  */
static int
unexec_write_zero (off_t dest, size_t count)
{
  char buf[UNEXEC_COPY_BUFSZ];
  ssize_t bytes;

256
  memset (buf, 0, UNEXEC_COPY_BUFSZ);
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
  if (lseek (outfd, dest, SEEK_SET) != dest)
    return 0;

  while (count > 0)
    {
      bytes = count > UNEXEC_COPY_BUFSZ ? UNEXEC_COPY_BUFSZ : count;
      if (write (outfd, buf, bytes) != bytes)
	return 0;
      count -= bytes;
    }

  return 1;
}

/* Copy COUNT bytes from starting offset SRC in infd to starting
   offset DEST in outfd.  Return true if successful, false
   otherwise.  */
274 275 276 277
static int
unexec_copy (off_t dest, off_t src, ssize_t count)
{
  ssize_t bytes_read;
278
  ssize_t bytes_to_read;
279 280 281 282 283 284 285 286 287 288 289

  char buf[UNEXEC_COPY_BUFSZ];

  if (lseek (infd, src, SEEK_SET) != src)
    return 0;

  if (lseek (outfd, dest, SEEK_SET) != dest)
    return 0;

  while (count > 0)
    {
290 291
      bytes_to_read = count > UNEXEC_COPY_BUFSZ ? UNEXEC_COPY_BUFSZ : count;
      bytes_read = read (infd, buf, bytes_to_read);
292 293 294 295 296 297 298 299 300 301 302 303
      if (bytes_read <= 0)
	return 0;
      if (write (outfd, buf, bytes_read) != bytes_read)
	return 0;
      count -= bytes_read;
    }

  return 1;
}

/* Debugging and informational messages routines.  */

304
static _Noreturn void
305
unexec_error (const char *format, ...)
306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
{
  va_list ap;

  va_start (ap, format);
  fprintf (stderr, "unexec: ");
  vfprintf (stderr, format, ap);
  fprintf (stderr, "\n");
  va_end (ap);
  exit (1);
}

static void
print_prot (vm_prot_t prot)
{
  if (prot == VM_PROT_NONE)
    printf ("none");
  else
    {
      putchar (prot & VM_PROT_READ ? 'r' : ' ');
      putchar (prot & VM_PROT_WRITE ? 'w' : ' ');
      putchar (prot & VM_PROT_EXECUTE ? 'x' : ' ');
      putchar (' ');
    }
}

static void
print_region (vm_address_t address, vm_size_t size, vm_prot_t prot,
	      vm_prot_t max_prot)
{
335
  printf ("%#10lx %#8lx ", (long) address, (long) size);
336 337 338 339 340 341 342
  print_prot (prot);
  putchar (' ');
  print_prot (max_prot);
  putchar ('\n');
}

static void
343
print_region_list (void)
344 345 346 347 348 349 350 351 352
{
  struct region_t *r;

  printf ("   address     size prot maxp\n");

  for (r = region_list_head; r; r = r->next)
    print_region (r->address, r->size, r->protection, r->max_protection);
}

353
static void
354
print_regions (void)
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
{
  task_t target_task = mach_task_self ();
  vm_address_t address = (vm_address_t) 0;
  vm_size_t size;
  struct vm_region_basic_info info;
  mach_msg_type_number_t info_count = VM_REGION_BASIC_INFO_COUNT;
  mach_port_t object_name;

  printf ("   address     size prot maxp\n");

  while (vm_region (target_task, &address, &size, VM_REGION_BASIC_INFO,
		    (vm_region_info_t) &info, &info_count, &object_name)
	 == KERN_SUCCESS && info_count == VM_REGION_BASIC_INFO_COUNT)
    {
      print_region (address, size, info.protection, info.max_protection);

      if (object_name != MACH_PORT_NULL)
	mach_port_deallocate (target_task, object_name);
373

374 375 376 377 378 379 380 381 382 383
      address += size;
    }
}

/* Build the list of regions that need to be dumped.  Regions with
   addresses above VM_DATA_TOP are omitted.  Adjacent regions with
   identical protection are merged.  Note that non-writable regions
   cannot be omitted because they some regions created at run time are
   read-only.  */
static void
384
build_region_list (void)
385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424
{
  task_t target_task = mach_task_self ();
  vm_address_t address = (vm_address_t) 0;
  vm_size_t size;
  struct vm_region_basic_info info;
  mach_msg_type_number_t info_count = VM_REGION_BASIC_INFO_COUNT;
  mach_port_t object_name;
  struct region_t *r;

#if VERBOSE
  printf ("--- List of All Regions ---\n");
  printf ("   address     size prot maxp\n");
#endif

  while (vm_region (target_task, &address, &size, VM_REGION_BASIC_INFO,
		    (vm_region_info_t) &info, &info_count, &object_name)
	 == KERN_SUCCESS && info_count == VM_REGION_BASIC_INFO_COUNT)
    {
      /* Done when we reach addresses of shared libraries, which are
	 loaded in high memory.  */
      if (address >= VM_DATA_TOP)
	break;

#if VERBOSE
      print_region (address, size, info.protection, info.max_protection);
#endif

      /* If a region immediately follows the previous one (the one
	 most recently added to the list) and has identical
	 protection, merge it with the latter.  Otherwise create a
	 new list element for it.  */
      if (region_list_tail
	  && info.protection == region_list_tail->protection
	  && info.max_protection == region_list_tail->max_protection
	  && region_list_tail->address + region_list_tail->size == address)
	{
	  region_list_tail->size += size;
	}
      else
	{
425
	  r = malloc (sizeof *r);
426

427 428
	  if (!r)
	    unexec_error ("cannot allocate region structure");
429

430 431 432 433
	  r->address = address;
	  r->size = size;
	  r->protection = info.protection;
	  r->max_protection = info.max_protection;
434

435 436 437 438 439 440 441 442 443 444 445
	  r->next = 0;
	  if (region_list_head == 0)
	    {
	      region_list_head = r;
	      region_list_tail = r;
	    }
	  else
	    {
	      region_list_tail->next = r;
	      region_list_tail = r;
	    }
446

447 448 449 450 451
	  /* Deallocate (unused) object name returned by
	     vm_region.  */
	  if (object_name != MACH_PORT_NULL)
	    mach_port_deallocate (target_task, object_name);
	}
452

453 454 455 456 457 458 459 460
      address += size;
    }

  printf ("--- List of Regions to be Dumped ---\n");
  print_region_list ();
}


461
#define MAX_UNEXEC_REGIONS 400
462

463 464 465 466 467 468
static int num_unexec_regions;
typedef struct {
  vm_range_t range;
  vm_size_t filesize;
} unexec_region_info;
static unexec_region_info unexec_regions[MAX_UNEXEC_REGIONS];
469 470 471 472 473

static void
unexec_regions_recorder (task_t task, void *rr, unsigned type,
			 vm_range_t *ranges, unsigned num)
{
474 475 476
  vm_address_t p;
  vm_size_t filesize;

477 478
  while (num && num_unexec_regions < MAX_UNEXEC_REGIONS)
    {
479
      /* Subtract the size of trailing null bytes from filesize.  It
480
	 can be smaller than vmsize in segment commands.  In such a
481 482 483 484 485
	 case, trailing bytes are initialized with zeros.  */
      for (p = ranges->address + ranges->size; p > ranges->address; p--)
      	if (*(((char *) p)-1))
      	  break;
      filesize = p - ranges->address;
486 487 488 489 490

      unexec_regions[num_unexec_regions].filesize = filesize;
      unexec_regions[num_unexec_regions++].range = *ranges;
      printf ("%#10lx (sz: %#8lx/%#8lx)\n", (long) (ranges->address),
	      (long) filesize, (long) (ranges->size));
491 492 493 494 495 496 497 498 499 500 501
      ranges++; num--;
    }
}

static kern_return_t
unexec_reader (task_t task, vm_address_t address, vm_size_t size, void **ptr)
{
  *ptr = (void *) address;
  return KERN_SUCCESS;
}

502
static void
503
find_emacs_zone_regions (void)
504 505 506
{
  num_unexec_regions = 0;

Juanma Barranquero's avatar
Juanma Barranquero committed
507
  emacs_zone->introspect->enumerator (mach_task_self (), 0,
508 509 510 511 512
				      MALLOC_PTR_REGION_RANGE_TYPE
				      | MALLOC_ADMIN_REGION_RANGE_TYPE,
				      (vm_address_t) emacs_zone,
				      unexec_reader,
				      unexec_regions_recorder);
513 514 515

  if (num_unexec_regions == MAX_UNEXEC_REGIONS)
    unexec_error ("find_emacs_zone_regions: too many regions");
516 517
}

518 519 520
static int
unexec_regions_sort_compare (const void *a, const void *b)
{
521 522
  vm_address_t aa = ((unexec_region_info *) a)->range.address;
  vm_address_t bb = ((unexec_region_info *) b)->range.address;
523 524 525 526 527 528 529 530 531 532

  if (aa < bb)
    return -1;
  else if (aa > bb)
    return 1;
  else
    return 0;
}

static void
533
unexec_regions_merge (void)
534 535
{
  int i, n;
536
  unexec_region_info r;
537
  vm_size_t padsize;
538 539 540 541 542

  qsort (unexec_regions, num_unexec_regions, sizeof (unexec_regions[0]),
	 &unexec_regions_sort_compare);
  n = 0;
  r = unexec_regions[0];
543 544 545 546 547 548 549
  padsize = r.range.address & (pagesize - 1);
  if (padsize)
    {
      r.range.address -= padsize;
      r.range.size += padsize;
      r.filesize += padsize;
    }
550 551
  for (i = 1; i < num_unexec_regions; i++)
    {
552 553
      if (r.range.address + r.range.size == unexec_regions[i].range.address
	  && r.range.size - r.filesize < 2 * pagesize)
554
	{
555 556
	  r.filesize = r.range.size + unexec_regions[i].filesize;
	  r.range.size += unexec_regions[i].range.size;
557 558 559 560 561
	}
      else
	{
	  unexec_regions[n++] = r;
	  r = unexec_regions[i];
562 563 564 565 566 567 568 569 570 571 572
	  padsize = r.range.address & (pagesize - 1);
	  if (padsize)
	    {
	      if ((unexec_regions[n-1].range.address
		   + unexec_regions[n-1].range.size) == r.range.address)
		unexec_regions[n-1].range.size -= padsize;

	      r.range.address -= padsize;
	      r.range.size += padsize;
	      r.filesize += padsize;
	    }
573 574 575 576 577 578
	}
    }
  unexec_regions[n++] = r;
  num_unexec_regions = n;
}

579 580 581 582 583 584 585 586 587

/* More informational messages routines.  */

static void
print_load_command_name (int lc)
{
  switch (lc)
    {
    case LC_SEGMENT:
588
#ifndef _LP64
589
      printf ("LC_SEGMENT       ");
590 591 592
#else
      printf ("LC_SEGMENT_64    ");
#endif
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
      break;
    case LC_LOAD_DYLINKER:
      printf ("LC_LOAD_DYLINKER ");
      break;
    case LC_LOAD_DYLIB:
      printf ("LC_LOAD_DYLIB    ");
      break;
    case LC_SYMTAB:
      printf ("LC_SYMTAB        ");
      break;
    case LC_DYSYMTAB:
      printf ("LC_DYSYMTAB      ");
      break;
    case LC_UNIXTHREAD:
      printf ("LC_UNIXTHREAD    ");
      break;
    case LC_PREBOUND_DYLIB:
      printf ("LC_PREBOUND_DYLIB");
      break;
    case LC_TWOLEVEL_HINTS:
      printf ("LC_TWOLEVEL_HINTS");
      break;
615 616 617 618
#ifdef LC_UUID
    case LC_UUID:
      printf ("LC_UUID          ");
      break;
619 620 621 622 623 624 625 626
#endif
#ifdef LC_DYLD_INFO
    case LC_DYLD_INFO:
      printf ("LC_DYLD_INFO     ");
      break;
    case LC_DYLD_INFO_ONLY:
      printf ("LC_DYLD_INFO_ONLY");
      break;
627 628 629 630 631 632 633 634 635 636
#endif
#ifdef LC_VERSION_MIN_MACOSX
    case LC_VERSION_MIN_MACOSX:
      printf ("LC_VERSION_MIN_MACOSX");
      break;
#endif
#ifdef LC_FUNCTION_STARTS
    case LC_FUNCTION_STARTS:
      printf ("LC_FUNCTION_STARTS");
      break;
637 638 639 640 641 642
#endif
#ifdef LC_MAIN
    case LC_MAIN:
      printf ("LC_MAIN          ");
      break;
#endif
643 644
#ifdef LC_DATA_IN_CODE
    case LC_DATA_IN_CODE:
YAMAMOTO Mitsuharu's avatar
YAMAMOTO Mitsuharu committed
645
      printf ("LC_DATA_IN_CODE  ");
646 647
      break;
#endif
648 649 650 651 652 653 654 655 656
#ifdef LC_SOURCE_VERSION
    case LC_SOURCE_VERSION:
      printf ("LC_SOURCE_VERSION");
      break;
#endif
#ifdef LC_DYLIB_CODE_SIGN_DRS
    case LC_DYLIB_CODE_SIGN_DRS:
      printf ("LC_DYLIB_CODE_SIGN_DRS");
      break;
657
#endif
658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
    default:
      printf ("unknown          ");
    }
}

static void
print_load_command (struct load_command *lc)
{
  print_load_command_name (lc->cmd);
  printf ("%8d", lc->cmdsize);

  if (lc->cmd == LC_SEGMENT)
    {
      struct segment_command *scp;
      struct section *sectp;
      int j;

      scp = (struct segment_command *) lc;
676 677
      printf (" %-16.16s %#10lx %#8lx\n",
	      scp->segname, (long) (scp->vmaddr), (long) (scp->vmsize));
678 679 680 681

      sectp = (struct section *) (scp + 1);
      for (j = 0; j < scp->nsects; j++)
	{
682 683
	  printf ("                           %-16.16s %#10lx %#8lx\n",
		  sectp->sectname, (long) (sectp->addr), (long) (sectp->size));
684 685 686 687 688 689 690 691 692 693 694
	  sectp++;
	}
    }
  else
    printf ("\n");
}

/* Read header and load commands from input file.  Store the latter in
   the global array lca.  Store the total number of load commands in
   global variable nlc.  */
static void
695
read_load_commands (void)
696
{
697
  int i;
698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719

  if (!unexec_read (&mh, sizeof (struct mach_header)))
    unexec_error ("cannot read mach-o header");

  if (mh.magic != MH_MAGIC)
    unexec_error ("input file not in Mach-O format");

  if (mh.filetype != MH_EXECUTE)
    unexec_error ("input Mach-O file is not an executable object file");

#if VERBOSE
  printf ("--- Header Information ---\n");
  printf ("Magic = 0x%08x\n", mh.magic);
  printf ("CPUType = %d\n", mh.cputype);
  printf ("CPUSubType = %d\n", mh.cpusubtype);
  printf ("FileType = 0x%x\n", mh.filetype);
  printf ("NCmds = %d\n", mh.ncmds);
  printf ("SizeOfCmds = %d\n", mh.sizeofcmds);
  printf ("Flags = 0x%08x\n", mh.flags);
#endif

  nlc = mh.ncmds;
720
  lca = malloc (nlc * sizeof *lca);
721

722 723 724 725 726 727 728
  for (i = 0; i < nlc; i++)
    {
      struct load_command lc;
      /* Load commands are variable-size: so read the command type and
	 size first and then read the rest.  */
      if (!unexec_read (&lc, sizeof (struct load_command)))
        unexec_error ("cannot read load command");
729
      lca[i] = malloc (lc.cmdsize);
730 731 732 733 734 735
      memcpy (lca[i], &lc, sizeof (struct load_command));
      if (!unexec_read (lca[i] + 1, lc.cmdsize - sizeof (struct load_command)))
        unexec_error ("cannot read content of load command");
      if (lc.cmd == LC_SEGMENT)
	{
	  struct segment_command *scp = (struct segment_command *) lca[i];
736

737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
	  if (scp->vmaddr + scp->vmsize > infile_lc_highest_addr)
	    infile_lc_highest_addr = scp->vmaddr + scp->vmsize;

	  if (strncmp (scp->segname, SEG_TEXT, 16) == 0)
	    {
	      struct section *sectp = (struct section *) (scp + 1);
	      int j;

	      for (j = 0; j < scp->nsects; j++)
		if (sectp->offset < text_seg_lowest_offset)
		  text_seg_lowest_offset = sectp->offset;
	    }
	}
    }

752 753
  printf ("Highest address of load commands in input file: %#8lx\n",
	  (unsigned long)infile_lc_highest_addr);
754

755
  printf ("Lowest offset of all sections in __TEXT segment: %#8lx\n",
756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778
	  text_seg_lowest_offset);

  printf ("--- List of Load Commands in Input File ---\n");
  printf ("# cmd              cmdsize name                address     size\n");

  for (i = 0; i < nlc; i++)
    {
      printf ("%1d ", i);
      print_load_command (lca[i]);
    }
}

/* Copy a LC_SEGMENT load command other than the __DATA segment from
   the input file to the output file, adjusting the file offset of the
   segment and the file offsets of sections contained in it.  */
static void
copy_segment (struct load_command *lc)
{
  struct segment_command *scp = (struct segment_command *) lc;
  unsigned long old_fileoff = scp->fileoff;
  struct section *sectp;
  int j;

779
  scp->fileoff = curr_file_offset;
780 781 782 783

  sectp = (struct section *) (scp + 1);
  for (j = 0; j < scp->nsects; j++)
    {
784
      sectp->offset += curr_file_offset - old_fileoff;
785 786 787
      sectp++;
    }

788 789 790
  printf ("Writing segment %-16.16s @ %#8lx (%#8lx/%#8lx @ %#10lx)\n",
	  scp->segname, (long) (scp->fileoff), (long) (scp->filesize),
	  (long) (scp->vmsize), (long) (scp->vmaddr));
791 792 793

  if (!unexec_copy (scp->fileoff, old_fileoff, scp->filesize))
    unexec_error ("cannot copy segment from input to output file");
794 795
  curr_file_offset += ROUNDUP_TO_PAGE_BOUNDARY (scp->filesize);

796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819
  if (!unexec_write (curr_header_offset, lc, lc->cmdsize))
    unexec_error ("cannot write load command to header");

  curr_header_offset += lc->cmdsize;
}

/* Copy a LC_SEGMENT load command for the __DATA segment in the input
   file to the output file.  We assume that only one such segment load
   command exists in the input file and it contains the sections
   __data, __bss, __common, __la_symbol_ptr, __nl_symbol_ptr, and
   __dyld.  The first three of these should be dumped from memory and
   the rest should be copied from the input file.  Note that the
   sections __bss and __common contain no data in the input file
   because their flag fields have the value S_ZEROFILL.  Dumping these
   from memory makes it necessary to adjust file offset fields in
   subsequently dumped load commands.  Then, create new __DATA segment
   load commands for regions on the region list other than the one
   corresponding to the __DATA segment in the input file.  */
static void
copy_data_segment (struct load_command *lc)
{
  struct segment_command *scp = (struct segment_command *) lc;
  struct section *sectp;
  int j;
820 821 822 823 824 825 826 827
  unsigned long header_offset, old_file_offset;

  /* The new filesize of the segment is set to its vmsize because data
     blocks for segments must start at region boundaries.  Note that
     this may leave unused locations at the end of the segment data
     block because the total of the sizes of all sections in the
     segment is generally smaller than vmsize.  */
  scp->filesize = scp->vmsize;
828

829 830 831
  printf ("Writing segment %-16.16s @ %#8lx (%#8lx/%#8lx @ %#10lx)\n",
	  scp->segname, curr_file_offset, (long)(scp->filesize),
	  (long)(scp->vmsize), (long) (scp->vmaddr));
832 833 834 835 836 837 838 839 840

  /* Offsets in the output file for writing the next section structure
     and segment data block, respectively.  */
  header_offset = curr_header_offset + sizeof (struct segment_command);

  sectp = (struct section *) (scp + 1);
  for (j = 0; j < scp->nsects; j++)
    {
      old_file_offset = sectp->offset;
841
      sectp->offset = sectp->addr - scp->vmaddr + curr_file_offset;
842 843 844 845 846 847 848
      /* The __data section is dumped from memory.  The __bss and
	 __common sections are also dumped from memory but their flag
	 fields require changing (from S_ZEROFILL to S_REGULAR).  The
	 other three kinds of sections are just copied from the input
	 file.  */
      if (strncmp (sectp->sectname, SECT_DATA, 16) == 0)
	{
849 850 851 852 853 854 855 856 857 858 859 860 861
	  unsigned long my_size;

	  /* The __data section is basically dumped from memory.  But
	     initialized data in statically linked libraries are
	     copied from the input file.  In particular,
	     add_image_hook.names and add_image_hook.pointers stored
	     by libarclite_macosx.a, are restored so that they will be
	     reinitialized when the dumped binary is executed.  */
	  my_size = (unsigned long)my_edata - sectp->addr;
	  if (!(sectp->addr <= (unsigned long)my_edata
		&& my_size <= sectp->size))
	    unexec_error ("my_edata is not in section %s", SECT_DATA);
	  if (!unexec_write (sectp->offset, (void *) sectp->addr, my_size))
862
	    unexec_error ("cannot write section %s", SECT_DATA);
863 864 865
	  if (!unexec_copy (sectp->offset + my_size, old_file_offset + my_size,
			    sectp->size - my_size))
	    unexec_error ("cannot copy section %s", SECT_DATA);
866 867 868
	  if (!unexec_write (header_offset, sectp, sizeof (struct section)))
	    unexec_error ("cannot write section %s's header", SECT_DATA);
	}
869
      else if (strncmp (sectp->sectname, SECT_COMMON, 16) == 0)
870 871 872
	{
	  sectp->flags = S_REGULAR;
	  if (!unexec_write (sectp->offset, (void *) sectp->addr, sectp->size))
873
	    unexec_error ("cannot write section %.16s", sectp->sectname);
874
	  if (!unexec_write (header_offset, sectp, sizeof (struct section)))
875
	    unexec_error ("cannot write section %.16s's header", sectp->sectname);
876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
	}
      else if (strncmp (sectp->sectname, SECT_BSS, 16) == 0)
	{
	  unsigned long my_size;

	  sectp->flags = S_REGULAR;

	  /* Clear uninitialized local variables in statically linked
	     libraries.  In particular, function pointers stored by
	     libSystemStub.a, which is introduced in Mac OS X 10.4 for
	     binary compatibility with respect to long double, are
	     cleared so that they will be reinitialized when the
	     dumped binary is executed on other versions of OS.  */
	  my_size = (unsigned long)my_endbss_static - sectp->addr;
	  if (!(sectp->addr <= (unsigned long)my_endbss_static
		&& my_size <= sectp->size))
892
	    unexec_error ("my_endbss_static is not in section %.16s",
893 894
			  sectp->sectname);
	  if (!unexec_write (sectp->offset, (void *) sectp->addr, my_size))
895
	    unexec_error ("cannot write section %.16s", sectp->sectname);
896 897
	  if (!unexec_write_zero (sectp->offset + my_size,
				  sectp->size - my_size))
898
	    unexec_error ("cannot write section %.16s", sectp->sectname);
899
	  if (!unexec_write (header_offset, sectp, sizeof (struct section)))
900
	    unexec_error ("cannot write section %.16s's header", sectp->sectname);
901
	}
902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
      else if (strncmp (sectp->sectname, "__bss", 5) == 0
	       || strncmp (sectp->sectname, "__pu_bss", 8) == 0)
	{
	  sectp->flags = S_REGULAR;

	  /* These sections are produced by GCC 4.6+.

	     FIXME: We possibly ought to clear uninitialized local
	     variables in statically linked libraries like for
	     SECT_BSS (__bss) above, but setting up the markers we
	     need in lastfile.c would be rather messy. See
	     darwin_output_aligned_bss () in gcc/config/darwin.c for
	     the root of the problem, keeping in mind that the
	     sections are numbered by their alignment in GCC 4.6, but
	     by log2(alignment) in GCC 4.7. */

	  if (!unexec_write (sectp->offset, (void *) sectp->addr, sectp->size))
	    unexec_error ("cannot copy section %.16s", sectp->sectname);
	  if (!unexec_write (header_offset, sectp, sizeof (struct section)))
	    unexec_error ("cannot write section %.16s's header", sectp->sectname);
	}
923 924
      else if (strncmp (sectp->sectname, "__la_symbol_ptr", 16) == 0
	       || strncmp (sectp->sectname, "__nl_symbol_ptr", 16) == 0
925
	       || strncmp (sectp->sectname, "__got", 16) == 0
926
	       || strncmp (sectp->sectname, "__la_sym_ptr2", 16) == 0
927
	       || strncmp (sectp->sectname, "__dyld", 16) == 0
928
	       || strncmp (sectp->sectname, "__const", 16) == 0
929 930
	       || strncmp (sectp->sectname, "__cfstring", 16) == 0
	       || strncmp (sectp->sectname, "__gcc_except_tab", 16) == 0
931
	       || strncmp (sectp->sectname, "__program_vars", 16) == 0
932 933
	       || strncmp (sectp->sectname, "__mod_init_func", 16) == 0
	       || strncmp (sectp->sectname, "__mod_term_func", 16) == 0
934
	       || strncmp (sectp->sectname, "__static_data", 16) == 0
935
	       || strncmp (sectp->sectname, "__objc_", 7) == 0)
936 937
	{
	  if (!unexec_copy (sectp->offset, old_file_offset, sectp->size))
938
	    unexec_error ("cannot copy section %.16s", sectp->sectname);
939
	  if (!unexec_write (header_offset, sectp, sizeof (struct section)))
940
	    unexec_error ("cannot write section %.16s's header", sectp->sectname);
941 942
	}
      else
943 944
	unexec_error ("unrecognized section %.16s in __DATA segment",
		      sectp->sectname);
945

946 947 948
      printf ("        section %-16.16s at %#8lx - %#8lx (sz: %#8lx)\n",
	      sectp->sectname, (long) (sectp->offset),
	      (long) (sectp->offset + sectp->size), (long) (sectp->size));
949 950 951 952 953

      header_offset += sizeof (struct section);
      sectp++;
    }

954 955
  curr_file_offset += ROUNDUP_TO_PAGE_BOUNDARY (scp->filesize);

956 957 958 959 960 961 962
  if (!unexec_write (curr_header_offset, scp, sizeof (struct segment_command)))
    unexec_error ("cannot write header of __DATA segment");
  curr_header_offset += lc->cmdsize;

  /* Create new __DATA segment load commands for regions on the region
     list that do not corresponding to any segment load commands in
     the input file.
963
  */
964 965 966
  for (j = 0; j < num_unexec_regions; j++)
    {
      struct segment_command sc;
967

968 969 970
      sc.cmd = LC_SEGMENT;
      sc.cmdsize = sizeof (struct segment_command);
      strncpy (sc.segname, SEG_DATA, 16);
971 972
      sc.vmaddr = unexec_regions[j].range.address;
      sc.vmsize = unexec_regions[j].range.size;
973
      sc.fileoff = curr_file_offset;
974
      sc.filesize = unexec_regions[j].filesize;
975 976 977 978
      sc.maxprot = VM_PROT_READ | VM_PROT_WRITE;
      sc.initprot = VM_PROT_READ | VM_PROT_WRITE;
      sc.nsects = 0;
      sc.flags = 0;
979

980 981 982
      printf ("Writing segment %-16.16s @ %#8lx (%#8lx/%#8lx @ %#10lx)\n",
	      sc.segname, (long) (sc.fileoff), (long) (sc.filesize),
	      (long) (sc.vmsize), (long) (sc.vmaddr));
983

984
      if (!unexec_write (sc.fileoff, (void *) sc.vmaddr, sc.filesize))
985
	unexec_error ("cannot write new __DATA segment");
986
      curr_file_offset += ROUNDUP_TO_PAGE_BOUNDARY (sc.filesize);
987

988 989 990 991 992 993 994 995 996 997
      if (!unexec_write (curr_header_offset, &sc, sc.cmdsize))
	unexec_error ("cannot write new __DATA segment's header");
      curr_header_offset += sc.cmdsize;
      mh.ncmds++;
    }
}

/* Copy a LC_SYMTAB load command from the input file to the output
   file, adjusting the file offset fields.  */
static void
998
copy_symtab (struct load_command *lc, long delta)
999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012
{
  struct symtab_command *stp = (struct symtab_command *) lc;

  stp->symoff += delta;
  stp->stroff += delta;

  printf ("Writing LC_SYMTAB command\n");

  if (!unexec_write (curr_header_offset, lc, lc->cmdsize))
    unexec_error ("cannot write symtab command to header");

  curr_header_offset += lc->cmdsize;
}

1013 1014
/* Fix up relocation entries. */
static void
1015
unrelocate (const char *name, off_t reloff, int nrel, vm_address_t base)
1016 1017 1018 1019 1020
{
  int i, unreloc_count;
  struct relocation_info reloc_info;
  struct scattered_relocation_info *sc_reloc_info
    = (struct scattered_relocation_info *) &reloc_info;
1021
  vm_address_t location;
1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034

  for (unreloc_count = 0, i = 0; i < nrel; i++)
    {
      if (lseek (infd, reloff, L_SET) != reloff)
	unexec_error ("unrelocate: %s:%d cannot seek to reloc_info", name, i);
      if (!unexec_read (&reloc_info, sizeof (reloc_info)))
	unexec_error ("unrelocate: %s:%d cannot read reloc_info", name, i);
      reloff += sizeof (reloc_info);

      if (sc_reloc_info->r_scattered == 0)
	switch (reloc_info.r_type)
	  {
	  case GENERIC_RELOC_VANILLA:
1035
	    location = base + reloc_info.r_address;
1036 1037 1038
	    if (location >= data_segment_scp->vmaddr
		&& location < (data_segment_scp->vmaddr
			       + data_segment_scp->vmsize))
1039 1040
	      {
		off_t src_off = data_segment_old_fileoff
1041
		  + (location - data_segment_scp->vmaddr);
1042
		off_t dst_off = data_segment_scp->fileoff
1043
		  + (location - data_segment_scp->vmaddr);
1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055

		if (!unexec_copy (dst_off, src_off, 1 << reloc_info.r_length))
		  unexec_error ("unrelocate: %s:%d cannot copy original value",
				name, i);
		unreloc_count++;
	      }
	    break;
	  default:
	    unexec_error ("unrelocate: %s:%d cannot handle type = %d",
			  name, i, reloc_info.r_type);
	  }
      else
1056 1057
        unexec_error ("unrelocate: %s:%d cannot handle scattered type = %d",
                      name, i, sc_reloc_info->r_type);
1058 1059 1060 1061 1062 1063 1064
    }

  if (nrel > 0)
    printf ("Fixed up %d/%d %s relocation entries in data segment.\n",
	    unreloc_count, nrel, name);
}

1065 1066 1067
/* Copy a LC_DYSYMTAB load command from the input file to the output
   file, adjusting the file offset fields.  */
static void
1068
copy_dysymtab (struct load_command *lc, long delta)
1069 1070
{
  struct dysymtab_command *dstp = (struct dysymtab_command *) lc;
1071
  vm_address_t base;
1072

1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
#ifdef _LP64
  /* First writable segment address.  */
  base = data_segment_scp->vmaddr;
#else
  /* First segment address in the file (unless MH_SPLIT_SEGS set). */
  base = 0;
#endif

  unrelocate ("local", dstp->locreloff, dstp->nlocrel, base);
  unrelocate ("external", dstp->extreloff, dstp->nextrel, base);
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102

  if (dstp->nextrel > 0) {
    dstp->extreloff += delta;
  }

  if (dstp->nlocrel > 0) {
    dstp->locreloff += delta;
  }

  if (dstp->nindirectsyms > 0)
    dstp->indirectsymoff += delta;

  printf ("Writing LC_DYSYMTAB command\n");

  if (!unexec_write (curr_header_offset, lc, lc->cmdsize))
    unexec_error ("cannot write symtab command to header");

  curr_header_offset += lc->cmdsize;
}

1103 1104 1105
/* Copy a LC_TWOLEVEL_HINTS load command from the input file to the output
   file, adjusting the file offset fields.  */
static void
1106
copy_twolevelhints (struct load_command *lc, long delta)
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
{
  struct twolevel_hints_command *tlhp = (struct twolevel_hints_command *) lc;

  if (tlhp->nhints > 0) {
    tlhp->offset += delta;
  }

  printf ("Writing LC_TWOLEVEL_HINTS command\n");

  if (!unexec_write (curr_header_offset, lc, lc->cmdsize))
    unexec_error ("cannot write two level hint command to header");

  curr_header_offset += lc->cmdsize;
}

1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
#ifdef LC_DYLD_INFO
/* Copy a LC_DYLD_INFO(_ONLY) load command from the input file to the output
   file, adjusting the file offset fields.  */
static void
copy_dyld_info (struct load_command *lc, long delta)
{
  struct dyld_info_command *dip = (struct dyld_info_command *) lc;

  if (dip->rebase_off > 0)
    dip->rebase_off += delta;
  if (dip->bind_off > 0)
    dip->bind_off += delta;
  if (dip->weak_bind_off > 0)
    dip->weak_bind_off += delta;
  if (dip->lazy_bind_off > 0)
    dip->lazy_bind_off += delta;
  if (dip->export_off > 0)
    dip->export_off += delta;

  printf ("Writing ");
  print_load_command_name (lc->cmd);
  printf (" command\n");

  if (!unexec_write (curr_header_offset, lc, lc->cmdsize))
    unexec_error ("cannot write dyld info command to header");

  curr_header_offset += lc->cmdsize;
}
#endif

1152
#ifdef LC_FUNCTION_STARTS
1153 1154 1155
/* Copy a LC_FUNCTION_STARTS/LC_DATA_IN_CODE/LC_DYLIB_CODE_SIGN_DRS
   load command from the input file to the output file, adjusting the
   data offset field.  */
1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
static void
copy_linkedit_data (struct load_command *lc, long delta)
{
  struct linkedit_data_command *ldp = (struct linkedit_data_command *) lc;

  if (ldp->dataoff > 0)
    ldp->dataoff += delta;

  printf ("Writing ");
  print_load_command_name (lc->cmd);
  printf (" command\n");

  if (!unexec_write (curr_header_offset, lc, lc->cmdsize))
    unexec_error ("cannot write linkedit data command to header");

  curr_header_offset += lc->cmdsize;
}
#endif

1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
/* Copy other kinds of load commands from the input file to the output
   file, ones that do not require adjustments of file offsets.  */
static void
copy_other (struct load_command *lc)
{
  printf ("Writing ");
  print_load_command_name (lc->cmd);
  printf (" command\n");

  if (!unexec_write (curr_header_offset, lc, lc->cmdsize))
    unexec_error ("cannot write symtab command to header");

  curr_header_offset += lc->cmdsize;
}

/* Loop through all load commands and dump them.  Then write the Mach
   header.  */
static void
1193
dump_it (void)
1194 1195
{
  int i;
1196
  long linkedit_delta = 0;
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207

  printf ("--- Load Commands written to Output File ---\n");

  for (i = 0; i < nlc; i++)
    switch (lca[i]->cmd)
      {
      case LC_SEGMENT:
	{
	  struct segment_command *scp = (struct segment_command *) lca[i];
	  if (strncmp (scp->segname, SEG_DATA, 16) == 0)
	    {
1208 1209
	      /* save data segment file offset and segment_command for
		 unrelocate */
1210 1211 1212
	      if (data_segment_old_fileoff)
		unexec_error ("cannot handle multiple DATA segments"
			      " in input file");
1213 1214 1215
	      data_segment_old_fileoff = scp->fileoff;
	      data_segment_scp = scp;

1216 1217 1218 1219
	      copy_data_segment (lca[i]);
	    }
	  else
	    {
1220 1221 1222 1223 1224 1225 1226 1227
	      if (strncmp (scp->segname, SEG_LINKEDIT, 16) == 0)
		{
		  if (linkedit_delta)
		    unexec_error ("cannot handle multiple LINKEDIT segments"
				  " in input file");
		  linkedit_delta = curr_file_offset - scp->fileoff;
		}

1228 1229 1230 1231 1232
	      copy_segment (lca[i]);
	    }
	}
	break;
      case LC_SYMTAB:
1233
	copy_symtab (lca[i], linkedit_delta);
1234 1235
	break;
      case LC_DYSYMTAB:
1236
	copy_dysymtab (lca[i], linkedit_delta);
1237
	break;
1238
      case LC_TWOLEVEL_HINTS:
1239
	copy_twolevelhints (lca[i], linkedit_delta);
1240
	break;
1241 1242 1243 1244 1245
#ifdef LC_DYLD_INFO
      case LC_DYLD_INFO:
      case LC_DYLD_INFO_ONLY:
	copy_dyld_info (lca[i], linkedit_delta);
	break;
1246 1247 1248
#endif
#ifdef LC_FUNCTION_STARTS
      case LC_FUNCTION_STARTS:
1249 1250 1251
#ifdef LC_DATA_IN_CODE
      case LC_DATA_IN_CODE:
#endif
1252 1253 1254
#ifdef LC_DYLIB_CODE_SIGN_DRS
      case LC_DYLIB_CODE_SIGN_DRS:
#endif
1255 1256
	copy_linkedit_data (lca[i], linkedit_delta);
	break;
1257
#endif
1258 1259 1260 1261 1262 1263
      default:
	copy_other (lca[i]);
	break;
      }

  if (curr_header_offset > text_seg_lowest_offset)
1264 1265 1266
    unexec_error ("not enough room for load commands for new __DATA segments"
		  " (increase headerpad_extra in configure.in to at least %lX)",
		  num_unexec_regions * sizeof (struct segment_command));
1267

1268
  printf ("%ld unused bytes follow Mach-O header\n",
1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
	  text_seg_lowest_offset - curr_header_offset);

  mh.sizeofcmds = curr_header_offset - sizeof (struct mach_header);
  if (!unexec_write (0, &mh, sizeof (struct mach_header)))
    unexec_error ("cannot write final header contents");
}

/* Take a snapshot of Emacs and make a Mach-O format executable file
   from it.  The file names of the output and input files are outfile
   and infile, respectively.  The three other parameters are
   ignored.  */
1280
void
1281
unexec (const char *outfile, const char *infile)
1282
{
1283 1284 1285
  if (in_dumped_exec)
    unexec_error ("Unexec from a dumped executable is not supported.");

1286
  pagesize = getpagesize ();
1287
  infd = emacs_open (infile, O_RDONLY, 0);
1288 1289
  if (infd < 0)
    {
1290
      unexec_error ("%s: %s", infile, strerror (errno));
1291
    }
1292

1293
  outfd = emacs_open (outfile, O_WRONLY | O_TRUNC | O_CREAT, 0777);
1294 1295
  if (outfd < 0)
    {
1296
      emacs_close (infd);
1297
      unexec_error ("%s: %s", outfile, strerror (errno));
1298 1299 1300 1301 1302 1303
    }

  build_region_list ();
  read_load_commands ();

  find_emacs_zone_regions ();
1304
  unexec_regions_merge ();
1305 1306 1307 1308 1309

  in_dumped_exec = 1;

  dump_it ();

1310
  emacs_close (outfd);
1311 1312 1313 1314
}


void
1315
unexec_init_emacs_zone (void)
1316 1317 1318 1319 1320
{
  emacs_zone = malloc_create_zone (0, 0);
  malloc_set_zone_name (emacs_zone, "EmacsZone");
}

YAMAMOTO Mitsuharu's avatar
YAMAMOTO Mitsuharu committed
1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337
#ifndef MACOSX_MALLOC_MULT16
#define MACOSX_MALLOC_MULT16 1
#endif

typedef struct unexec_malloc_header {
  union {
    char c[8];
    size_t size;
  } u;
} unexec_malloc_header_t;

#if MACOSX_MALLOC_MULT16

#define ptr_in_unexec_regions(p) ((((vm_address_t) (p)) & 8) != 0)

#else

1338 1339 1340 1341 1342 1343
int
ptr_in_unexec_regions (void *ptr)
{
  int i;

  for (i = 0; i < num_unexec_regions; i++)
1344 1345
    if ((vm_address_t) ptr - unexec_regions[i].range.address
	< unexec_regions[i].range.size)
1346 1347 1348 1349 1350
      return 1;

  return 0;
}

YAMAMOTO Mitsuharu's avatar
YAMAMOTO Mitsuharu committed
1351 1352
#endif

1353 1354 1355 1356
void *
unexec_malloc (size_t size)
{
  if (in_dumped_exec)
YAMAMOTO Mitsuharu's avatar
YAMAMOTO Mitsuharu committed
1357 1358 1359 1360 1361 1362 1363 1364 1365
    {
      void *p;

      p = malloc (size);
#if MACOSX_MALLOC_MULT16
      assert (((vm_address_t) p % 16) == 0);
#endif
      return p;
    }
1366
  else
YAMAMOTO Mitsuharu's avatar
YAMAMOTO Mitsuharu committed
1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378
    {
      unexec_malloc_header_t *ptr;

      ptr = (unexec_malloc_header_t *)
	malloc_zone_malloc (emacs_zone, size + sizeof (unexec_malloc_header_t));
      ptr->u.size = size;
      ptr++;
#if MACOSX_MALLOC_MULT16
      assert (((vm_address_t) ptr % 16) == 8);
#endif
      return (void *) ptr;
    }
1379 1380 1381 1382 1383 1384
}

void *
unexec_realloc (void *old_ptr, size_t new_size)
{
  if (in_dumped_exec)
YAMAMOTO Mitsuharu's avatar
YAMAMOTO Mitsuharu committed
1385 1386 1387 1388 1389 1390 1391 1392
    {
      void *p;

      if (ptr_in_unexec_regions (old_ptr))
	{
	  size_t old_size = ((unexec_malloc_header_t *) old_ptr)[-1].u.size;
	  size_t size = new_size > old_size ? old_size : new_size;

1393
	  p = malloc (new_size);
YAMAMOTO Mitsuharu's avatar
YAMAMOTO Mitsuharu committed
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405
	  if (size)
	    memcpy (p, old_ptr, size);
	}
      else
	{
	  p = realloc (old_ptr, new_size);
	}
#if MACOSX_MALLOC_MULT16
      assert (((vm_address_t) p % 16) == 0);
#endif
      return p;
    }
1406
  else
YAMAMOTO Mitsuharu's avatar
YAMAMOTO Mitsuharu committed
1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419
    {
      unexec_malloc_header_t *ptr;

      ptr = (unexec_malloc_header_t *)
	malloc_zone_realloc (emacs_zone, (unexec_malloc_header_t *) old_ptr - 1,
			     new_size + sizeof (unexec_malloc_header_t));
      ptr->u.size = new_size;
      ptr++;
#if MACOSX_MALLOC_MULT16
      assert (((vm_address_t) ptr % 16) == 8);
#endif
      return (void *) ptr;
    }
1420 1421 1422 1423 1424
}

void
unexec_free (void *ptr)
{
1425 1426
  if (ptr == NULL)
    return;
1427 1428 1429 1430 1431 1432
  if (in_dumped_exec)
    {
      if (!ptr_in_unexec_regions (ptr))
	free (ptr);
    }
  else
YAMAMOTO Mitsuharu's avatar
YAMAMOTO Mitsuharu committed
1433
    malloc_zone_free (emacs_zone, (unexec_malloc_header_t *) ptr - 1);
1434
}