/*
 * Copyright (C) 2018-2020 Western Digital Corporation or its affiliates
 * Copyright (C) 2017-2018 Wearable, Inc.
 * Copyright (C) 2000-2012 leJOS Contributors
 * Copyright (C) 2000 Jose H. Solorzano and TinyVM Contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 * 
 * This Source Code Form is “Incompatible With Secondary Licenses”,
 * as defined by the Mozilla Public License, v. 2.0.
 */

/**
 * load.c
 * Loads binary into VM memory.
 */



#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "language.h"
#include "trace.h"
#include "types.h"

#ifndef O_BINARY
#define O_BINARY 0
#endif

size_t readBinary(const char *fileName, void* mem, size_t mem_len)
{
    int pDesc;
    ssize_t pLength;
    ssize_t pTotal;
    ssize_t pNumRead;
    byte *pBinary;
    
    pDesc = open (fileName, O_RDONLY | O_BINARY);
    if (pDesc == -1) {
        printf("Unable to open %s\n", fileName);
        exit(1);
    }
    pLength = (ssize_t)lseek (pDesc, 0, SEEK_END);
    if(pLength == 0) {
        printf("Unable to open %s\n", fileName);
        exit(1);
    }
    lseek (pDesc, 0, SEEK_SET);
    if (pLength > (ssize_t) mem_len) {
        return 0;
    }
    pBinary = mem;
    pTotal = 0;
    while (pTotal < pLength) {
        pNumRead = read (pDesc, pBinary + pTotal, (size_t)(pLength - pTotal));
        if (pNumRead == -1) {
            printf ("Unexpected EOF\n");
            free(pBinary);
            exit (1);
        }
        pTotal += pNumRead;
    }
    
    return pLength;
}


