1/* Copyright (C) 1985, 1986, 1987, 1988, 1992, 1993, 1994, 2001, 2002, 2003,
2                 2004, 2005, 2006, 2007  Free Software Foundation, Inc.
3
4This file is part of GNU Emacs.
5
6GNU Emacs is free software; you can redistribute it and/or modify
7it under the terms of the GNU General Public License as published by
8the Free Software Foundation; either version 2, or (at your option)
9any later version.
10
11GNU Emacs is distributed in the hope that it will be useful,
12but WITHOUT ANY WARRANTY; without even the implied warranty of
13MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14GNU General Public License for more details.
15
16You should have received a copy of the GNU General Public License
17along with GNU Emacs; see the file COPYING.  If not, write to
18the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
19Boston, MA 02110-1301, USA.  */
20
21
22/*
23 * unexec.c - Convert a running program into an a.out file.
24 *
25 * Author:	Spencer W. Thomas
26 * 		Computer Science Dept.
27 * 		University of Utah
28 * Date:	Tue Mar  2 1982
29 * Modified heavily since then.
30 *
31 * Synopsis:
32 *	unexec (new_name, a_name, data_start, bss_start, entry_address)
33 *	char *new_name, *a_name;
34 *	unsigned data_start, bss_start, entry_address;
35 *
36 * Takes a snapshot of the program and makes an a.out format file in the
37 * file named by the string argument new_name.
38 * If a_name is non-NULL, the symbol table will be taken from the given file.
39 * On some machines, an existing a_name file is required.
40 *
41 * The boundaries within the a.out file may be adjusted with the data_start
42 * and bss_start arguments.  Either or both may be given as 0 for defaults.
43 *
44 * Data_start gives the boundary between the text segment and the data
45 * segment of the program.  The text segment can contain shared, read-only
46 * program code and literal data, while the data segment is always unshared
47 * and unprotected.  Data_start gives the lowest unprotected address.
48 * The value you specify may be rounded down to a suitable boundary
49 * as required by the machine you are using.
50 *
51 * Specifying zero for data_start means the boundary between text and data
52 * should not be the same as when the program was loaded.
53 * If NO_REMAP is defined, the argument data_start is ignored and the
54 * segment boundaries are never changed.
55 *
56 * Bss_start indicates how much of the data segment is to be saved in the
57 * a.out file and restored when the program is executed.  It gives the lowest
58 * unsaved address, and is rounded up to a page boundary.  The default when 0
59 * is given assumes that the entire data segment is to be stored, including
60 * the previous data and bss as well as any additional storage allocated with
61 * break (2).
62 *
63 * The new file is set up to start at entry_address.
64 *
65 * If you make improvements I'd like to get them too.
66 * harpo!utah-cs!thomas, thomas@Utah-20
67 *
68 */
69
70/* Modified to support SysVr3 shared libraries by James Van Artsdalen
71 * of Dell Computer Corporation.  james@bigtex.cactus.org.
72 */
73
74/* There are several compilation parameters affecting unexec:
75
76* COFF
77
78Define this if your system uses COFF for executables.
79
80* COFF_ENCAPSULATE
81
82Define this if you are using the GNU coff encapsulated a.out format.
83This is closer to a.out than COFF. You should *not* define COFF if
84you define COFF_ENCAPSULATE
85
86Otherwise we assume you use Berkeley format.
87
88* NO_REMAP
89
90Define this if you do not want to try to save Emacs's pure data areas
91as part of the text segment.
92
93Saving them as text is good because it allows users to share more.
94
95However, on machines that locate the text area far from the data area,
96the boundary cannot feasibly be moved.  Such machines require
97NO_REMAP.
98
99Also, remapping can cause trouble with the built-in startup routine
100/lib/crt0.o, which defines `environ' as an initialized variable.
101Dumping `environ' as pure does not work!  So, to use remapping,
102you must write a startup routine for your machine in Emacs's crt0.c.
103If NO_REMAP is defined, Emacs uses the system's crt0.o.
104
105* SECTION_ALIGNMENT
106
107Some machines that use COFF executables require that each section
108start on a certain boundary *in the COFF file*.  Such machines should
109define SECTION_ALIGNMENT to a mask of the low-order bits that must be
110zero on such a boundary.  This mask is used to control padding between
111segments in the COFF file.
112
113If SECTION_ALIGNMENT is not defined, the segments are written
114consecutively with no attempt at alignment.  This is right for
115unmodified system V.
116
117* SEGMENT_MASK
118
119Some machines require that the beginnings and ends of segments
120*in core* be on certain boundaries.  For most machines, a page
121boundary is sufficient.  That is the default.  When a larger
122boundary is needed, define SEGMENT_MASK to a mask of
123the bits that must be zero on such a boundary.
124
125* A_TEXT_OFFSET(HDR)
126
127Some machines count the a.out header as part of the size of the text
128segment (a_text); they may actually load the header into core as the
129first data in the text segment.  Some have additional padding between
130the header and the real text of the program that is counted in a_text.
131
132For these machines, define A_TEXT_OFFSET(HDR) to examine the header
133structure HDR and return the number of bytes to add to `a_text'
134before writing it (above and beyond the number of bytes of actual
135program text).  HDR's standard fields are already correct, except that
136this adjustment to the `a_text' field has not yet been made;
137thus, the amount of offset can depend on the data in the file.
138
139* A_TEXT_SEEK(HDR)
140
141If defined, this macro specifies the number of bytes to seek into the
142a.out file before starting to write the text segment.
143
144* EXEC_MAGIC
145
146For machines using COFF, this macro, if defined, is a value stored
147into the magic number field of the output file.
148
149* ADJUST_EXEC_HEADER
150
151This macro can be used to generate statements to adjust or
152initialize nonstandard fields in the file header
153
154* ADDR_CORRECT(ADDR)
155
156Macro to correct an int which is the bit pattern of a pointer to a byte
157into an int which is the number of a byte.
158
159This macro has a default definition which is usually right.
160This default definition is a no-op on most machines (where a
161pointer looks like an int) but not on all machines.
162
163*/
164
165#ifndef emacs
166#define PERROR(arg) perror (arg); return -1
167#else
168#define IN_UNEXEC
169#include <config.h>
170#define PERROR(file) report_error (file, new)
171#endif
172
173#ifndef CANNOT_DUMP  /* all rest of file!  */
174
175#if defined(COFF) && defined(HAVE_COFF_H)
176#include <coff.h>
177#ifdef MSDOS
178#if __DJGPP__ > 1
179#include <fcntl.h>  /* for O_RDONLY, O_RDWR */
180#include <crt0.h>   /* for _crt0_startup_flags and its bits */
181static int save_djgpp_startup_flags;
182#endif /* __DJGPP__ > 1 */
183#define filehdr external_filehdr
184#define scnhdr external_scnhdr
185#define syment external_syment
186#define auxent external_auxent
187#define n_numaux e_numaux
188#define n_type e_type
189struct aouthdr
190{
191  unsigned short	magic;	/* type of file				*/
192  unsigned short	vstamp;	/* version stamp			*/
193  unsigned long		tsize;	/* text size in bytes, padded to FW bdry*/
194  unsigned long		dsize;	/* initialized data "  "		*/
195  unsigned long		bsize;	/* uninitialized data "   "		*/
196  unsigned long		entry;	/* entry pt.				*/
197  unsigned long	 	text_start;/* base of text used for this file */
198  unsigned long	 	data_start;/* base of data used for this file */
199};
200#endif /* not MSDOS */
201#else  /* not COFF */
202#ifdef COFF_ENCAPSULATE
203int need_coff_header = 1;
204#include <coff-encap/a.out.encap.h> /* The location might be a poor assumption */
205#else  /* not COFF_ENCAPSULATE */
206#include <a.out.h>
207#endif /* not COFF_ENCAPSULATE */
208#endif /* not COFF */
209
210/* Define getpagesize if the system does not.
211   Note that this may depend on symbols defined in a.out.h.  */
212#include "getpagesize.h"
213
214#ifndef makedev			/* Try to detect types.h already loaded */
215#include <sys/types.h>
216#endif /* makedev */
217#include <stdio.h>
218#include <sys/stat.h>
219#include <errno.h>
220
221#include <sys/file.h>	/* Must be after sys/types.h for USG and BSD4_1*/
222
223#ifdef USG5
224#include <fcntl.h>
225#endif
226
227#ifndef O_RDONLY
228#define O_RDONLY 0
229#endif
230#ifndef O_RDWR
231#define O_RDWR 2
232#endif
233
234
235extern char *start_of_text ();		/* Start of text */
236extern char *start_of_data ();		/* Start of initialized data */
237
238#ifdef COFF
239static long block_copy_start;		/* Old executable start point */
240static struct filehdr f_hdr;		/* File header */
241static struct aouthdr f_ohdr;		/* Optional file header (a.out) */
242long bias;			/* Bias to add for growth */
243long lnnoptr;			/* Pointer to line-number info within file */
244#define SYMS_START block_copy_start
245
246static long text_scnptr;
247static long data_scnptr;
248
249static long coff_offset;
250
251#else /* not COFF */
252
253#ifdef HPUX
254extern void *sbrk ();
255#else
256#if 0
257/* Some systems with __STDC__ compilers still declare this `char *' in some
258   header file, and our declaration conflicts.  The return value is always
259   cast, so it should be harmless to leave it undefined.  Hopefully
260   machines with different size pointers and ints declare sbrk in a header
261   file.  */
262#ifdef __STDC__
263extern void *sbrk ();
264#else
265extern char *sbrk ();
266#endif /* __STDC__ */
267#endif
268#endif /* HPUX */
269
270#define SYMS_START ((long) N_SYMOFF (ohdr))
271
272/* Some machines override the structure name for an a.out header.  */
273#ifndef EXEC_HDR_TYPE
274#define EXEC_HDR_TYPE struct exec
275#endif
276
277#ifdef HPUX
278#ifdef HP9000S200_ID
279#define MY_ID HP9000S200_ID
280#else
281#include <model.h>
282#define MY_ID MYSYS
283#endif /* no HP9000S200_ID */
284static MAGIC OLDMAGIC = {MY_ID, SHARE_MAGIC};
285static MAGIC NEWMAGIC = {MY_ID, DEMAND_MAGIC};
286#define N_TXTOFF(x) TEXT_OFFSET(x)
287#define N_SYMOFF(x) LESYM_OFFSET(x)
288static EXEC_HDR_TYPE hdr, ohdr;
289
290#else /* not HPUX */
291
292#if defined (USG) && !defined (IBMAIX) && !defined (IRIS) && !defined (COFF_ENCAPSULATE) && !defined (GNU_LINUX)
293static struct bhdr hdr, ohdr;
294#define a_magic fmagic
295#define a_text tsize
296#define a_data dsize
297#define a_bss bsize
298#define a_syms ssize
299#define a_trsize rtsize
300#define a_drsize rdsize
301#define a_entry entry
302#define	N_BADMAG(x) \
303    (((x).fmagic)!=OMAGIC && ((x).fmagic)!=NMAGIC &&\
304     ((x).fmagic)!=FMAGIC && ((x).fmagic)!=IMAGIC)
305#define NEWMAGIC FMAGIC
306#else /* IRIS or IBMAIX or not USG */
307static EXEC_HDR_TYPE hdr, ohdr;
308#define NEWMAGIC ZMAGIC
309#endif /* IRIS or IBMAIX not USG */
310#endif /* not HPUX */
311
312static int unexec_text_start;
313static int unexec_data_start;
314
315#ifdef COFF_ENCAPSULATE
316/* coffheader is defined in the GNU a.out.encap.h file.  */
317struct coffheader coffheader;
318#endif
319
320#endif /* not COFF */
321
322static int pagemask;
323
324/* Correct an int which is the bit pattern of a pointer to a byte
325   into an int which is the number of a byte.
326   This is a no-op on ordinary machines, but not on all.  */
327
328#ifndef ADDR_CORRECT   /* Let m-*.h files override this definition */
329#define ADDR_CORRECT(x) ((char *)(x) - (char*)0)
330#endif
331
332#ifdef emacs
333
334#include "lisp.h"
335
336static
337report_error (file, fd)
338     char *file;
339     int fd;
340{
341  if (fd)
342    close (fd);
343  report_file_error ("Cannot unexec", Fcons (build_string (file), Qnil));
344}
345#endif /* emacs */
346
347#define ERROR0(msg) report_error_1 (new, msg, 0, 0); return -1
348#define ERROR1(msg,x) report_error_1 (new, msg, x, 0); return -1
349#define ERROR2(msg,x,y) report_error_1 (new, msg, x, y); return -1
350
351static
352report_error_1 (fd, msg, a1, a2)
353     int fd;
354     char *msg;
355     int a1, a2;
356{
357  close (fd);
358#ifdef emacs
359  error (msg, a1, a2);
360#else
361  fprintf (stderr, msg, a1, a2);
362  fprintf (stderr, "\n");
363#endif
364}
365
366static int make_hdr ();
367static int copy_text_and_data ();
368static int copy_sym ();
369static void mark_x ();
370
371/* ****************************************************************
372 * make_hdr
373 *
374 * Make the header in the new a.out from the header in core.
375 * Modify the text and data sizes.
376 */
377static int
378make_hdr (new, a_out, data_start, bss_start, entry_address, a_name, new_name)
379     int new, a_out;
380     unsigned data_start, bss_start, entry_address;
381     char *a_name;
382     char *new_name;
383{
384  int tem;
385#ifdef COFF
386  auto struct scnhdr f_thdr;		/* Text section header */
387  auto struct scnhdr f_dhdr;		/* Data section header */
388  auto struct scnhdr f_bhdr;		/* Bss section header */
389  auto struct scnhdr scntemp;		/* Temporary section header */
390  register int scns;
391#endif /* COFF */
392#ifdef USG_SHARED_LIBRARIES
393  extern unsigned int bss_end;
394#else
395  unsigned int bss_end;
396#endif
397
398  pagemask = getpagesize () - 1;
399
400  /* Adjust text/data boundary. */
401#ifdef NO_REMAP
402  data_start = (int) start_of_data ();
403#else /* not NO_REMAP */
404  if (!data_start)
405    data_start = (int) start_of_data ();
406#endif /* not NO_REMAP */
407  data_start = ADDR_CORRECT (data_start);
408
409#ifdef SEGMENT_MASK
410  data_start = data_start & ~SEGMENT_MASK; /* (Down) to segment boundary. */
411#else
412  data_start = data_start & ~pagemask; /* (Down) to page boundary. */
413#endif
414
415  bss_end = ADDR_CORRECT (sbrk (0)) + pagemask;
416  bss_end &= ~ pagemask;
417
418  /* Adjust data/bss boundary. */
419  if (bss_start != 0)
420    {
421      bss_start = (ADDR_CORRECT (bss_start) + pagemask);
422      /* (Up) to page bdry. */
423      bss_start &= ~ pagemask;
424      if (bss_start > bss_end)
425	{
426	  ERROR1 ("unexec: Specified bss_start (%u) is past end of program",
427		  bss_start);
428	}
429    }
430  else
431    bss_start = bss_end;
432
433  if (data_start > bss_start)	/* Can't have negative data size. */
434    {
435      ERROR2 ("unexec: data_start (%u) can't be greater than bss_start (%u)",
436	      data_start, bss_start);
437    }
438
439#ifdef COFF
440  coff_offset = 0L;		/* stays zero, except in DJGPP */
441
442  /* Salvage as much info from the existing file as possible */
443  if (a_out >= 0)
444    {
445#ifdef MSDOS
446#if __DJGPP__ > 1
447      /* Support the coff-go32-exe format with a prepended stub, since
448	 this is what GCC 2.8.0 and later generates by default in DJGPP.  */
449      unsigned short mz_header[3];
450
451      if (read (a_out, &mz_header, sizeof (mz_header)) != sizeof (mz_header))
452	{
453	  PERROR (a_name);
454	}
455      if (mz_header[0] == 0x5a4d || mz_header[0] == 0x4d5a) /* "MZ" or "ZM" */
456	{
457	  coff_offset = (long)mz_header[2] * 512L;
458	  if (mz_header[1])
459	    coff_offset += (long)mz_header[1] - 512L;
460	  lseek (a_out, coff_offset, 0);
461	}
462      else
463	lseek (a_out, 0L, 0);
464#endif /* __DJGPP__ > 1 */
465#endif /* MSDOS */
466      if (read (a_out, &f_hdr, sizeof (f_hdr)) != sizeof (f_hdr))
467	{
468	  PERROR (a_name);
469	}
470      block_copy_start += sizeof (f_hdr);
471      if (f_hdr.f_opthdr > 0)
472	{
473	  if (read (a_out, &f_ohdr, sizeof (f_ohdr)) != sizeof (f_ohdr))
474	    {
475	      PERROR (a_name);
476	    }
477	  block_copy_start += sizeof (f_ohdr);
478	}
479      /* Loop through section headers, copying them in */
480      lseek (a_out, coff_offset + sizeof (f_hdr) + f_hdr.f_opthdr, 0);
481      for (scns = f_hdr.f_nscns; scns > 0; scns--) {
482	if (read (a_out, &scntemp, sizeof (scntemp)) != sizeof (scntemp))
483	  {
484	    PERROR (a_name);
485	  }
486	if (scntemp.s_scnptr > 0L)
487	  {
488            if (block_copy_start < scntemp.s_scnptr + scntemp.s_size)
489	      block_copy_start = scntemp.s_scnptr + scntemp.s_size;
490	  }
491	if (strcmp (scntemp.s_name, ".text") == 0)
492	  {
493	    f_thdr = scntemp;
494	  }
495	else if (strcmp (scntemp.s_name, ".data") == 0)
496	  {
497	    f_dhdr = scntemp;
498	  }
499	else if (strcmp (scntemp.s_name, ".bss") == 0)
500	  {
501	    f_bhdr = scntemp;
502	  }
503      }
504    }
505  else
506    {
507      ERROR0 ("can't build a COFF file from scratch yet");
508    }
509
510  /* Now we alter the contents of all the f_*hdr variables
511     to correspond to what we want to dump.  */
512
513#ifdef USG_SHARED_LIBRARIES
514
515  /* The amount of data we're adding to the file is distance from the
516   * end of the original .data space to the current end of the .data
517   * space.
518   */
519
520  bias = bss_start - (f_ohdr.data_start + f_dhdr.s_size);
521
522#endif
523
524  f_hdr.f_flags |= (F_RELFLG | F_EXEC);
525#ifdef TPIX
526  f_hdr.f_nscns = 3;
527#endif
528#ifdef EXEC_MAGIC
529  f_ohdr.magic = EXEC_MAGIC;
530#endif
531#ifndef NO_REMAP
532  f_ohdr.text_start = (long) start_of_text ();
533  f_ohdr.tsize = data_start - f_ohdr.text_start;
534  f_ohdr.data_start = data_start;
535#endif /* NO_REMAP */
536  f_ohdr.dsize = bss_start - f_ohdr.data_start;
537  f_ohdr.bsize = bss_end - bss_start;
538#ifndef KEEP_OLD_TEXT_SCNPTR
539  /* On some machines, the old values are right.
540     ??? Maybe on all machines with NO_REMAP.  */
541  f_thdr.s_size = f_ohdr.tsize;
542  f_thdr.s_scnptr = sizeof (f_hdr) + sizeof (f_ohdr);
543  f_thdr.s_scnptr += (f_hdr.f_nscns) * (sizeof (f_thdr));
544#endif /* KEEP_OLD_TEXT_SCNPTR */
545#ifdef ADJUST_TEXT_SCNHDR_SIZE
546  /* On some machines, `text size' includes all headers.  */
547  f_thdr.s_size -= f_thdr.s_scnptr;
548#endif /* ADJUST_TEST_SCNHDR_SIZE */
549  lnnoptr = f_thdr.s_lnnoptr;
550#ifdef SECTION_ALIGNMENT
551  /* Some systems require special alignment
552     of the sections in the file itself.  */
553  f_thdr.s_scnptr
554    = (f_thdr.s_scnptr + SECTION_ALIGNMENT) & ~SECTION_ALIGNMENT;
555#endif /* SECTION_ALIGNMENT */
556#ifdef TPIX
557  f_thdr.s_scnptr = 0xd0;
558#endif
559  text_scnptr = f_thdr.s_scnptr;
560#ifdef ADJUST_TEXTBASE
561  text_scnptr = sizeof (f_hdr) + sizeof (f_ohdr) + (f_hdr.f_nscns) * (sizeof (f_thdr));
562#endif
563#ifndef KEEP_OLD_PADDR
564  f_dhdr.s_paddr = f_ohdr.data_start;
565#endif /* KEEP_OLD_PADDR */
566  f_dhdr.s_vaddr = f_ohdr.data_start;
567  f_dhdr.s_size = f_ohdr.dsize;
568  f_dhdr.s_scnptr = f_thdr.s_scnptr + f_thdr.s_size;
569#ifdef SECTION_ALIGNMENT
570  /* Some systems require special alignment
571     of the sections in the file itself.  */
572  f_dhdr.s_scnptr
573    = (f_dhdr.s_scnptr + SECTION_ALIGNMENT) & ~SECTION_ALIGNMENT;
574#endif /* SECTION_ALIGNMENT */
575#ifdef DATA_SECTION_ALIGNMENT
576  /* Some systems require special alignment
577     of the data section only.  */
578  f_dhdr.s_scnptr
579    = (f_dhdr.s_scnptr + DATA_SECTION_ALIGNMENT) & ~DATA_SECTION_ALIGNMENT;
580#endif /* DATA_SECTION_ALIGNMENT */
581  data_scnptr = f_dhdr.s_scnptr;
582#ifndef KEEP_OLD_PADDR
583  f_bhdr.s_paddr = f_ohdr.data_start + f_ohdr.dsize;
584#endif /* KEEP_OLD_PADDR */
585  f_bhdr.s_vaddr = f_ohdr.data_start + f_ohdr.dsize;
586  f_bhdr.s_size = f_ohdr.bsize;
587  f_bhdr.s_scnptr = 0L;
588#ifndef USG_SHARED_LIBRARIES
589  bias = f_dhdr.s_scnptr + f_dhdr.s_size - block_copy_start;
590#endif
591
592  if (f_hdr.f_symptr > 0L)
593    {
594      f_hdr.f_symptr += bias;
595    }
596
597  if (f_thdr.s_lnnoptr > 0L)
598    {
599      f_thdr.s_lnnoptr += bias;
600    }
601
602#ifdef ADJUST_EXEC_HEADER
603  ADJUST_EXEC_HEADER;
604#endif /* ADJUST_EXEC_HEADER */
605
606  if (write (new, &f_hdr, sizeof (f_hdr)) != sizeof (f_hdr))
607    {
608      PERROR (new_name);
609    }
610
611  if (write (new, &f_ohdr, sizeof (f_ohdr)) != sizeof (f_ohdr))
612    {
613      PERROR (new_name);
614    }
615
616#ifndef USG_SHARED_LIBRARIES
617
618  if (write (new, &f_thdr, sizeof (f_thdr)) != sizeof (f_thdr))
619    {
620      PERROR (new_name);
621    }
622
623  if (write (new, &f_dhdr, sizeof (f_dhdr)) != sizeof (f_dhdr))
624    {
625      PERROR (new_name);
626    }
627
628  if (write (new, &f_bhdr, sizeof (f_bhdr)) != sizeof (f_bhdr))
629    {
630      PERROR (new_name);
631    }
632
633#else /* USG_SHARED_LIBRARIES */
634
635  /* The purpose of this code is to write out the new file's section
636   * header table.
637   *
638   * Scan through the original file's sections.  If the encountered
639   * section is one we know (.text, .data or .bss), write out the
640   * correct header.  If it is a section we do not know (such as
641   * .lib), adjust the address of where the section data is in the
642   * file, and write out the header.
643   *
644   * If any section precedes .text or .data in the file, this code
645   * will not adjust the file pointer for that section correctly.
646   */
647
648  /* This used to use sizeof (f_ohdr) instead of .f_opthdr.
649     .f_opthdr is said to be right when there is no optional header.  */
650  lseek (a_out, sizeof (f_hdr) + f_hdr.f_opthdr, 0);
651
652  for (scns = f_hdr.f_nscns; scns > 0; scns--)
653    {
654      if (read (a_out, &scntemp, sizeof (scntemp)) != sizeof (scntemp))
655	PERROR (a_name);
656
657      if (!strcmp (scntemp.s_name, f_thdr.s_name))	/* .text */
658	{
659	  if (write (new, &f_thdr, sizeof (f_thdr)) != sizeof (f_thdr))
660	    PERROR (new_name);
661	}
662      else if (!strcmp (scntemp.s_name, f_dhdr.s_name))	/* .data */
663	{
664	  if (write (new, &f_dhdr, sizeof (f_dhdr)) != sizeof (f_dhdr))
665	    PERROR (new_name);
666	}
667      else if (!strcmp (scntemp.s_name, f_bhdr.s_name))	/* .bss */
668	{
669	  if (write (new, &f_bhdr, sizeof (f_bhdr)) != sizeof (f_bhdr))
670	    PERROR (new_name);
671	}
672      else
673	{
674	  if (scntemp.s_scnptr)
675	    scntemp.s_scnptr += bias;
676	  if (write (new, &scntemp, sizeof (scntemp)) != sizeof (scntemp))
677	    PERROR (new_name);
678	}
679    }
680#endif /* USG_SHARED_LIBRARIES */
681
682  return (0);
683
684#else /* if not COFF */
685
686  /* Get symbol table info from header of a.out file if given one. */
687  if (a_out >= 0)
688    {
689#ifdef COFF_ENCAPSULATE
690      if (read (a_out, &coffheader, sizeof coffheader) != sizeof coffheader)
691	{
692	  PERROR(a_name);
693	}
694      if (coffheader.f_magic != COFF_MAGIC)
695	{
696	  ERROR1("%s doesn't have legal coff magic number\n", a_name);
697	}
698#endif
699      if (read (a_out, &ohdr, sizeof hdr) != sizeof hdr)
700	{
701	  PERROR (a_name);
702	}
703
704      if (N_BADMAG (ohdr))
705	{
706	  ERROR1 ("invalid magic number in %s", a_name);
707	}
708      hdr = ohdr;
709    }
710  else
711    {
712#ifdef COFF_ENCAPSULATE
713      /* We probably could without too much trouble. The code is in gld
714       * but I don't have that much time or incentive.
715       */
716      ERROR0 ("can't build a COFF file from scratch yet");
717#else
718#ifdef MSDOS	/* Demacs 1.1.1 91/10/16 HIRANO Satoshi */
719      bzero ((void *)&hdr, sizeof hdr);
720#else
721      bzero (&hdr, sizeof hdr);
722#endif
723#endif
724    }
725
726  unexec_text_start = (long) start_of_text ();
727  unexec_data_start = data_start;
728
729  /* Machine-dependent fixup for header, or maybe for unexec_text_start */
730#ifdef ADJUST_EXEC_HEADER
731  ADJUST_EXEC_HEADER;
732#endif /* ADJUST_EXEC_HEADER */
733
734  hdr.a_trsize = 0;
735  hdr.a_drsize = 0;
736  if (entry_address != 0)
737    hdr.a_entry = entry_address;
738
739  hdr.a_bss = bss_end - bss_start;
740  hdr.a_data = bss_start - data_start;
741#ifdef NO_REMAP
742  hdr.a_text = ohdr.a_text;
743#else /* not NO_REMAP */
744  hdr.a_text = data_start - unexec_text_start;
745
746#ifdef A_TEXT_OFFSET
747  hdr.a_text += A_TEXT_OFFSET (ohdr);
748#endif
749
750#endif /* not NO_REMAP */
751
752#ifdef COFF_ENCAPSULATE
753  /* We are encapsulating BSD format within COFF format.  */
754  {
755    struct coffscn *tp, *dp, *bp;
756    tp = &coffheader.scns[0];
757    dp = &coffheader.scns[1];
758    bp = &coffheader.scns[2];
759    tp->s_size = hdr.a_text + sizeof(struct exec);
760    dp->s_paddr = data_start;
761    dp->s_vaddr = data_start;
762    dp->s_size = hdr.a_data;
763    bp->s_paddr = dp->s_vaddr + dp->s_size;
764    bp->s_vaddr = bp->s_paddr;
765    bp->s_size = hdr.a_bss;
766    coffheader.tsize = tp->s_size;
767    coffheader.dsize = dp->s_size;
768    coffheader.bsize = bp->s_size;
769    coffheader.text_start = tp->s_vaddr;
770    coffheader.data_start = dp->s_vaddr;
771  }
772  if (write (new, &coffheader, sizeof coffheader) != sizeof coffheader)
773    {
774      PERROR(new_name);
775    }
776#endif /* COFF_ENCAPSULATE */
777
778  if (write (new, &hdr, sizeof hdr) != sizeof hdr)
779    {
780      PERROR (new_name);
781    }
782
783#if 0 /* This #ifndef caused a bug on GNU/Linux when using QMAGIC.  */
784  /* This adjustment was done above only #ifndef NO_REMAP,
785     so only undo it now #ifndef NO_REMAP.  */
786  /* #ifndef NO_REMAP  */
787#endif
788#ifdef A_TEXT_OFFSET
789  hdr.a_text -= A_TEXT_OFFSET (ohdr);
790#endif
791
792  return 0;
793
794#endif /* not COFF */
795}
796
797write_segment (new, ptr, end)
798     int new;
799     register char *ptr, *end;
800{
801  register int i, nwrite, ret;
802  char buf[80];
803#ifndef USE_CRT_DLL
804  extern int errno;
805#endif
806  /* This is the normal amount to write at once.
807     It is the size of block that NFS uses.  */
808  int writesize = 1 << 13;
809  int pagesize = getpagesize ();
810  char zeros[1 << 13];
811
812  bzero (zeros, sizeof (zeros));
813
814  for (i = 0; ptr < end;)
815    {
816      /* Distance to next multiple of writesize.  */
817      nwrite = (((int) ptr + writesize) & -writesize) - (int) ptr;
818      /* But not beyond specified end.  */
819      if (nwrite > end - ptr) nwrite = end - ptr;
820      ret = write (new, ptr, nwrite);
821      /* If write gets a page fault, it means we reached
822	 a gap between the old text segment and the old data segment.
823	 This gap has probably been remapped into part of the text segment.
824	 So write zeros for it.  */
825      if (ret == -1
826#ifdef EFAULT
827	  && errno == EFAULT
828#endif
829	  )
830	{
831	  /* Write only a page of zeros at once,
832	     so that we we don't overshoot the start
833	     of the valid memory in the old data segment.  */
834	  if (nwrite > pagesize)
835	    nwrite = pagesize;
836	  write (new, zeros, nwrite);
837	}
838#if 0 /* Now that we have can ask `write' to write more than a page,
839	 it is legit for write do less than the whole amount specified.  */
840      else if (nwrite != ret)
841	{
842	  sprintf (buf,
843		   "unexec write failure: addr 0x%x, fileno %d, size 0x%x, wrote 0x%x, errno %d",
844		   ptr, new, nwrite, ret, errno);
845	  PERROR (buf);
846	}
847#endif
848      i += nwrite;
849      ptr += nwrite;
850    }
851}
852/* ****************************************************************
853 * copy_text_and_data
854 *
855 * Copy the text and data segments from memory to the new a.out
856 */
857static int
858copy_text_and_data (new, a_out)
859     int new, a_out;
860{
861  register char *end;
862  register char *ptr;
863
864#ifdef COFF
865
866#ifdef USG_SHARED_LIBRARIES
867
868  int scns;
869  struct scnhdr scntemp;		/* Temporary section header */
870
871  /* The purpose of this code is to write out the new file's section
872   * contents.
873   *
874   * Step through the section table.  If we know the section (.text,
875   * .data) do the appropriate thing.  Otherwise, if the section has
876   * no allocated space in the file (.bss), do nothing.  Otherwise,
877   * the section has space allocated in the file, and is not a section
878   * we know.  So just copy it.
879   */
880
881  lseek (a_out, sizeof (struct filehdr) + sizeof (struct aouthdr), 0);
882
883  for (scns = f_hdr.f_nscns; scns > 0; scns--)
884    {
885      if (read (a_out, &scntemp, sizeof (scntemp)) != sizeof (scntemp))
886	PERROR ("temacs");
887
888      if (!strcmp (scntemp.s_name, ".text"))
889	{
890	  lseek (new, (long) text_scnptr, 0);
891	  ptr = (char *) f_ohdr.text_start;
892	  end = ptr + f_ohdr.tsize;
893	  write_segment (new, ptr, end);
894	}
895      else if (!strcmp (scntemp.s_name, ".data"))
896	{
897	  lseek (new, (long) data_scnptr, 0);
898	  ptr = (char *) f_ohdr.data_start;
899	  end = ptr + f_ohdr.dsize;
900	  write_segment (new, ptr, end);
901	}
902      else if (!scntemp.s_scnptr)
903	; /* do nothing - no data for this section */
904      else
905	{
906	  char page[BUFSIZ];
907	  int size, n;
908	  long old_a_out_ptr = lseek (a_out, 0, 1);
909
910	  lseek (a_out, scntemp.s_scnptr, 0);
911	  for (size = scntemp.s_size; size > 0; size -= sizeof (page))
912	    {
913	      n = size > sizeof (page) ? sizeof (page) : size;
914	      if (read (a_out, page, n) != n || write (new, page, n) != n)
915		PERROR ("emacs");
916	    }
917	  lseek (a_out, old_a_out_ptr, 0);
918	}
919    }
920
921#else /* COFF, but not USG_SHARED_LIBRARIES */
922
923#ifdef MSDOS
924#if __DJGPP__ >= 2
925  /* Dump the original table of exception handlers, not the one
926     where our exception hooks are registered.  */
927  __djgpp_exception_toggle ();
928
929  /* Switch off startup flags that might have been set at runtime
930     and which might change the way that dumped Emacs works.  */
931  save_djgpp_startup_flags = _crt0_startup_flags;
932  _crt0_startup_flags &= ~(_CRT0_FLAG_NO_LFN | _CRT0_FLAG_NEARPTR);
933#endif
934#endif
935
936  lseek (new, (long) text_scnptr, 0);
937  ptr = (char *) f_ohdr.text_start;
938#ifdef HEADER_INCL_IN_TEXT
939  /* For Gould UTX/32, text starts after headers */
940  ptr = (char *) (ptr + text_scnptr);
941#endif /* HEADER_INCL_IN_TEXT */
942  end = ptr + f_ohdr.tsize;
943  write_segment (new, ptr, end);
944
945  lseek (new, (long) data_scnptr, 0);
946  ptr = (char *) f_ohdr.data_start;
947  end = ptr + f_ohdr.dsize;
948  write_segment (new, ptr, end);
949
950#ifdef MSDOS
951#if __DJGPP__ >= 2
952  /* Restore our exception hooks.  */
953  __djgpp_exception_toggle ();
954
955  /* Restore the startup flags.  */
956  _crt0_startup_flags = save_djgpp_startup_flags;
957#endif
958#endif
959
960#endif /* USG_SHARED_LIBRARIES */
961
962#else /* if not COFF */
963
964/* Some machines count the header as part of the text segment.
965   That is to say, the header appears in core
966   just before the address that start_of_text returns.
967   For them, N_TXTOFF is the place where the header goes.
968   We must adjust the seek to the place after the header.
969   Note that at this point hdr.a_text does *not* count
970   the extra A_TEXT_OFFSET bytes, only the actual bytes of code.  */
971
972#ifdef A_TEXT_SEEK
973  lseek (new, (long) A_TEXT_SEEK (hdr), 0);
974#else
975  lseek (new, (long) N_TXTOFF (hdr), 0);
976#endif /* no A_TEXT_SEEK */
977
978#ifdef RISCiX
979
980  /* Acorn's RISC-iX has a wacky way of initialising the position of the heap.
981   * There is a little table in crt0.o that is filled at link time with
982   * the min and current brk positions, among other things.  When start
983   * runs, it copies the table to where these parameters live during
984   * execution.  This data is in text space, so it cannot be modified here
985   * before saving the executable, so the data is written manually.  In
986   * addition, the table does not have a label, and the nearest accessible
987   * label (mcount) is not prefixed with a '_', thus making it inaccessible
988   * from within C programs.  To overcome this, emacs's executable is passed
989   * through the command 'nm %s | fgrep mcount' into a pipe, and the
990   * resultant output is then used to find the address of 'mcount'.  As far as
991   * is possible to determine, in RISC-iX releases prior to 1.2, the negative
992   * offset of the table from mcount is 0x2c, whereas from 1.2 onwards it is
993   * 0x30.  bss_end has been rounded up to page boundary.  This solution is
994   * based on suggestions made by Kevin Welton and Steve Hunt of Acorn, and
995   * avoids the need for a custom version of crt0.o for emacs which has its
996   * table in data space.
997   */
998
999  {
1000    char command[1024];
1001    char errbuf[1024];
1002    char address_text[32];
1003    int  proforma[4];
1004    FILE *pfile;
1005    char *temp_ptr;
1006    char c;
1007    int mcount_address, mcount_offset, count;
1008    extern char *_execname;
1009
1010
1011    /* The use of _execname is incompatible with RISCiX 1.1 */
1012    sprintf (command, "nm %s | fgrep mcount", _execname);
1013
1014    if ( (pfile = popen(command, "r")) == NULL)
1015    {
1016      sprintf (errbuf, "Could not open pipe");
1017      PERROR (errbuf);
1018    }
1019
1020    count=0;
1021    while ( ((c=getc(pfile)) != EOF) && (c != ' ') && (count < 31))
1022      address_text[count++]=c;
1023    address_text[count]=0;
1024
1025    if ((count == 0) || pclose(pfile) != NULL)
1026    {
1027      sprintf (errbuf, "Failed to execute the command '%s'\n", command);
1028      PERROR (errbuf);
1029    }
1030
1031    sscanf(address_text, "%x", &mcount_address);
1032    ptr = (char *) unexec_text_start;
1033    mcount_offset = (char *)mcount_address - ptr;
1034
1035#ifdef RISCiX_1_1
1036#define EDATA_OFFSET 0x2c
1037#else
1038#define EDATA_OFFSET 0x30
1039#endif
1040
1041    end = ptr + mcount_offset - EDATA_OFFSET;
1042
1043    write_segment (new, ptr, end);
1044
1045    proforma[0] = bss_end;	/* becomes _edata */
1046    proforma[1] = bss_end;	/* becomes _end */
1047    proforma[2] = bss_end;	/* becomes _minbrk */
1048    proforma[3] = bss_end;	/* becomes _curbrk */
1049
1050    write (new, proforma, 16);
1051
1052    temp_ptr = ptr;
1053    ptr = end + 16;
1054    end = temp_ptr + hdr.a_text;
1055
1056    write_segment (new, ptr, end);
1057  }
1058
1059#else /* !RISCiX */
1060  ptr = (char *) unexec_text_start;
1061  end = ptr + hdr.a_text;
1062  write_segment (new, ptr, end);
1063#endif /* RISCiX */
1064
1065  ptr = (char *) unexec_data_start;
1066  end = ptr + hdr.a_data;
1067/*  This lseek is certainly incorrect when A_TEXT_OFFSET
1068    and I believe it is a no-op otherwise.
1069    Let's see if its absence ever fails.  */
1070/*  lseek (new, (long) N_TXTOFF (hdr) + hdr.a_text, 0); */
1071  write_segment (new, ptr, end);
1072
1073#endif /* not COFF */
1074
1075  return 0;
1076}
1077
1078/* ****************************************************************
1079 * copy_sym
1080 *
1081 * Copy the relocation information and symbol table from the a.out to the new
1082 */
1083static int
1084copy_sym (new, a_out, a_name, new_name)
1085     int new, a_out;
1086     char *a_name, *new_name;
1087{
1088  char page[1024];
1089  int n;
1090
1091  if (a_out < 0)
1092    return 0;
1093
1094#ifdef COFF
1095  if (SYMS_START == 0L)
1096    return 0;
1097#endif  /* COFF */
1098
1099#ifdef COFF
1100  if (lnnoptr)			/* if there is line number info */
1101    lseek (a_out, coff_offset + lnnoptr, 0);	/* start copying from there */
1102  else
1103    lseek (a_out, coff_offset + SYMS_START, 0);	/* Position a.out to symtab. */
1104#else  /* not COFF */
1105  lseek (a_out, SYMS_START, 0);	/* Position a.out to symtab. */
1106#endif /* not COFF */
1107
1108  while ((n = read (a_out, page, sizeof page)) > 0)
1109    {
1110      if (write (new, page, n) != n)
1111	{
1112	  PERROR (new_name);
1113	}
1114    }
1115  if (n < 0)
1116    {
1117      PERROR (a_name);
1118    }
1119  return 0;
1120}
1121
1122/* ****************************************************************
1123 * mark_x
1124 *
1125 * After successfully building the new a.out, mark it executable
1126 */
1127static void
1128mark_x (name)
1129     char *name;
1130{
1131  struct stat sbuf;
1132  int um;
1133  int new = 0;  /* for PERROR */
1134
1135  um = umask (777);
1136  umask (um);
1137  if (stat (name, &sbuf) == -1)
1138    {
1139      PERROR (name);
1140    }
1141  sbuf.st_mode |= 0111 & ~um;
1142  if (chmod (name, sbuf.st_mode) == -1)
1143    PERROR (name);
1144}
1145
1146#ifdef COFF
1147#ifndef COFF_BSD_SYMBOLS
1148
1149/*
1150 *	If the COFF file contains a symbol table and a line number section,
1151 *	then any auxiliary entries that have values for x_lnnoptr must
1152 *	be adjusted by the amount that the line number section has moved
1153 *	in the file (bias computed in make_hdr).  The #@$%&* designers of
1154 *	the auxiliary entry structures used the absolute file offsets for
1155 *	the line number entry rather than an offset from the start of the
1156 *	line number section!
1157 *
1158 *	When I figure out how to scan through the symbol table and pick out
1159 *	the auxiliary entries that need adjustment, this routine will
1160 *	be fixed.  As it is now, all such entries are wrong and sdb
1161 *	will complain.   Fred Fish, UniSoft Systems Inc.
1162 */
1163
1164/* This function is probably very slow.  Instead of reopening the new
1165   file for input and output it should copy from the old to the new
1166   using the two descriptors already open (WRITEDESC and READDESC).
1167   Instead of reading one small structure at a time it should use
1168   a reasonable size buffer.  But I don't have time to work on such
1169   things, so I am installing it as submitted to me.  -- RMS.  */
1170
1171adjust_lnnoptrs (writedesc, readdesc, new_name)
1172     int writedesc;
1173     int readdesc;
1174     char *new_name;
1175{
1176  register int nsyms;
1177  register int new;
1178#if defined (amdahl_uts) || defined (pfa)
1179  SYMENT symentry;
1180  AUXENT auxentry;
1181#else
1182  struct syment symentry;
1183  union auxent auxentry;
1184#endif
1185
1186  if (!lnnoptr || !f_hdr.f_symptr)
1187    return 0;
1188
1189#ifdef MSDOS
1190  if ((new = writedesc) < 0)
1191#else
1192  if ((new = open (new_name, O_RDWR)) < 0)
1193#endif
1194    {
1195      PERROR (new_name);
1196      return -1;
1197    }
1198
1199  lseek (new, f_hdr.f_symptr, 0);
1200  for (nsyms = 0; nsyms < f_hdr.f_nsyms; nsyms++)
1201    {
1202      read (new, &symentry, SYMESZ);
1203      if (symentry.n_numaux)
1204	{
1205	  read (new, &auxentry, AUXESZ);
1206	  nsyms++;
1207	  if (ISFCN (symentry.n_type) || symentry.n_type == 0x2400)
1208	    {
1209	      auxentry.x_sym.x_fcnary.x_fcn.x_lnnoptr += bias;
1210	      lseek (new, -AUXESZ, 1);
1211	      write (new, &auxentry, AUXESZ);
1212	    }
1213	}
1214    }
1215#ifndef MSDOS
1216  close (new);
1217#endif
1218  return 0;
1219}
1220
1221#endif /* COFF_BSD_SYMBOLS */
1222
1223#endif /* COFF */
1224
1225/* ****************************************************************
1226 * unexec
1227 *
1228 * driving logic.
1229 */
1230unexec (new_name, a_name, data_start, bss_start, entry_address)
1231     char *new_name, *a_name;
1232     unsigned data_start, bss_start, entry_address;
1233{
1234  int new, a_out = -1;
1235
1236  if (a_name && (a_out = open (a_name, O_RDONLY)) < 0)
1237    {
1238      PERROR (a_name);
1239    }
1240  if ((new = creat (new_name, 0666)) < 0)
1241    {
1242      PERROR (new_name);
1243    }
1244
1245  if (make_hdr (new, a_out, data_start, bss_start, entry_address, a_name, new_name) < 0
1246      || copy_text_and_data (new, a_out) < 0
1247      || copy_sym (new, a_out, a_name, new_name) < 0
1248#ifdef COFF
1249#ifndef COFF_BSD_SYMBOLS
1250      || adjust_lnnoptrs (new, a_out, new_name) < 0
1251#endif
1252#endif
1253      )
1254    {
1255      close (new);
1256      /* unlink (new_name);	    	/* Failed, unlink new a.out */
1257      return -1;
1258    }
1259
1260  close (new);
1261  if (a_out >= 0)
1262    close (a_out);
1263  mark_x (new_name);
1264  return 0;
1265}
1266
1267#endif /* not CANNOT_DUMP */
1268
1269/* arch-tag: 62409b69-e27a-4a7c-9413-0210d6b54e7f
1270   (do not change this comment) */
1271