elf2ecoff.c revision 1.29
1/*	$NetBSD: elf2ecoff.c,v 1.29 2013/11/10 17:14:25 christos Exp $	*/
2
3/*
4 * Copyright (c) 1997 Jonathan Stone
5 *    All rights reserved.
6 * Copyright (c) 1995
7 *	Ted Lemon (hereinafter referred to as the author)
8 *
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
11 * are met:
12 * 1. Redistributions of source code must retain the above copyright
13 *    notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 *    notice, this list of conditions and the following disclaimer in the
16 *    documentation and/or other materials provided with the distribution.
17 * 3. The name of the author may not be used to endorse or promote products
18 *    derived from this software without specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * SUCH DAMAGE.
31 */
32
33/* elf2ecoff.c
34
35   This program converts an elf executable to an ECOFF executable.
36   No symbol table is retained.   This is useful primarily in building
37   net-bootable kernels for machines (e.g., DECstation and Alpha) which
38   only support the ECOFF object file format. */
39
40#if HAVE_NBTOOL_CONFIG_H
41#include "nbtool_config.h"
42#endif
43
44#include <sys/types.h>
45#include <err.h>
46#include <errno.h>
47#include <fcntl.h>
48#include <unistd.h>
49#include <sys/exec_elf.h>
50#include <stdio.h>
51#include <sys/exec_ecoff.h>
52#include <stdlib.h>
53#include <string.h>
54#include <limits.h>
55
56#define	ISLAST(p)	(p->n_un.n_name == 0 || p->n_un.n_name[0] == 0)
57
58struct sect {
59	unsigned long vaddr;
60	unsigned long len;
61};
62
63struct elf_syms {
64	int     nsymbols;
65	Elf32_Sym *elf_syms;
66	off_t   stringsize;
67	char   *stringtab;
68};
69
70struct ecoff_syms {
71	int     nsymbols;
72	struct ecoff_extsym *ecoff_syms;
73	off_t   stringsize;
74	char   *stringtab;
75};
76
77static int     debug = 0;
78static int     needswap;
79
80static int     phcmp(Elf32_Phdr *, Elf32_Phdr *);
81static char   *saveRead(int, off_t, off_t, const char *);
82static void    safewrite(int, const void *, off_t, const char *);
83static void    copy(int, int, off_t, off_t);
84static void    combine(struct sect *, struct sect *, int);
85static void    translate_syms(struct elf_syms *, struct ecoff_syms *);
86static void    elf_symbol_table_to_ecoff(int, int, struct ecoff_exechdr *,
87    off_t, off_t, off_t, off_t);
88static int     make_ecoff_section_hdrs(struct ecoff_exechdr *,
89    struct ecoff_scnhdr *);
90static void    write_ecoff_symhdr(int, struct ecoff_exechdr *,
91    struct ecoff_symhdr *, long, long, long, long);
92static void    pad16(int, int, const char *);
93static void    bswap32_region(int32_t* , int);
94static void    elf_read_syms(struct elf_syms *, int, off_t, off_t, off_t,
95    off_t);
96
97
98int
99main(int argc, char **argv)
100{
101	Elf32_Ehdr ex;
102	Elf32_Phdr *ph;
103	Elf32_Shdr *sh;
104	char   *shstrtab;
105	int     strtabix, symtabix;
106	size_t	i;
107	int     pad;
108	struct sect text, data, bss;	/* a.out-compatible sections */
109
110	struct ecoff_exechdr ep;
111	struct ecoff_scnhdr esecs[6];
112	struct ecoff_symhdr symhdr;
113
114	int     infile, outfile;
115	unsigned long cur_vma = ULONG_MAX;
116	int     nsecs = 0;
117	int	mipsel;
118
119
120	text.len = data.len = bss.len = 0;
121	text.vaddr = data.vaddr = bss.vaddr = 0;
122
123	/* Check args... */
124	if (argc < 3 || argc > 4) {
125usage:
126		fprintf(stderr,
127		    "Usage: %s <elf executable> <ECOFF executable> [-s]\n",
128		    getprogname());
129		exit(1);
130	}
131	if (argc == 4) {
132		if (strcmp(argv[3], "-s"))
133			goto usage;
134	}
135	/* Try the input file... */
136	if ((infile = open(argv[1], O_RDONLY)) < 0)
137		err(1, "Can't open %s for read", argv[1]);
138	/* Read the header, which is at the beginning of the file... */
139	i = read(infile, &ex, sizeof ex);
140	if (i != sizeof ex)
141		err(1, "Short header read from %s", argv[1]);
142	if (ex.e_ident[EI_DATA] == ELFDATA2LSB)
143		mipsel = 1;
144	else if (ex.e_ident[EI_DATA] == ELFDATA2MSB)
145		mipsel = 0;
146	else
147		errx(1, "invalid ELF byte order %d", ex.e_ident[EI_DATA]);
148#if BYTE_ORDER == BIG_ENDIAN
149	if (mipsel)
150		needswap = 1;
151	else
152		needswap = 0;
153#elif BYTE_ORDER == LITTLE_ENDIAN
154	if (mipsel)
155		needswap = 0;
156	else
157		needswap = 1;
158#else
159#error "unknown endian"
160#endif
161
162	if (needswap) {
163		ex.e_type	= bswap16(ex.e_type);
164		ex.e_machine	= bswap16(ex.e_machine);
165		ex.e_version	= bswap32(ex.e_version);
166		ex.e_entry 	= bswap32(ex.e_entry);
167		ex.e_phoff	= bswap32(ex.e_phoff);
168		ex.e_shoff	= bswap32(ex.e_shoff);
169		ex.e_flags	= bswap32(ex.e_flags);
170		ex.e_ehsize	= bswap16(ex.e_ehsize);
171		ex.e_phentsize	= bswap16(ex.e_phentsize);
172		ex.e_phnum	= bswap16(ex.e_phnum);
173		ex.e_shentsize	= bswap16(ex.e_shentsize);
174		ex.e_shnum	= bswap16(ex.e_shnum);
175		ex.e_shstrndx	= bswap16(ex.e_shstrndx);
176	}
177
178	/* Read the program headers... */
179	ph = (Elf32_Phdr *) saveRead(infile, ex.e_phoff,
180	    ex.e_phnum * sizeof(Elf32_Phdr), "ph");
181	if (needswap)
182		bswap32_region((int32_t*)ph, sizeof(Elf32_Phdr) * ex.e_phnum);
183	/* Read the section headers... */
184	sh = (Elf32_Shdr *) saveRead(infile, ex.e_shoff,
185	    ex.e_shnum * sizeof(Elf32_Shdr), "sh");
186	if (needswap)
187		bswap32_region((int32_t*)sh, sizeof(Elf32_Shdr) * ex.e_shnum);
188
189	/* Read in the section string table. */
190	shstrtab = saveRead(infile, sh[ex.e_shstrndx].sh_offset,
191	    sh[ex.e_shstrndx].sh_size, "shstrtab");
192
193
194	/* Look for the symbol table and string table... Also map section
195	 * indices to symbol types for a.out */
196	symtabix = 0;
197	strtabix = 0;
198	for (i = 0; i < ex.e_shnum; i++) {
199		char   *name = shstrtab + sh[i].sh_name;
200		if (!strcmp(name, ".symtab"))
201			symtabix = i;
202		else
203			if (!strcmp(name, ".strtab"))
204				strtabix = i;
205
206	}
207
208	/*
209	 * Figure out if we can cram the program header into an ECOFF
210	 * header...  Basically, we can't handle anything but loadable
211	 * segments, but we can ignore some kinds of segments.  We can't
212	 * handle holes in the address space.  Segments may be out of order,
213	 * so we sort them first.
214	 */
215
216	qsort(ph, ex.e_phnum, sizeof(Elf32_Phdr),
217	    (int (*) (const void *, const void *)) phcmp);
218
219	for (i = 0; i < ex.e_phnum; i++) {
220		/* Section types we can ignore... */
221		if (ph[i].p_type == PT_NULL || ph[i].p_type == PT_NOTE ||
222		    ph[i].p_type == PT_PHDR ||
223		    ph[i].p_type == PT_MIPS_REGINFO) {
224
225			if (debug) {
226				fprintf(stderr, "  skipping PH %zu type %d "
227				    "flags 0x%x\n",
228				    i, ph[i].p_type, ph[i].p_flags);
229			}
230			continue;
231		}
232		/* Section types we can't handle... */
233		else
234			if (ph[i].p_type != PT_LOAD)
235				errx(1, "Program header %zu type %d can't be "
236				    "converted", i, ph[i].p_type);
237		/* Writable (data) segment? */
238		if (ph[i].p_flags & PF_W) {
239			struct sect ndata, nbss;
240
241			ndata.vaddr = ph[i].p_vaddr;
242			ndata.len = ph[i].p_filesz;
243			nbss.vaddr = ph[i].p_vaddr + ph[i].p_filesz;
244			nbss.len = ph[i].p_memsz - ph[i].p_filesz;
245
246			if (debug) {
247				fprintf(stderr, "  combinining PH %zu type %d "
248				    "flags 0x%x with data, ndata = %ld, "
249				    "nbss =%ld\n", i, ph[i].p_type,
250				    ph[i].p_flags, ndata.len, nbss.len);
251			}
252			combine(&data, &ndata, 0);
253			combine(&bss, &nbss, 1);
254		} else {
255			struct sect ntxt;
256
257			ntxt.vaddr = ph[i].p_vaddr;
258			ntxt.len = ph[i].p_filesz;
259			if (debug) {
260				fprintf(stderr, "  combinining PH %zu type %d "
261				    "flags 0x%x with text, len = %ld\n",
262				    i, ph[i].p_type, ph[i].p_flags, ntxt.len);
263			}
264			combine(&text, &ntxt, 0);
265		}
266		/* Remember the lowest segment start address. */
267		if (ph[i].p_vaddr < cur_vma)
268			cur_vma = ph[i].p_vaddr;
269	}
270
271	/* Sections must be in order to be converted... */
272	if (text.vaddr > data.vaddr || data.vaddr > bss.vaddr ||
273	    text.vaddr + text.len > data.vaddr ||
274	    data.vaddr + data.len > bss.vaddr)
275		errx(1, "Sections ordering prevents a.out conversion");
276	/* If there's a data section but no text section, then the loader
277	 * combined everything into one section.   That needs to be the text
278	 * section, so just make the data section zero length following text. */
279	if (data.len && text.len == 0) {
280		text = data;
281		data.vaddr = text.vaddr + text.len;
282		data.len = 0;
283	}
284	/* If there is a gap between text and data, we'll fill it when we copy
285	 * the data, so update the length of the text segment as represented
286	 * in a.out to reflect that, since a.out doesn't allow gaps in the
287	 * program address space. */
288	if (text.vaddr + text.len < data.vaddr)
289		text.len = data.vaddr - text.vaddr;
290
291	/* We now have enough information to cons up an a.out header... */
292	ep.a.magic = ECOFF_OMAGIC;
293	ep.a.vstamp = 2 * 256 + 10;	/* compatible with version 2.10 */
294	ep.a.tsize = text.len;
295	ep.a.dsize = data.len;
296	ep.a.bsize = bss.len;
297	ep.a.entry = ex.e_entry;
298	ep.a.text_start = text.vaddr;
299	ep.a.data_start = data.vaddr;
300	ep.a.bss_start = bss.vaddr;
301	ep.a.gprmask = 0xf3fffffe;
302	memset(&ep.a.cprmask, 0, sizeof ep.a.cprmask);
303	ep.a.gp_value = 0;	/* unused. */
304
305	if (mipsel)
306		ep.f.f_magic = ECOFF_MAGIC_MIPSEL;
307	else
308		ep.f.f_magic = ECOFF_MAGIC_MIPSEB;
309
310	ep.f.f_nscns = 6;
311	ep.f.f_timdat = 0;	/* bogus */
312	ep.f.f_symptr = 0;
313	ep.f.f_nsyms = sizeof(struct ecoff_symhdr);
314	ep.f.f_opthdr = sizeof ep.a;
315	ep.f.f_flags = 0x100f;	/* Stripped, not sharable. */
316
317	memset(esecs, 0, sizeof(esecs));
318
319	/* Make  ECOFF section headers, with empty stubs for
320	 * .rdata/.sdata/.sbss. */
321	make_ecoff_section_hdrs(&ep, esecs);
322
323	nsecs = ep.f.f_nscns;
324
325	if (needswap) {
326		ep.f.f_magic	= bswap16(ep.f.f_magic);
327		ep.f.f_nscns	= bswap16(ep.f.f_nscns);
328		ep.f.f_timdat	= bswap32(ep.f.f_timdat);
329		ep.f.f_symptr	= bswap32(ep.f.f_symptr);
330		ep.f.f_nsyms	= bswap32(ep.f.f_nsyms);
331		ep.f.f_opthdr	= bswap16(ep.f.f_opthdr);
332		ep.f.f_flags	= bswap16(ep.f.f_flags);
333		ep.a.magic	= bswap16(ep.a.magic);
334		ep.a.vstamp	= bswap16(ep.a.vstamp);
335		ep.a.tsize	= bswap32(ep.a.tsize);
336		ep.a.dsize	= bswap32(ep.a.dsize);
337		ep.a.bsize	= bswap32(ep.a.bsize);
338		ep.a.entry	= bswap32(ep.a.entry);
339		ep.a.text_start	= bswap32(ep.a.text_start);
340		ep.a.data_start	= bswap32(ep.a.data_start);
341		ep.a.bss_start	= bswap32(ep.a.bss_start);
342		ep.a.gprmask	= bswap32(ep.a.gprmask);
343		bswap32_region((int32_t*)ep.a.cprmask, sizeof(ep.a.cprmask));
344		ep.a.gp_value	= bswap32(ep.a.gp_value);
345		for (i = 0; i < sizeof(esecs) / sizeof(esecs[0]); i++) {
346			esecs[i].s_paddr	= bswap32(esecs[i].s_paddr);
347			esecs[i].s_vaddr	= bswap32(esecs[i].s_vaddr);
348			esecs[i].s_size 	= bswap32(esecs[i].s_size);
349			esecs[i].s_scnptr	= bswap32(esecs[i].s_scnptr);
350			esecs[i].s_relptr	= bswap32(esecs[i].s_relptr);
351			esecs[i].s_lnnoptr	= bswap32(esecs[i].s_lnnoptr);
352			esecs[i].s_nreloc	= bswap16(esecs[i].s_nreloc);
353			esecs[i].s_nlnno	= bswap16(esecs[i].s_nlnno);
354			esecs[i].s_flags	= bswap32(esecs[i].s_flags);
355		}
356	}
357
358	/* Make the output file... */
359	if ((outfile = open(argv[2], O_WRONLY | O_CREAT, 0777)) < 0)
360		err(1, "Unable to create %s", argv[2]);
361
362	/* Truncate file... */
363	if (ftruncate(outfile, 0)) {
364		warn("ftruncate %s", argv[2]);
365	}
366	/* Write the headers... */
367	safewrite(outfile, &ep.f, sizeof(ep.f), "ep.f: write");
368	if (debug)
369		fprintf(stderr, "wrote %zu byte file header.\n", sizeof(ep.f));
370
371	safewrite(outfile, &ep.a, sizeof(ep.a), "ep.a: write");
372	if (debug)
373		fprintf(stderr, "wrote %zu byte a.out header.\n", sizeof(ep.a));
374
375	safewrite(outfile, &esecs, sizeof(esecs[0]) * nsecs, "esecs: write");
376	if (debug)
377		fprintf(stderr, "wrote %zu bytes of section headers.\n",
378		    sizeof(esecs[0]) * nsecs);
379
380
381	pad = ((sizeof ep.f + sizeof ep.a + sizeof esecs) & 15);
382	if (pad) {
383		pad = 16 - pad;
384		pad16(outfile, pad, "ipad: write");
385		if (debug)
386			fprintf(stderr, "wrote %d byte pad.\n", pad);
387	}
388	/* Copy the loadable sections.   Zero-fill any gaps less than 64k;
389	 * complain about any zero-filling, and die if we're asked to
390	 * zero-fill more than 64k. */
391	for (i = 0; i < ex.e_phnum; i++) {
392		/* Unprocessable sections were handled above, so just verify
393		 * that the section can be loaded before copying. */
394		if (ph[i].p_type == PT_LOAD && ph[i].p_filesz) {
395			if (cur_vma != ph[i].p_vaddr) {
396				unsigned long gap = ph[i].p_vaddr - cur_vma;
397				char    obuf[1024];
398				if (gap > 65536)
399					errx(1, "Intersegment gap (%ld bytes) "
400					    "too large", gap);
401				if (debug)
402					fprintf(stderr, "Warning: %ld byte "
403					    "intersegment gap.\n", gap);
404				memset(obuf, 0, sizeof obuf);
405				while (gap) {
406					int count = write(outfile, obuf,
407					    (gap > sizeof obuf
408					    ? sizeof obuf : gap));
409					if (count < 0)
410						err(1, "Error writing gap");
411					gap -= count;
412				}
413			}
414			if (debug)
415				fprintf(stderr, "writing %d bytes...\n",
416				    ph[i].p_filesz);
417			copy(outfile, infile, ph[i].p_offset, ph[i].p_filesz);
418			cur_vma = ph[i].p_vaddr + ph[i].p_filesz;
419		}
420	}
421
422
423	if (debug)
424		fprintf(stderr, "writing syms at offset 0x%lx\n",
425		    (u_long) ep.f.f_symptr + sizeof(symhdr));
426
427	/* Copy and translate the symbol table... */
428	elf_symbol_table_to_ecoff(outfile, infile, &ep,
429	    sh[symtabix].sh_offset, sh[symtabix].sh_size,
430	    sh[strtabix].sh_offset, sh[strtabix].sh_size);
431
432	/*
433         * Write a page of padding for boot PROMS that read entire pages.
434         * Without this, they may attempt to read past the end of the
435         * data section, incur an error, and refuse to boot.
436         */
437	{
438		char    obuf[4096];
439		memset(obuf, 0, sizeof obuf);
440		if (write(outfile, obuf, sizeof(obuf)) != sizeof(obuf))
441			err(1, "Error writing PROM padding");
442	}
443
444	/* Looks like we won... */
445	return 0;
446}
447
448static void
449copy(int out, int in, off_t offset, off_t size)
450{
451	char    ibuf[4096];
452	size_t  remaining, cur, count;
453
454	/* Go to the start of the ELF symbol table... */
455	if (lseek(in, offset, SEEK_SET) < 0)
456		err(1, "copy: lseek");
457	remaining = size;
458	while (remaining) {
459		cur = remaining;
460		if (cur > sizeof ibuf)
461			cur = sizeof ibuf;
462		remaining -= cur;
463		if ((count = read(in, ibuf, cur)) != cur)
464			err(1, "copy: short read");
465		safewrite(out, ibuf, cur, "copy: write");
466	}
467}
468
469/* Combine two segments, which must be contiguous.   If pad is true, it's
470   okay for there to be padding between. */
471static void
472combine(struct sect *base, struct sect *new, int pad)
473{
474
475	if (base->len == 0)
476		*base = *new;
477	else
478		if (new->len) {
479			if (base->vaddr + base->len != new->vaddr) {
480				if (pad)
481					base->len = new->vaddr - base->vaddr;
482				else
483					errx(1, "Non-contiguous data can't be "
484					    "converted");
485			}
486			base->len += new->len;
487		}
488}
489
490static int
491phcmp(Elf32_Phdr *h1, Elf32_Phdr *h2)
492{
493
494	if (h1->p_vaddr > h2->p_vaddr)
495		return 1;
496	else
497		if (h1->p_vaddr < h2->p_vaddr)
498			return -1;
499		else
500			return 0;
501}
502
503static char *
504saveRead(int file, off_t offset, off_t len, const char *name)
505{
506	char   *tmp;
507	int     count;
508	off_t   off;
509
510	if ((off = lseek(file, offset, SEEK_SET)) < 0)
511		err(1, "%s: fseek", name);
512	if ((tmp = malloc(len)) == NULL)
513		err(1, "%s: Can't allocate %ld bytes", name, (long) len);
514	count = read(file, tmp, len);
515	if (count != len)
516		err(1, "%s: short read", name);
517	return tmp;
518}
519
520static void
521safewrite(int outfile, const void *buf, off_t len, const char *msg)
522{
523	ssize_t     written;
524
525	written = write(outfile, buf, len);
526	if (written != len)
527		err(1, "%s", msg);
528}
529
530
531/*
532 * Output only three ECOFF sections, corresponding to ELF psecs
533 * for text, data, and bss.
534 */
535static int
536make_ecoff_section_hdrs(struct ecoff_exechdr *ep, struct ecoff_scnhdr *esecs)
537{
538
539	ep->f.f_nscns = 6;	/* XXX */
540
541	strcpy(esecs[0].s_name, ".text");
542	strcpy(esecs[1].s_name, ".data");
543	strcpy(esecs[2].s_name, ".bss");
544
545	esecs[0].s_paddr = esecs[0].s_vaddr = ep->a.text_start;
546	esecs[1].s_paddr = esecs[1].s_vaddr = ep->a.data_start;
547	esecs[2].s_paddr = esecs[2].s_vaddr = ep->a.bss_start;
548	esecs[0].s_size = ep->a.tsize;
549	esecs[1].s_size = ep->a.dsize;
550	esecs[2].s_size = ep->a.bsize;
551
552	esecs[0].s_scnptr = ECOFF_TXTOFF(ep);
553	esecs[1].s_scnptr = ECOFF_DATOFF(ep);
554#if 0
555	esecs[2].s_scnptr = esecs[1].s_scnptr +
556	    ECOFF_ROUND(esecs[1].s_size, ECOFF_SEGMENT_ALIGNMENT(ep));
557#endif
558
559	esecs[0].s_relptr = esecs[1].s_relptr = esecs[2].s_relptr = 0;
560	esecs[0].s_lnnoptr = esecs[1].s_lnnoptr = esecs[2].s_lnnoptr = 0;
561	esecs[0].s_nreloc = esecs[1].s_nreloc = esecs[2].s_nreloc = 0;
562	esecs[0].s_nlnno = esecs[1].s_nlnno = esecs[2].s_nlnno = 0;
563
564	esecs[1].s_flags = 0x100;	/* ECOFF rdata */
565	esecs[3].s_flags = 0x200;	/* ECOFF sdata */
566	esecs[4].s_flags = 0x400;	/* ECOFF sbss */
567
568	/*
569	 * Set the symbol-table offset  to point at the end of any
570	 * sections we loaded above, so later code can use it to write
571	 * symbol table info..
572	 */
573	ep->f.f_symptr = esecs[1].s_scnptr + esecs[1].s_size;
574	return (ep->f.f_nscns);
575}
576
577
578/*
579 * Write the ECOFF symbol header.
580 * Guess at how big the symbol table will be.
581 * Mark all symbols as EXTERN (for now).
582 */
583static void
584write_ecoff_symhdr(int out, struct ecoff_exechdr *ep,
585    struct ecoff_symhdr *symhdrp, long nesyms,
586    long extsymoff, long extstroff, long strsize)
587{
588
589	if (debug)
590		fprintf(stderr,
591		    "writing symhdr for %ld entries at offset 0x%lx\n",
592		    nesyms, (u_long) ep->f.f_symptr);
593
594	ep->f.f_nsyms = sizeof(struct ecoff_symhdr);
595
596	memset(symhdrp, 0, sizeof(*symhdrp));
597	symhdrp->esymMax = nesyms;
598	symhdrp->magic = 0x7009;/* XXX */
599	symhdrp->cbExtOffset = extsymoff;
600	symhdrp->cbSsExtOffset = extstroff;
601
602	symhdrp->issExtMax = strsize;
603	if (debug)
604		fprintf(stderr,
605		    "ECOFF symhdr: symhdr %zx, strsize %lx, symsize %lx\n",
606		    sizeof(*symhdrp), strsize,
607		    (nesyms * sizeof(struct ecoff_extsym)));
608
609	if (needswap) {
610		bswap32_region(&symhdrp->ilineMax,
611		    sizeof(*symhdrp) -  sizeof(symhdrp->magic) -
612		    sizeof(symhdrp->ilineMax));
613		symhdrp->magic = bswap16(symhdrp->magic);
614		symhdrp->ilineMax = bswap16(symhdrp->ilineMax);
615	}
616
617	safewrite(out, symhdrp, sizeof(*symhdrp),
618	    "writing symbol header");
619}
620
621
622static void
623elf_read_syms(struct elf_syms *elfsymsp, int in, off_t symoff, off_t symsize,
624    off_t stroff, off_t strsize)
625{
626	register int nsyms;
627	int i;
628	nsyms = symsize / sizeof(Elf32_Sym);
629
630	/* Suck in the ELF symbol list... */
631	elfsymsp->elf_syms = (Elf32_Sym *)
632	    saveRead(in, symoff, nsyms * sizeof(Elf32_Sym),
633	    "ELF symboltable");
634	elfsymsp->nsymbols = nsyms;
635	if (needswap) {
636		for (i = 0; i < nsyms; i++) {
637			Elf32_Sym *s = &elfsymsp->elf_syms[i];
638			s->st_name	= bswap32(s->st_name);
639			s->st_value	= bswap32(s->st_value);
640			s->st_size	= bswap32(s->st_size);
641			s->st_shndx	= bswap16(s->st_shndx);
642		}
643	}
644
645	/* Suck in the ELF string table... */
646	elfsymsp->stringtab = (char *)
647	    saveRead(in, stroff, strsize, "ELF string table");
648	elfsymsp->stringsize = strsize;
649}
650
651
652static void
653elf_symbol_table_to_ecoff(int out, int in, struct ecoff_exechdr *ep,
654    off_t symoff, off_t symsize, off_t stroff, off_t strsize)
655{
656
657	struct elf_syms elfsymtab;
658	struct ecoff_syms ecoffsymtab;
659	register u_long ecoff_symhdr_off, symtaboff, stringtaboff;
660	register u_long nextoff, symtabsize, ecoff_strsize;
661	int     nsyms, i;
662	struct ecoff_symhdr symhdr;
663	int     padding;
664
665	/* Read in the ELF symbols. */
666	elf_read_syms(&elfsymtab, in, symoff, symsize, stroff, strsize);
667
668	/* Approximate translation to ECOFF. */
669	translate_syms(&elfsymtab, &ecoffsymtab);
670	nsyms = ecoffsymtab.nsymbols;
671
672	/* Compute output ECOFF symbol- and string-table offsets. */
673	ecoff_symhdr_off = ep->f.f_symptr;
674
675	nextoff = ecoff_symhdr_off + sizeof(struct ecoff_symhdr);
676	stringtaboff = nextoff;
677	ecoff_strsize = ECOFF_ROUND(ecoffsymtab.stringsize,
678	    (ECOFF_SEGMENT_ALIGNMENT(ep)));
679
680
681	nextoff = stringtaboff + ecoff_strsize;
682	symtaboff = nextoff;
683	symtabsize = nsyms * sizeof(struct ecoff_extsym);
684	symtabsize = ECOFF_ROUND(symtabsize, ECOFF_SEGMENT_ALIGNMENT(ep));
685
686	/* Write out the symbol header ... */
687	write_ecoff_symhdr(out, ep, &symhdr, nsyms, symtaboff,
688	    stringtaboff, ecoffsymtab.stringsize);
689
690	/* Write out the string table... */
691	padding = ecoff_strsize - ecoffsymtab.stringsize;
692	safewrite(out, ecoffsymtab.stringtab, ecoffsymtab.stringsize,
693	    "string table: write");
694	if (padding)
695		pad16(out, padding, "string table: padding");
696
697
698	/* Write out the symbol table... */
699	padding = symtabsize - (nsyms * sizeof(struct ecoff_extsym));
700
701	for (i = 0; i < nsyms; i++) {
702		struct ecoff_extsym *es = &ecoffsymtab.ecoff_syms[i];
703		es->es_flags	= bswap16(es->es_flags);
704		es->es_ifd	= bswap16(es->es_ifd);
705		bswap32_region(&es->es_strindex,
706		    sizeof(*es) - sizeof(es->es_flags) - sizeof(es->es_ifd));
707	}
708	safewrite(out, ecoffsymtab.ecoff_syms,
709	    nsyms * sizeof(struct ecoff_extsym),
710	    "symbol table: write");
711	if (padding)
712		pad16(out, padding, "symbols: padding");
713}
714
715
716
717/*
718 * In-memory translation of ELF symbosl to ECOFF.
719 */
720static void
721translate_syms(struct elf_syms *elfp, struct ecoff_syms *ecoffp)
722{
723
724	int     i;
725	char   *oldstringbase;
726	char   *newstrings, *nsp;
727
728	int     nsyms, idx;
729
730	nsyms = elfp->nsymbols;
731	oldstringbase = elfp->stringtab;
732
733	/* Allocate space for corresponding ECOFF symbols. */
734	memset(ecoffp, 0, sizeof(*ecoffp));
735
736	ecoffp->nsymbols = 0;
737	ecoffp->ecoff_syms = malloc(sizeof(struct ecoff_extsym) * nsyms);
738
739	/* we are going to be no bigger than the ELF symbol table. */
740	ecoffp->stringsize = elfp->stringsize;
741	ecoffp->stringtab = malloc(elfp->stringsize);
742
743	newstrings = (char *) ecoffp->stringtab;
744	nsp = (char *) ecoffp->stringtab;
745	if (newstrings == NULL)
746		errx(1, "No memory for new string table");
747	/* Copy and translate  symbols... */
748	idx = 0;
749	for (i = 0; i < nsyms; i++) {
750		int     binding;
751
752		binding = ELF32_ST_BIND((elfp->elf_syms[i].st_info));
753
754		/* skip strange symbols */
755		if (binding == 0) {
756			continue;
757		}
758		/* Copy the symbol into the new table */
759		strcpy(nsp, oldstringbase + elfp->elf_syms[i].st_name);
760		ecoffp->ecoff_syms[idx].es_strindex = nsp - newstrings;
761		nsp += strlen(nsp) + 1;
762
763		/* translate symbol types to ECOFF XXX */
764		ecoffp->ecoff_syms[idx].es_type = 1;
765		ecoffp->ecoff_syms[idx].es_class = 5;
766
767		/* Symbol values in executables should be compatible. */
768		ecoffp->ecoff_syms[idx].es_value = elfp->elf_syms[i].st_value;
769		ecoffp->ecoff_syms[idx].es_symauxindex = 0xfffff;
770
771		idx++;
772	}
773
774	ecoffp->nsymbols = idx;
775	ecoffp->stringsize = nsp - newstrings;
776}
777/*
778 * pad to a 16-byte boundary
779 */
780static void
781pad16(int fd, int size, const char *msg)
782{
783
784	safewrite(fd, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0", size, msg);
785}
786
787/* swap a 32bit region */
788static void
789bswap32_region(int32_t* p, int len)
790{
791	size_t i;
792
793	for (i = 0; i < len / sizeof(int32_t); i++, p++)
794		*p = bswap32(*p);
795}
796