

/****************************************************************************
 *
 *  (C) 1999 ARTX INC..  ALL RIGHTS RESERVED.  UNPUBLISHED -- RIGHTS
 *  RESERVED UNDER THE COPYRIGHT LAWS OF THE UNITED STATES.  USE OF A
 *  COPYRIGHT NOTICE IS PRECAUTIONARY ONLY AND DOES NOT IMPLY PUBLICATION
 *  OR DISCLOSURE.
 *
 *  THIS SOFTWARE CONTAINS CONFIDENTIAL INFORMATION AND TRADE SECRETS OF
 *  ARTX INC..  USE, DISCLOSURE, OR REPRODUCTION IS PROHIBITED WITHOUT
 *  THE PRIOR EXPRESS WRITTEN PERMISSION OF ARTX INC..
 *
 *                  RESTRICTED RIGHTS LEGEND
 *
 *  Use, duplication, or disclosure by the Government is subject to
 *  restrictions as set forth in subparagraph (c)(1)(ii) of the Rights
 *  in Technical Data and Computer Software clause at DFARS 252.227-7013
 *  or subparagraphs (c)(1) and (2) of Commercial Computer Software --
 *  Restricted Rights at 48 CFR 52.227-19, as applicable. 
 *
 *  ArtX Inc.
 *  3400 Hillview Ave, Bldg 5
 *  Palo Alto, CA 94304
 *
 * $Id: elf.c,v 1.1 2006/02/12 21:47:21 horti Exp $
 *
 ***************************************************************************/

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "elf.h"
#include "image.h"

static ElfHdr eh;
static ElfPrgHdr *ph;

u8
hostorder (void)
{
      return 1;
}

u32
swap32(u32 val)
{
#if ATI_BIG_ENDIAN
    return val;
#else
    return ((val >> 24) & 0x000000ff) |
           ((val >>  8) & 0x0000ff00) |
           ((val <<  8) & 0x00ff0000) |
           ((val << 24) & 0xff000000);
#endif // ATI_BIG_ENDIAN
}

u16
swap16(u16 val)
{
#if ATI_BIG_ENDIAN
    return val;
#else
    return ((val >> 8) & 0x00ff) | ((val << 8) & 0xff00);
#endif // ATI_BIG_ENDIAN
}

void
swapPh(ElfPrgHdr *pp)
{
    u32 *ip;
    u32  i;

    ip = (u32 *)pp;
    for( i = 0 ; i < sizeof(*pp) ; i += 4, ip++ ) {
        *ip = swap32(*ip);
    }
}

void
swapEh(ElfHdr *ep)
{
    ep->e_type = swap16(ep->e_type);
    ep->e_machine = swap16(ep->e_machine);
    ep->e_version = swap32(ep->e_version);
    ep->e_entry = swap32(ep->e_entry);
    ep->e_phoff = swap32(ep->e_phoff);
    ep->e_shoff = swap32(ep->e_shoff);
    ep->e_flags = swap32(ep->e_flags);
    ep->e_ehsize = swap16(ep->e_ehsize);
    ep->e_phentsize = swap16(ep->e_phentsize);
    ep->e_phnum = swap16(ep->e_phnum);
    ep->e_shentsize = swap16(ep->e_shentsize);
    ep->e_shnum = swap16(ep->e_shnum);
    ep->e_shstrndx = swap16(ep->e_shstrndx);
}

