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