/*
 *               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"

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

u32
dolload(char *name, u32 *entry_point)
{
    FILE *fp = 0;
    u32 rv = -1;
    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 */
    memset((void*) dhdr.bss, 0, dhdr.bssLen); 
    /*load text */
    if ( 0 > loadSegment(fp, dhdr.textData, dhdr.text, dhdr.textLen) )
        goto out;
    /*load data */
    if ( 0 > loadSegment(fp, dhdr.dataData, dhdr.data, dhdr.dataLen) )
        goto out;
    rv = 0;
    printf("Loaded %s successfully\n", name);
out:
    if (fp) fclose(fp);
    return rv;
}
