/*
 *               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: Load segments from a .dol file. File is assumed to be
 *  big-endian and that this function is run on a big-endian machine.
 */
#include <iostypes.h>
#include <ioslibc.h>
#include "dol.h"


#define PPC_VIRT_ADDR_MASK  0x80000000
#define PPC_VIRT2PHYS(a)    ((a)&(~PPC_VIRT_ADDR_MASK))

u32
loadSegment(FILE *fp, u8 **src, u32 *dstn, u32 *len)
{
   u32 i, size;
   u32 rv = 0;
   for ( i = 0; i <  DOL_MAX_TEXT; i++) {
       if (src[i] == NULL) continue;
       size = (len[i] + 31) & ~31;
       printf("-> Loading seg[%02d]: src:0x%08X(phys:0x%08X) "
           "dst:0x%08X(phys:0x%08X) size:0x%08X\n",
           i, src[i], PPC_VIRT2PHYS((u32)src[i]), 
           dstn[i], PPC_VIRT2PHYS((u32)dstn[i]), size);
       if ( 0 > fseek(fp, (u32) (PPC_VIRT2PHYS((u32)src[i])), SEEK_SET) ) {
           printf("fseek(%u) failed\n", src[i]);
           rv = 0;
           goto out;
       }
       if ( 0 > fread((void *)(PPC_VIRT2PHYS((u32)dstn[i])), size, 1, fp)) {
           printf("fread failed\n");
           rv = 0;
           goto out;
       }
       rv += size;
   }
out:
   return rv;
}

u32
dolload(char *name, u32 *entry_point)
{
    FILE *fp = 0;
    u32 rv = 0;
    DolImage dhdr;
    
    if ( (NULL == name) || (0 == (fp = fopen(name, "rb")))) {
        printf("fopen: unable to load file '%s'\n", name);
        goto out;
    }
    if ( 0 > fread(&dhdr, sizeof(dhdr), 1, fp) ) {
        printf("fread: failed to read dol header from %s\n", name);
        goto out;
    }
    *entry_point = dhdr.entry;
    /* zero bss */
    printf("Clearing dol bss: bss:0x%08X(phys:0x%08X) len:0x%08X\n",
        dhdr.bss, PPC_VIRT2PHYS(dhdr.bss), dhdr.bssLen);
    memset((void*) (PPC_VIRT2PHYS(dhdr.bss)), 0, dhdr.bssLen); 
    /*load text */
    printf("Loading dol text: textData:0x%08X text:0x%08X len:0x%08X\n",
        dhdr.textData, dhdr.text, dhdr.textLen);
    rv = loadSegment(fp, dhdr.textData, dhdr.text, dhdr.textLen);
    if (rv == 0) goto out;
    printf("Loaded dol text of size %u(0x%08X) bytes successfully\n", rv, rv);
    /*load data */
    printf("Loading dol data: dataData:0x%08X data:0x%08X len:0x%08X\n",
        dhdr.dataData, dhdr.data, dhdr.dataLen);
    rv = loadSegment(fp, dhdr.dataData, dhdr.data, dhdr.dataLen);
    if (rv == 0) goto out;
    printf("Loaded dol data of size %u(0x%08X) bytes successfully\n", rv, rv);
    printf("Loaded %s successfully\n", name);
out:
    if (fp) fclose(fp);
    return rv;
}