static Image *
eatPh(FILE *fp)
{
    Image   *ip;
    u8   *bp;
    u32   bLen, oLen;
    u32   zLen, zOff = 0;
    int i;

    ip = (Image *)calloc(1, sizeof(Image));
    if ( ip == NULL ) {
        fprintf(stderr, "out of mem\n");
        return NULL;
    }

    ip->entry = eh.e_entry;

    /* locate the text and data segments */
    for( i = 0 ; i < eh.e_phnum ; i++ ) {
        if ( ph[i].p_type != PT_LOAD ) {
            continue;
        }

        bLen = ph[i].p_filesz;
        if ( (bLen == 0) && (ph[i].p_memsz == 0) ) {
            // printf("empty program header? %d\n", i);
            continue;
        }

        /* check for text section */
        if ( ph[i].p_flags & PF_X ) {
            if ( ip->textData ) {
                // sanity check
                if ( ip->dataData ) {
                    fprintf(stderr, "Mult text with intermediate Data!!!\n");
                    return NULL;
                }
                fprintf(stderr, "Warning: multiple text segments...\n");
                oLen = ph[i].p_vaddr - ip->text;
                // zero any data not covered by aligning headers
                if ( oLen > ip->textLen ) {
                    zLen = oLen - ip->textLen;
                    zOff = ip->textLen;
                }
                else {
                    zLen = 0;
                }
                ip->textLen = oLen + ph[i].p_memsz;
                ip->textData = realloc(ip->textData, ip->textLen);
                if ( ip->textData == NULL ) {
                    fprintf(stderr, "unable to realloc text %d\n", i);
                    return NULL;
                }
                if (zLen) {
                    memset(&ip->textData[zOff], 0, zLen);
                }
                bp = &ip->textData[oLen];
            }
            else {
                ip->textLen = bLen;
                ip->textData = bp = (u8 *)malloc(bLen);
                ip->text = ph[i].p_vaddr;
            }
            goto readIt;
        }

#if 0
        /* BSS gets its own program header with MWX */
        if ( bLen == 0 ) {
	    if (ip->bss) {
		ip->bssLen = (ph[i].p_vaddr - ip->bss) + ph[i].p_memsz;
            }
	    else {
                ip->bss = ph[i].p_vaddr;
                ip->bssLen = ph[i].p_memsz;
            }
            continue;
        }
#endif // 0

        // deal with a data segment
        /* see if we have to grow the buffer */
        if ( ip->dataData ) {
            oLen = ph[i].p_vaddr - ip->data;
            // zero any data not covered by aligning headers
            if ( oLen > ip->dataLen ) {
                zLen = oLen - ip->dataLen;
                zOff = ip->dataLen;
            }
            else {
                zLen = 0;
            }
            ip->dataLen = oLen + ph[i].p_memsz;
            ip->dataData = realloc(ip->dataData, ip->dataLen);
            if ( ip->dataData == NULL ) {
                fprintf(stderr, "unable to realloc data %d\n", i);
                return NULL;
            }
            if (zLen) {
                memset(&ip->dataData[zOff], 0, zLen);
            }
            bp = &ip->dataData[oLen];
        }
        else {
            ip->data = ph[i].p_vaddr;
            ip->dataLen = ph[i].p_memsz;
            ip->dataData = bp = (u8 *)malloc(ph[i].p_memsz);
        }

readIt:
        if ( bLen == 0 ) {
            memset(bp, 0, ph[i].p_memsz);
            continue;
        }

        /* read in the segment */
        fseek(fp, ph[i].p_offset, SEEK_SET);
        if ( fread((void *)bp, bLen, 1, fp) != 1 ) {
            fprintf(stderr, "unable to read segment %d\n", i);
            return NULL;
        }
    }

    // Now, generate our own BSS
    for( i = ip->dataLen - 1 ; i >= 0 ; i-- ) {
        if ( ip->dataData[i] ) {
            break;
        }
    }
    i++;
    if ( i < ip->dataLen ) {
        ip->bssLen =  ip->dataLen - i;
        ip->bss = ip->data + i;
        ip->dataLen = i;
    }

    return ip;
}

void
dumpImage(Image *ip)
{
    printf("text 0x%08x:0x%08x\n", ip->text,  ip->textLen);
    printf("data 0x%08x:0x%08x\n", ip->data,  ip->dataLen);
    printf("bss  0x%08x:0x%08x\n", ip->bss,   ip->bssLen);
    printf("entry 0x%x\n", ip->entry);
}

Image *
elfRead(const char *elfFile)
{
    FILE   *fp;
    Image  *ip;
    u32  sz;
    u32  tmp;
    int     i;

    /* read file */
    fp = fopen(elfFile, "rb");
    if ( fp == NULL ) {
        fprintf(stderr, "unable to open %s\n", elfFile);
        return NULL;
    }

    if ( fread((void *)&eh, sizeof(eh), 1, fp) != 1 ) {
        fprintf(stderr, "unable to read elf header\n");
        return NULL;
    }

    fprintf (stderr, "before swap 0x%x machine 0x%x order 0x%x host 0x%x\n", 
	     eh.e_type, eh.e_machine, eh.e_ident[EI_ORDER], hostorder());

    /* fix it */
    if (eh.e_ident[EI_ORDER] != hostorder())
      swapEh(&eh);

    /* we could be a little more careful here... */
    if ( eh.e_type != ET_EXEC ) {
        fprintf(stderr, "invalid elf header 0x%x expected 0x%x\n", 
		eh.e_type, ET_EXEC);
        return NULL;
    }

    /* read in the program headers */
    sz = eh.e_phnum * eh.e_phentsize;
    fprintf (stderr, "sz 0x%x = 0x%x * 0x%x\n",
	     sz, eh.e_phnum, eh.e_phentsize);
    ph = (ElfPrgHdr *)malloc(sz);
    fseek(fp, eh.e_phoff, SEEK_SET);
    if ( fread((void *)ph, sz, 1, fp) != 1 ) {
        fprintf(stderr, "unable to read program headers\n");
        return NULL;
    }

    if ( eh.e_phentsize != sizeof(ElfPrgHdr) ) {
        fprintf(stderr, "mismatch in elf prg headers\n");
        return NULL;
    }

    /* fix the ph */
    tmp = eh.e_phnum;
    for( i = 0 ; i < eh.e_phnum ; i++ ) {
        swapPh(&ph[i]);
    }

    ip = eatPh(fp);

    free(ph);
    fclose(fp);

    return ip;
}

/* eof */
