/*
 *               Copyright (C) 2005, BroadOn Communications Corp.
 *
 *  These coded instructions, statements, and computer programs contain
 *  unpublished proprietary information of BroadOn Communications Corp.,
 *  and are protected by federal copyright law. They may not be disclosed
 *  to third parties or copied or duplicated in any form, in whole or in
 *  part, without the prior written consent of BroadOn Communications Corp.
 *
 *  Description:
 *      This file implements common utility functions.
 */
#include <iostypes.h>
#include <ioslibc.h>
#include <elf.h>
#ifdef RVL
extern void little2big(u32 *buf, u32 len);
#endif 
u32
elfload(char *name, u32 *entry_point)
{
    FILE *fp = 0;
    u8 i;
    u32 rv = 0;
    Elf32_Ehdr ehdr;
    char buffer[512];
    Elf32_Phdr *phdr = (Elf32_Phdr *)buffer;

    if ( (NULL == name) || (0 == (fp = fopen(name, "rb")))) {
        printf("fopen: unable to load file '%s'\n", name);
        goto out;
    }
    fread(&ehdr, sizeof(ehdr), 1, fp);
    fread(buffer, ehdr.e_phentsize * ehdr.e_phnum, 1, fp);
    *entry_point = ehdr.e_entry;
    printf("entry point = 0x%08x\n", *entry_point);
    printf("phnum = %u\n", ehdr.e_phnum);
    for (i = 0; i < ehdr.e_phnum; ++i) {
        if (phdr[i].p_type == PT_LOAD) {
            u8 *buf = (u8*)phdr[i].p_vaddr;
            if (phdr[i].p_filesz > 0) {
                fseek(fp, phdr[i].p_offset, SEEK_SET);
                fread(buf, phdr[i].p_filesz, 1, fp);
                rv += phdr[i].p_filesz;
#if 0
#ifdef RVL
                little2big((u32 *)buf, phdr[i].p_filesz);
#endif
#endif
            }
            if (phdr[i].p_memsz > phdr[i].p_filesz) {
                memset(buf + phdr[i].p_filesz, 0, phdr[i].p_memsz - phdr[i].p_filesz);
            }
            printf("Loaded segment [%08x, %08x]\n", phdr[i].p_vaddr, phdr[i].p_vaddr + phdr[i].p_memsz);
        }
    }
out:
    if (fp) fclose(fp);
    return rv;
}
