1/* Unexec for Siemens machines running Sinix (modified SVR4).
2   Copyright (C) 1985, 1986, 1987, 1988, 1990, 1992, 1993, 1994, 1995, 2001,
3                 2002, 2003, 2004, 2005, 2006, 2007
4                 Free Software Foundation, Inc.
5
6This file is part of GNU Emacs.
7
8GNU Emacs is free software; you can redistribute it and/or modify
9it under the terms of the GNU General Public License as published by
10the Free Software Foundation; either version 2, or (at your option)
11any later version.
12
13GNU Emacs is distributed in the hope that it will be useful,
14but WITHOUT ANY WARRANTY; without even the implied warranty of
15MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16GNU General Public License for more details.
17
18You should have received a copy of the GNU General Public License
19along with GNU Emacs; see the file COPYING.  If not, write to
20the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
21Boston, MA 02110-1301, USA.
22
23In other words, you are welcome to use, share and improve this program.
24You are forbidden to forbid anyone else to use, share and improve
25what you give them.   Help stamp out software-hoarding!  */
26
27/*
28 * unexec.c - Convert a running program into an a.out file.
29 *
30 * Author:	Spencer W. Thomas
31 * 		Computer Science Dept.
32 * 		University of Utah
33 * Date:	Tue Mar  2 1982
34 * Modified heavily since then.
35 *
36 * Synopsis:
37 *	unexec (new_name, a_name, data_start, bss_start, entry_address)
38 *	char *new_name, *a_name;
39 *	unsigned data_start, bss_start, entry_address;
40 *
41 * Takes a snapshot of the program and makes an a.out format file in the
42 * file named by the string argument new_name.
43 * If a_name is non-NULL, the symbol table will be taken from the given file.
44 * On some machines, an existing a_name file is required.
45 *
46 * The boundaries within the a.out file may be adjusted with the data_start
47 * and bss_start arguments.  Either or both may be given as 0 for defaults.
48 *
49 * Data_start gives the boundary between the text segment and the data
50 * segment of the program.  The text segment can contain shared, read-only
51 * program code and literal data, while the data segment is always unshared
52 * and unprotected.  Data_start gives the lowest unprotected address.
53 * The value you specify may be rounded down to a suitable boundary
54 * as required by the machine you are using.
55 *
56 * Specifying zero for data_start means the boundary between text and data
57 * should not be the same as when the program was loaded.
58 * If NO_REMAP is defined, the argument data_start is ignored and the
59 * segment boundaries are never changed.
60 *
61 * Bss_start indicates how much of the data segment is to be saved in the
62 * a.out file and restored when the program is executed.  It gives the lowest
63 * unsaved address, and is rounded up to a page boundary.  The default when 0
64 * is given assumes that the entire data segment is to be stored, including
65 * the previous data and bss as well as any additional storage allocated with
66 * break (2).
67 *
68 * The new file is set up to start at entry_address.
69 *
70 * If you make improvements I'd like to get them too.
71 * harpo!utah-cs!thomas, thomas@Utah-20
72 *
73 */
74
75/* Even more heavily modified by james@bigtex.cactus.org of Dell Computer Co.
76 * ELF support added.
77 *
78 * Basic theory: the data space of the running process needs to be
79 * dumped to the output file.  Normally we would just enlarge the size
80 * of .data, scooting everything down.  But we can't do that in ELF,
81 * because there is often something between the .data space and the
82 * .bss space.
83 *
84 * In the temacs dump below, notice that the Global Offset Table
85 * (.got) and the Dynamic link data (.dynamic) come between .data1 and
86 * .bss.  It does not work to overlap .data with these fields.
87 *
88 * The solution is to create a new .data segment.  This segment is
89 * filled with data from the current process.  Since the contents of
90 * various sections refer to sections by index, the new .data segment
91 * is made the last in the table to avoid changing any existing index.
92 */
93
94/* Modified by wtien@urbana.mcd.mot.com of Motorola Inc.
95 *
96 * The above mechanism does not work if the unexeced ELF file is being
97 * re-layout by other applications (such as `strip'). All the applications
98 * that re-layout the internal of ELF will layout all sections in ascending
99 * order of their file offsets. After the re-layout, the data2 section will
100 * still be the LAST section in the section header vector, but its file offset
101 * is now being pushed far away down, and causes part of it not to be mapped
102 * in (ie. not covered by the load segment entry in PHDR vector), therefore
103 * causes the new binary to fail.
104 *
105 * The solution is to modify the unexec algorithm to insert the new data2
106 * section header right before the new bss section header, so their file
107 * offsets will be in the ascending order. Since some of the section's (all
108 * sections AFTER the bss section) indexes are now changed, we also need to
109 * modify some fields to make them point to the right sections. This is done
110 * by macro PATCH_INDEX. All the fields that need to be patched are:
111 *
112 * 1. ELF header e_shstrndx field.
113 * 2. section header sh_link and sh_info field.
114 * 3. symbol table entry st_shndx field.
115 */
116
117/*
118 * New modifications for Siemens Nixdorf's MIPS-based machines.
119 * Marco.Walther@mch.sni.de
120 * marco@inreach.com
121 *
122 * The problem: Before the bss segment we have a so called sbss segment
123 *              (small bss) and maybe an sdata segment. These segments
124 *              must also be handled correct.
125 *
126 * /home1/marco/emacs/emacs-19.22/src
127 * dump -hv temacs
128 *
129 * temacs:
130 *
131 *	   **** SECTION HEADER TABLE ****
132 * [No]	Type	Flags	Addr         Offset       Size        	Name
133 *	Link	Info	Adralgn      Entsize
134 *
135 * [1]	PBIT    -A--	0x4000f4     0xf4         0x13         	.interp
136 *	0	0	0x1          0
137 *
138 * [2]	REGI    -A--	0x400108     0x108        0x18         	.reginfo
139 *	0	0	0x4          0x18
140 *
141 * [3]	DYNM    -A--	0x400120     0x120        0xb8         	.dynamic
142 *	6	0	0x4          0x8
143 *
144 * [4]	HASH    -A--	0x4001d8     0x1d8        0x8a0        	.hash
145 *	5	0	0x4          0x4
146 *
147 * [5]	DYNS    -A--	0x400a78     0xa78        0x11f0       	.dynsym
148 *	6	2	0x4          0x10
149 *
150 * [6]	STRT    -A--	0x401c68     0x1c68       0xbf9        	.dynstr
151 *	0	0	0x1          0
152 *
153 * [7]	REL     -A--	0x402864     0x2864       0x18         	.rel.dyn
154 *	5	14	0x4          0x8
155 *
156 * [8]	PBIT    -AI-	0x402880     0x2880       0x60         	.init
157 *	0	0	0x10         0x1
158 *
159 * [9]	PBIT    -AI-	0x4028e0     0x28e0       0x1234       	.plt
160 *	0	0	0x4          0x4
161 *
162 * [10]	PBIT    -AI-	0x403b20     0x3b20       0xee400      	.text
163 *	0	0	0x20         0x1
164 *
165 * [11]	PBIT    -AI-	0x4f1f20     0xf1f20      0x60         	.fini
166 *	0	0	0x10         0x1
167 *
168 * [12]	PBIT    -A--	0x4f1f80     0xf1f80      0xd90        	.rdata
169 *	0	0	0x10         0x1
170 *
171 * [13]	PBIT    -A--	0x4f2d10     0xf2d10      0x17e0       	.rodata
172 *	0	0	0x10         0x1
173 *
174 * [14]	PBIT    WA--	0x5344f0     0xf44f0      0x4b3e4      	.data  <<<<<
175 *	0	0	0x10         0x1
176 *
177 * [15]	PBIT    WA-G	0x57f8d4     0x13f8d4     0x2a84       	.got
178 *	0	0	0x4          0x4
179 *
180 * [16]	PBIT    WA-G	0x582360     0x142360     0x10         	.sdata <<<<<
181 *	0	0	0x10         0x1
182 *
183 * [17]	NOBI    WA-G	0x582370     0x142370     0xb84        	.sbss  <<<<<
184 *	0	0	0x4          0
185 *
186 * [18]	NOBI    WA--	0x582f00     0x142370     0x27ec0      	.bss   <<<<<
187 *	0	0	0x10         0x1
188 *
189 * [19]	SYMT    ----	0            0x142370     0x10e40      	.symtab
190 *	20	1108	0x4          0x10
191 *
192 * [20]	STRT    ----	0            0x1531b0     0xed9e       	.strtab
193 *	0	0	0x1          0
194 *
195 * [21]	STRT    ----	0            0x161f4e     0xb5         	.shstrtab
196 *	0	0	0x1          0
197 *
198 * [22]	PBIT    ----	0            0x162003     0x28e2a      	.comment
199 *	0	0	0x1          0x1
200 *
201 * [23]	PBIT    ----	0            0x18ae2d     0x592        	.debug
202 *	0	0	0x1          0
203 *
204 * [24]	PBIT    ----	0            0x18b3bf     0x80         	.line
205 *	0	0	0x1          0
206 *
207 * [25]	MDBG    ----	0            0x18b440     0x60         	.mdebug
208 *	0	0	0x4          0
209 *
210 *
211 * dump -hv emacs
212 *
213 * emacs:
214 *
215 *	   **** SECTION HEADER TABLE ****
216 * [No]	Type	Flags	Addr         Offset       Size        	Name
217 *	Link	Info	Adralgn      Entsize
218 *
219 * [1]	PBIT    -A--	0x4000f4     0xf4         0x13         	.interp
220 *	0	0	0x1          0
221 *
222 * [2]	REGI    -A--	0x400108     0x108        0x18         	.reginfo
223 *	0	0	0x4          0x18
224 *
225 * [3]	DYNM    -A--	0x400120     0x120        0xb8         	.dynamic
226 *	6	0	0x4          0x8
227 *
228 * [4]	HASH    -A--	0x4001d8     0x1d8        0x8a0        	.hash
229 *	5	0	0x4          0x4
230 *
231 * [5]	DYNS    -A--	0x400a78     0xa78        0x11f0       	.dynsym
232 *	6	2	0x4          0x10
233 *
234 * [6]	STRT    -A--	0x401c68     0x1c68       0xbf9        	.dynstr
235 *	0	0	0x1          0
236 *
237 * [7]	REL     -A--	0x402864     0x2864       0x18         	.rel.dyn
238 *	5	14	0x4          0x8
239 *
240 * [8]	PBIT    -AI-	0x402880     0x2880       0x60         	.init
241 *	0	0	0x10         0x1
242 *
243 * [9]	PBIT    -AI-	0x4028e0     0x28e0       0x1234       	.plt
244 *	0	0	0x4          0x4
245 *
246 * [10]	PBIT    -AI-	0x403b20     0x3b20       0xee400      	.text
247 *	0	0	0x20         0x1
248 *
249 * [11]	PBIT    -AI-	0x4f1f20     0xf1f20      0x60         	.fini
250 *	0	0	0x10         0x1
251 *
252 * [12]	PBIT    -A--	0x4f1f80     0xf1f80      0xd90        	.rdata
253 *	0	0	0x10         0x1
254 *
255 * [13]	PBIT    -A--	0x4f2d10     0xf2d10      0x17e0       	.rodata
256 *	0	0	0x10         0x1
257 *
258 * [14]	PBIT    WA--	0x5344f0     0xf44f0      0x4b3e4      	.data  <<<<<
259 *	0	0	0x10         0x1
260 *
261 * [15]	PBIT    WA-G	0x57f8d4     0x13f8d4     0x2a84       	.got
262 *	0	0	0x4          0x4
263 *
264 * [16]	PBIT    WA-G	0x582360     0x142360     0xb94        	.sdata <<<<<
265 *	0	0	0x10         0x1
266 *
267 * [17]	PBIT    WA--	0x582f00     0x142f00     0x94100      	.data  <<<<<
268 *	0	0	0x10         0x1
269 *
270 * [18]	NOBI    WA-G	0x617000     0x1d7000     0            	.sbss  <<<<<
271 *	0	0	0x4          0
272 *
273 * [19]	NOBI    WA--	0x617000     0x1d7000     0            	.bss   <<<<<
274 *	0	0	0x4          0x1
275 *
276 * [20]	SYMT    ----	0            0x1d7000     0x10e40      	.symtab
277 *	21	1109	0x4          0x10
278 *
279 * [21]	STRT    ----	0            0x1e7e40     0xed9e       	.strtab
280 *	0	0	0x1          0
281 *
282 * [22]	STRT    ----	0            0x1f6bde     0xb5         	.shstrtab
283 *	0	0	0x1          0
284 *
285 * [23]	PBIT    ----	0            0x1f6c93     0x28e2a      	.comment
286 *	0	0	0x1          0x1
287 *
288 * [24]	PBIT    ----	0            0x21fabd     0x592        	.debug
289 *	0	0	0x1          0
290 *
291 * [25]	PBIT    ----	0            0x22004f     0x80         	.line
292 *	0	0	0x1          0
293 *
294 * [26]	MDBG    ----	0            0x2200d0     0x60         	.mdebug
295 *	0	0	0x4          0
296 *
297 */
298
299#include <sys/types.h>
300#include <stdio.h>
301#include <sys/stat.h>
302#include <memory.h>
303#include <string.h>
304#include <errno.h>
305#include <unistd.h>
306#include <fcntl.h>
307#include <elf.h>
308#include <sys/mman.h>
309#include <assert.h>
310
311/* #define DEBUG */
312
313#ifndef emacs
314#define fatal(a, b, c) fprintf(stderr, a, b, c), exit(1)
315#else
316extern void fatal(char *, ...);
317#endif
318
319/* Get the address of a particular section or program header entry,
320 * accounting for the size of the entries.
321 */
322
323#define OLD_SECTION_H(n) \
324     (*(Elf32_Shdr *) ((byte *) old_section_h + old_file_h->e_shentsize * (n)))
325#define NEW_SECTION_H(n) \
326     (*(Elf32_Shdr *) ((byte *) new_section_h + new_file_h->e_shentsize * (n)))
327#define OLD_PROGRAM_H(n) \
328     (*(Elf32_Phdr *) ((byte *) old_program_h + old_file_h->e_phentsize * (n)))
329#define NEW_PROGRAM_H(n) \
330     (*(Elf32_Phdr *) ((byte *) new_program_h + new_file_h->e_phentsize * (n)))
331
332#define PATCH_INDEX(n) \
333  do { \
334	 if ((n) >= old_sbss_index) \
335	   (n) += 1 + (old_sdata_index ? 0 : 1); } while (0)
336
337typedef unsigned char byte;
338
339/* Round X up to a multiple of Y.  */
340
341int
342round_up (x, y)
343     int x, y;
344{
345  int rem = x % y;
346  if (rem == 0)
347    return x;
348  return x - rem + y;
349}
350
351/* ****************************************************************
352 * unexec
353 *
354 * driving logic.
355 *
356 * In ELF, this works by replacing the old .bss section with a new
357 * .data section, and inserting an empty .bss immediately afterwards.
358 *
359 */
360void
361unexec (new_name, old_name, data_start, bss_start, entry_address)
362     char *new_name, *old_name;
363     unsigned data_start, bss_start, entry_address;
364{
365  extern unsigned int bss_end;
366  int new_file, old_file, new_file_size;
367
368  /* Pointers to the base of the image of the two files. */
369  caddr_t old_base, new_base;
370
371  /* Pointers to the file, program and section headers for the old and new
372   * files.
373   */
374  Elf32_Ehdr *old_file_h, *new_file_h;
375  Elf32_Phdr *old_program_h, *new_program_h;
376  Elf32_Shdr *old_section_h, *new_section_h;
377
378  /* Point to the section name table in the old file */
379  char *old_section_names;
380
381  Elf32_Addr old_bss_addr, new_bss_addr;
382  Elf32_Addr old_sbss_addr;
383  Elf32_Word old_bss_size, new_data2_size;
384  Elf32_Word old_sbss_size, new_data3_size;
385  Elf32_Off  new_data2_offset;
386  Elf32_Off  new_data3_offset;
387  Elf32_Addr new_data2_addr;
388  Elf32_Addr new_data3_addr;
389
390
391  Elf32_Addr old_rel_dyn_addr;
392  Elf32_Word old_rel_dyn_size;
393  int old_rel_dyn_index;
394
395  Elf32_Word old_sdata_size, new_sdata_size;
396  int old_sdata_index = 0;
397
398  int n, nn, old_data_index, new_data2_align;
399  int old_bss_index;
400  int old_sbss_index;
401  int old_bss_padding;
402  struct stat stat_buf;
403
404  /* Open the old file & map it into the address space. */
405
406  old_file = open (old_name, O_RDONLY);
407
408  if (old_file < 0)
409    fatal ("Can't open %s for reading: errno %d\n", old_name, errno);
410
411  if (fstat (old_file, &stat_buf) == -1)
412    fatal ("Can't fstat(%s): errno %d\n", old_name, errno);
413
414  old_base = mmap (0, stat_buf.st_size, PROT_READ, MAP_SHARED, old_file, 0);
415
416  if (old_base == (caddr_t) -1)
417    fatal ("Can't mmap(%s): errno %d\n", old_name, errno);
418
419#ifdef DEBUG
420  fprintf (stderr, "mmap(%s, %x) -> %x\n", old_name, stat_buf.st_size,
421	   old_base);
422#endif
423
424  /* Get pointers to headers & section names */
425
426  old_file_h = (Elf32_Ehdr *) old_base;
427  old_program_h = (Elf32_Phdr *) ((byte *) old_base + old_file_h->e_phoff);
428  old_section_h = (Elf32_Shdr *) ((byte *) old_base + old_file_h->e_shoff);
429  old_section_names = (char *) old_base
430    + OLD_SECTION_H(old_file_h->e_shstrndx).sh_offset;
431
432  /* Find the old .sbss section.
433   */
434
435  for (old_sbss_index = 1; old_sbss_index < old_file_h->e_shnum;
436       old_sbss_index++)
437    {
438#ifdef DEBUG
439      fprintf (stderr, "Looking for .sbss - found %s\n",
440	       old_section_names + OLD_SECTION_H(old_sbss_index).sh_name);
441#endif
442      if (!strcmp (old_section_names + OLD_SECTION_H(old_sbss_index).sh_name,
443		   ".sbss"))
444	break;
445    }
446  if (old_sbss_index == old_file_h->e_shnum)
447    fatal ("Can't find .sbss in %s.\n", old_name, 0);
448
449  if (!strcmp(old_section_names + OLD_SECTION_H(old_sbss_index - 1).sh_name,
450	       ".sdata"))
451    {
452      old_sdata_index = old_sbss_index - 1;
453    }
454
455
456  /* Find the old .bss section.
457   */
458
459  for (old_bss_index = 1; old_bss_index < old_file_h->e_shnum; old_bss_index++)
460    {
461#ifdef DEBUG
462      fprintf (stderr, "Looking for .bss - found %s\n",
463	       old_section_names + OLD_SECTION_H(old_bss_index).sh_name);
464#endif
465      if (!strcmp (old_section_names + OLD_SECTION_H(old_bss_index).sh_name,
466		   ".bss"))
467	break;
468    }
469  if (old_bss_index == old_file_h->e_shnum)
470    fatal ("Can't find .bss in %s.\n", old_name, 0);
471
472  if (old_sbss_index != (old_bss_index - 1))
473    fatal (".sbss should come immediately before .bss in %s.\n", old_name, 0);
474
475  /* Find the old .rel.dyn section.
476   */
477
478  for (old_rel_dyn_index = 1; old_rel_dyn_index < old_file_h->e_shnum;
479       old_rel_dyn_index++)
480    {
481#ifdef DEBUG
482      fprintf (stderr, "Looking for .rel.dyn - found %s\n",
483	       old_section_names + OLD_SECTION_H(old_rel_dyn_index).sh_name);
484#endif
485      if (!strcmp (old_section_names + OLD_SECTION_H(old_rel_dyn_index).sh_name,
486		   ".rel.dyn"))
487	break;
488    }
489  if (old_rel_dyn_index == old_file_h->e_shnum)
490    fatal ("Can't find .rel_dyn in %s.\n", old_name, 0);
491
492  old_rel_dyn_addr = OLD_SECTION_H(old_rel_dyn_index).sh_addr;
493  old_rel_dyn_size = OLD_SECTION_H(old_rel_dyn_index).sh_size;
494
495  /* Figure out parameters of the new data3 and data2 sections.
496   * Change the sbss and bss sections.
497   */
498
499  old_bss_addr = OLD_SECTION_H(old_bss_index).sh_addr;
500  old_bss_size = OLD_SECTION_H(old_bss_index).sh_size;
501
502  old_sbss_addr = OLD_SECTION_H(old_sbss_index).sh_addr;
503  old_sbss_size = OLD_SECTION_H(old_sbss_index).sh_size;
504
505  if (old_sdata_index)
506    {
507    old_sdata_size = OLD_SECTION_H(old_sdata_index).sh_size;
508    }
509
510#if defined(emacs) || !defined(DEBUG)
511  bss_end = (unsigned int) sbrk (0);
512  new_bss_addr = (Elf32_Addr) bss_end;
513#else
514  new_bss_addr = old_bss_addr + old_bss_size + 0x1234;
515#endif
516  if (old_sdata_index)
517    {
518    new_sdata_size = OLD_SECTION_H(old_sbss_index).sh_offset -
519		     OLD_SECTION_H(old_sdata_index).sh_offset + old_sbss_size;
520    }
521
522  new_data3_addr = old_sbss_addr;
523  new_data3_size = old_sbss_size;
524  new_data3_offset = OLD_SECTION_H(old_sbss_index).sh_offset;
525
526  new_data2_addr = old_bss_addr;
527  new_data2_size = new_bss_addr - old_bss_addr;
528  new_data2_align = (new_data3_offset + old_sbss_size) %
529		    OLD_SECTION_H(old_bss_index).sh_addralign;
530  new_data2_align = new_data2_align ?
531		    OLD_SECTION_H(old_bss_index).sh_addralign - new_data2_align :
532		    0;
533  new_data2_offset = new_data3_offset + old_sbss_size + new_data2_align;
534
535  old_bss_padding = OLD_SECTION_H(old_bss_index).sh_offset -
536		    OLD_SECTION_H(old_sbss_index).sh_offset;
537#ifdef DEBUG
538  fprintf (stderr, "old_bss_index %d\n", old_bss_index);
539  fprintf (stderr, "old_bss_addr %x\n", old_bss_addr);
540  fprintf (stderr, "old_bss_size %x\n", old_bss_size);
541  fprintf (stderr, "new_bss_addr %x\n", new_bss_addr);
542  fprintf (stderr, "new_data2_addr %x\n", new_data2_addr);
543  fprintf (stderr, "new_data2_size %x\n", new_data2_size);
544  fprintf (stderr, "new_data2_offset %x\n", new_data2_offset);
545  fprintf (stderr, "old_sbss_index %d\n", old_sbss_index);
546  fprintf (stderr, "old_sbss_addr %x\n", old_sbss_addr);
547  fprintf (stderr, "old_sbss_size %x\n", old_sbss_size);
548  fprintf (stderr, "old_rel_dyn_addr %x\n", old_rel_dyn_addr);
549  fprintf (stderr, "old_rel_dyn_size %x\n", old_rel_dyn_size);
550  if (old_sdata_index)
551    {
552    fprintf (stderr, "old_sdata_size %x\n", old_sdata_size);
553    fprintf (stderr, "new_sdata_size %x\n", new_sdata_size);
554    }
555  else
556    {
557    fprintf (stderr, "new_data3_addr %x\n", new_data3_addr);
558    fprintf (stderr, "new_data3_size %x\n", new_data3_size);
559    fprintf (stderr, "new_data3_offset %x\n", new_data3_offset);
560    }
561#endif
562
563  if ((unsigned) new_bss_addr < (unsigned) old_bss_addr + old_bss_size)
564    fatal (".bss shrank when undumping???\n", 0, 0);
565
566  /* Set the output file to the right size and mmap(2) it.  Set
567   * pointers to various interesting objects.  stat_buf still has
568   * old_file data.
569   */
570
571  new_file = open (new_name, O_RDWR | O_CREAT, 0666);
572  if (new_file < 0)
573    fatal ("Can't creat(%s): errno %d\n", new_name, errno);
574
575  new_file_size = stat_buf.st_size +
576		  ((1 + (old_sdata_index ? 0 : 1)) * old_file_h->e_shentsize) +
577		  new_data2_size + new_data3_size + new_data2_align;
578
579  if (ftruncate (new_file, new_file_size))
580    fatal ("Can't ftruncate(%s): errno %d\n", new_name, errno);
581
582  new_base = mmap (0, new_file_size, PROT_READ | PROT_WRITE, MAP_SHARED,
583		   new_file, 0);
584
585  if (new_base == (caddr_t) -1)
586    fatal ("Can't mmap(%s): errno %d\n", new_name, errno);
587
588  new_file_h = (Elf32_Ehdr *) new_base;
589  new_program_h = (Elf32_Phdr *) ((byte *) new_base + old_file_h->e_phoff);
590  new_section_h = (Elf32_Shdr *) ((byte *) new_base +
591				  old_file_h->e_shoff +
592				  new_data2_size +
593				  new_data2_align +
594				  new_data3_size);
595
596  /* Make our new file, program and section headers as copies of the
597   * originals.
598   */
599
600  memcpy (new_file_h, old_file_h, old_file_h->e_ehsize);
601  memcpy (new_program_h, old_program_h,
602	  old_file_h->e_phnum * old_file_h->e_phentsize);
603
604  /* Modify the e_shstrndx if necessary. */
605  PATCH_INDEX (new_file_h->e_shstrndx);
606
607  /* Fix up file header.  We'll add one section.  Section header is
608   * further away now.
609   */
610
611  new_file_h->e_shoff += new_data2_size + new_data2_align + new_data3_size;
612  new_file_h->e_shnum += 1 + (old_sdata_index ? 0 : 1);
613
614#ifdef DEBUG
615  fprintf (stderr, "Old section offset %x\n", old_file_h->e_shoff);
616  fprintf (stderr, "Old section count %d\n", old_file_h->e_shnum);
617  fprintf (stderr, "New section offset %x\n", new_file_h->e_shoff);
618  fprintf (stderr, "New section count %d\n", new_file_h->e_shnum);
619#endif
620
621  /* Fix up a new program header.  Extend the writable data segment so
622   * that the bss area is covered too. Find that segment by looking
623   * for a segment that ends just before the .bss area.  Make sure
624   * that no segments are above the new .data2.  Put a loop at the end
625   * to adjust the offset and address of any segment that is above
626   * data2, just in case we decide to allow this later.
627   */
628
629  for (n = new_file_h->e_phnum - 1; n >= 0; n--)
630    {
631      /* Compute maximum of all requirements for alignment of section.  */
632      int alignment = (NEW_PROGRAM_H (n)).p_align;
633      if ((OLD_SECTION_H (old_bss_index)).sh_addralign > alignment)
634	alignment = OLD_SECTION_H (old_bss_index).sh_addralign;
635
636      if ((OLD_SECTION_H (old_sbss_index)).sh_addralign > alignment)
637	alignment = OLD_SECTION_H (old_sbss_index).sh_addralign;
638
639      /* Supposedly this condition is okay for the SGI.  */
640#if 0
641      if (NEW_PROGRAM_H(n).p_vaddr + NEW_PROGRAM_H(n).p_filesz > old_bss_addr)
642	fatal ("Program segment above .bss in %s\n", old_name, 0);
643#endif
644
645      if (NEW_PROGRAM_H(n).p_type == PT_LOAD
646	  && (round_up ((NEW_PROGRAM_H (n)).p_vaddr
647			+ (NEW_PROGRAM_H (n)).p_filesz,
648			alignment)
649	      == round_up (old_bss_addr, alignment)))
650	break;
651    }
652  if (n < 0)
653    fatal ("Couldn't find segment next to .bss in %s\n", old_name, 0);
654
655  NEW_PROGRAM_H(n).p_filesz += new_data2_size + new_data2_align +
656    new_data3_size;
657  NEW_PROGRAM_H(n).p_memsz = NEW_PROGRAM_H(n).p_filesz;
658
659#if 1 /* Maybe allow section after data2 - does this ever happen? */
660  for (n = new_file_h->e_phnum - 1; n >= 0; n--)
661    {
662      if (NEW_PROGRAM_H(n).p_vaddr
663	  && NEW_PROGRAM_H(n).p_vaddr >= new_data3_addr)
664	NEW_PROGRAM_H(n).p_vaddr += new_data2_size - old_bss_size +
665				    new_data3_size - old_sbss_size;
666
667      if (NEW_PROGRAM_H(n).p_offset >= new_data3_offset)
668	NEW_PROGRAM_H(n).p_offset += new_data2_size + new_data2_align +
669	  new_data3_size;
670    }
671#endif
672
673  /* Fix up section headers based on new .data2 section.  Any section
674   * whose offset or virtual address is after the new .data2 section
675   * gets its value adjusted.  .bss size becomes zero and new address
676   * is set.  data2 section header gets added by copying the existing
677   * .data header and modifying the offset, address and size.
678   */
679  for (old_data_index = 1; old_data_index < old_file_h->e_shnum;
680       old_data_index++)
681    if (!strcmp (old_section_names + OLD_SECTION_H(old_data_index).sh_name,
682		 ".data"))
683      break;
684  if (old_data_index == old_file_h->e_shnum)
685    fatal ("Can't find .data in %s.\n", old_name, 0);
686
687  /* Walk through all section headers, insert the new data2 section right
688     before the new bss section. */
689  for (n = 1, nn = 1; n < old_file_h->e_shnum; n++, nn++)
690    {
691      caddr_t src;
692
693      if (n == old_sbss_index)
694
695      /* If it is sbss section, insert the new data3 section before it. */
696	{
697	  /* Steal the data section header for this data3 section. */
698	  if (!old_sdata_index)
699	    {
700	    memcpy (&NEW_SECTION_H(nn), &OLD_SECTION_H(old_data_index),
701		    new_file_h->e_shentsize);
702
703	    NEW_SECTION_H(nn).sh_addr = new_data3_addr;
704	    NEW_SECTION_H(nn).sh_offset = new_data3_offset;
705	    NEW_SECTION_H(nn).sh_size = new_data3_size;
706	    NEW_SECTION_H(nn).sh_flags = OLD_SECTION_H(n).sh_flags;
707	    /* Use the sbss section's alignment. This will assure that the
708	       new data3 section always be placed in the same spot as the old
709	       sbss section by any other application. */
710	    NEW_SECTION_H(nn).sh_addralign = OLD_SECTION_H(n).sh_addralign;
711
712	    /* Now copy over what we have in the memory now. */
713	    memcpy (NEW_SECTION_H(nn).sh_offset + new_base,
714		    (caddr_t) OLD_SECTION_H(n).sh_addr,
715		    new_data3_size);
716		  /* the new .data2 section should also come before the
717		   * new .sbss section */
718	    nn += 2;
719	    }
720	  else
721	    {
722	    /* We always have a .sdata section: append the contents of the
723	     * old .sbss section.
724	     */
725	    memcpy (new_data3_offset + new_base,
726		    (caddr_t) OLD_SECTION_H(n).sh_addr,
727		    new_data3_size);
728	    nn ++;
729	    }
730	}
731      else if (n == old_bss_index)
732
733      /* If it is bss section, insert the new data2 section before it. */
734	{
735	  Elf32_Word tmp_align;
736	  Elf32_Addr tmp_addr;
737
738	  tmp_align = OLD_SECTION_H(n).sh_addralign;
739	  tmp_addr = OLD_SECTION_H(n).sh_addr;
740
741	  nn -= 2;
742	  /* Steal the data section header for this data2 section. */
743	  memcpy (&NEW_SECTION_H(nn), &OLD_SECTION_H(old_data_index),
744		  new_file_h->e_shentsize);
745
746	  NEW_SECTION_H(nn).sh_addr = new_data2_addr;
747	  NEW_SECTION_H(nn).sh_offset = new_data2_offset;
748	  NEW_SECTION_H(nn).sh_size = new_data2_size;
749	  /* Use the bss section's alignment. This will assure that the
750	     new data2 section always be placed in the same spot as the old
751	     bss section by any other application. */
752	  NEW_SECTION_H(nn).sh_addralign = tmp_align;
753
754	  /* Now copy over what we have in the memory now. */
755	  memcpy (NEW_SECTION_H(nn).sh_offset + new_base,
756		  (caddr_t) tmp_addr, new_data2_size);
757	  nn += 2;
758	}
759
760      memcpy (&NEW_SECTION_H(nn), &OLD_SECTION_H(n),
761	      old_file_h->e_shentsize);
762
763      if (old_sdata_index && n == old_sdata_index)
764	/* The old .sdata section has now a new size */
765	NEW_SECTION_H(nn).sh_size = new_sdata_size;
766
767      /* The new bss section's size is zero, and its file offset and virtual
768	 address should be off by NEW_DATA2_SIZE. */
769      if (n == old_sbss_index)
770	{
771	  /* NN should be `old_sbss_index + 2' at this point. */
772	  NEW_SECTION_H(nn).sh_offset += new_data2_size + new_data2_align +
773	    new_data3_size;
774	  NEW_SECTION_H(nn).sh_addr += new_data2_size + new_data2_align +
775	    new_data3_size;
776	  /* Let the new bss section address alignment be the same as the
777	     section address alignment followed the old bss section, so
778	     this section will be placed in exactly the same place. */
779	  NEW_SECTION_H(nn).sh_addralign =
780	    OLD_SECTION_H(nn + (old_sdata_index ? 1 : 0)).sh_addralign;
781	  NEW_SECTION_H(nn).sh_size = 0;
782	}
783      else if (n == old_bss_index)
784	{
785	  /* NN should be `old_bss_index + 2' at this point. */
786	  NEW_SECTION_H(nn).sh_offset += new_data2_size + new_data2_align +
787	    new_data3_size - old_bss_padding;
788	  NEW_SECTION_H(nn).sh_addr += new_data2_size;
789	  /* Let the new bss section address alignment be the same as the
790	     section address alignment followed the old bss section, so
791	     this section will be placed in exactly the same place. */
792	  NEW_SECTION_H(nn).sh_addralign =
793	    OLD_SECTION_H((nn - (old_sdata_index ? 0 : 1))).sh_addralign;
794	  NEW_SECTION_H(nn).sh_size = 0;
795	}
796      /* Any section that was original placed AFTER the bss section should now
797	 be off by NEW_DATA2_SIZE. */
798      else if (NEW_SECTION_H(nn).sh_offset >= new_data3_offset)
799	NEW_SECTION_H(nn).sh_offset += new_data2_size +
800				       new_data2_align +
801				       new_data3_size -
802				       old_bss_padding;
803
804      /* If any section hdr refers to the section after the new .data
805	 section, make it refer to next one because we have inserted
806	 a new section in between. */
807
808      PATCH_INDEX(NEW_SECTION_H(nn).sh_link);
809      PATCH_INDEX(NEW_SECTION_H(nn).sh_info);
810
811      /* Now, start to copy the content of sections. */
812      if (NEW_SECTION_H(nn).sh_type == SHT_NULL
813	  || NEW_SECTION_H(nn).sh_type == SHT_NOBITS)
814	continue;
815
816      /* Write out the sections. .data, .data1 and .sdata get copied from
817       * the current process instead of the old file.
818       */
819      if (!strcmp (old_section_names + OLD_SECTION_H(n).sh_name, ".data") ||
820	  !strcmp (old_section_names + OLD_SECTION_H(n).sh_name, ".data1") ||
821	  (old_sdata_index && (n == old_sdata_index)))
822	src = (caddr_t) OLD_SECTION_H(n).sh_addr;
823      else
824	src = old_base + OLD_SECTION_H(n).sh_offset;
825
826      memcpy (NEW_SECTION_H(nn).sh_offset + new_base, src,
827	      ((n == old_sdata_index) ?
828	       old_sdata_size :
829	       NEW_SECTION_H(nn).sh_size));
830
831      /* If it is the symbol table, its st_shndx field needs to be patched. */
832      if (NEW_SECTION_H(nn).sh_type == SHT_SYMTAB
833	  || NEW_SECTION_H(nn).sh_type == SHT_DYNSYM)
834	{
835	  Elf32_Shdr *spt = &NEW_SECTION_H(nn);
836	  unsigned int num = spt->sh_size / spt->sh_entsize;
837	  Elf32_Sym * sym = (Elf32_Sym *) (NEW_SECTION_H(nn).sh_offset +
838					   new_base);
839	  for (; num--; sym++)
840	    {
841	      if ((sym->st_shndx == SHN_UNDEF)
842		  || (sym->st_shndx == SHN_ABS)
843		  || (sym->st_shndx == SHN_COMMON))
844		continue;
845
846	      PATCH_INDEX(sym->st_shndx);
847	    }
848	}
849    }
850  {
851    Elf32_Rel *rel_p;
852    unsigned int old_data_addr_start;
853    unsigned int old_data_addr_end;
854    unsigned int old_data_offset;
855    unsigned int new_data_offset;
856    int i;
857
858    rel_p = (Elf32_Rel *)OLD_SECTION_H(old_rel_dyn_index).sh_addr;
859    old_data_addr_start = OLD_SECTION_H(old_data_index).sh_addr;
860    old_data_addr_end = old_data_addr_start +
861      OLD_SECTION_H(old_data_index).sh_size;
862    old_data_offset = (int)OLD_SECTION_H(old_data_index).sh_offset +
863      (unsigned int)old_base;
864    new_data_offset = (int)NEW_SECTION_H(old_data_index).sh_offset +
865      (unsigned int)new_base;
866
867#ifdef DEBUG
868    fprintf(stderr, "old_data.sh_addr= 0x%08x ... 0x%08x\n", old_data_addr_start,
869	    old_data_addr_end);
870#endif /* DEBUG */
871
872    for (i = 0; i < old_rel_dyn_size/sizeof(Elf32_Rel); i++)
873      {
874#ifdef DEBUG
875	fprintf(stderr, ".rel.dyn offset= 0x%08x  type= %d  sym= %d\n",
876		rel_p->r_offset, ELF32_R_TYPE(rel_p->r_info), ELF32_R_SYM(rel_p->r_info));
877#endif /* DEBUG */
878
879	if (rel_p->r_offset)
880	  {
881	    unsigned int offset;
882
883	    assert(old_data_addr_start <= rel_p->r_offset &&
884		   rel_p->r_offset <= old_data_addr_end);
885
886	    offset = rel_p->r_offset - old_data_addr_start;
887
888#ifdef DEBUG
889	    fprintf(stderr, "r_offset= 0x%08x  *r_offset= 0x%08x\n",
890		    rel_p->r_offset, *((int *)(rel_p->r_offset)));
891	    fprintf(stderr, "old     = 0x%08x  *old     =0x%08x\n",
892		    (old_data_offset + offset - (unsigned int)old_base),
893		    *((int *)(old_data_offset + offset)));
894	    fprintf(stderr, "new     = 0x%08x  *new     =0x%08x\n",
895		    (new_data_offset + offset - (unsigned int)new_base),
896		    *((int *)(new_data_offset + offset)));
897#endif /* DEBUG */
898
899	    *((int *)(new_data_offset + offset)) = *((int *)(old_data_offset + offset));
900	  }
901
902	rel_p++;
903      }
904  }
905
906  /* Close the files and make the new file executable */
907
908  if (close (old_file))
909    fatal ("Can't close(%s): errno %d\n", old_name, errno);
910
911  if (close (new_file))
912    fatal ("Can't close(%s): errno %d\n", new_name, errno);
913
914  if (stat (new_name, &stat_buf) == -1)
915    fatal ("Can't stat(%s): errno %d\n", new_name, errno);
916
917  n = umask (777);
918  umask (n);
919  stat_buf.st_mode |= 0111 & ~n;
920  if (chmod (new_name, stat_buf.st_mode) == -1)
921    fatal ("Can't chmod(%s): errno %d\n", new_name, errno);
922}
923
924/* arch-tag: c784ead3-7a27-442b-83fe-7af8d08654d3
925   (do not change this comment) */
926