-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprogram_loader.c
86 lines (73 loc) · 2.33 KB
/
program_loader.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*
* program_loader.c
*
* Authors : Emiton Alves and Cameron LaFreniere
*
* Description: This file handles the loading of a binary file.
* The input file will be translated into a set of 32 bit words.
* The set of words are returned to the client.
* */
#include "program_loader.h"
uint32_t fileLength(FILE *currentFile);
uint32_t createWord(FILE *program);
/**
* This method is used to load a program segment from the binary file
* @param: program - This is the binary file to be opened
* @return: will return an instruction set that conatins all loaded
* instructions and a field indicating number of instructions
**/
struct segment *load(char *program)
{
FILE *input = fopen(program, "r");
if(input == NULL)
{
fprintf(stderr, "Could not open file\n");
exit(EXIT_FAILURE);
}
uint32_t programLength = fileLength(input);
struct segment *instructionSet = NULL;
instructionSet = malloc(sizeof(struct segment));
instructionSet->segmentWords = malloc(programLength * sizeof(uint32_t));
instructionSet->segmentLength = programLength;
uint32_t currentWord = 0;
for(uint32_t i = 0; i < programLength; i++)
{
currentWord = createWord(input);
instructionSet->segmentWords[i] = currentWord;
}
return instructionSet;
}
/**
* This method will determine the number of 32 bit words in a file
* @param: currentFile - the file for which the words will be counted
* @return: will return value specifying the number of words in the file
**/
uint32_t fileLength(FILE *currentFile)
{
char currentChar = 0;
uint64_t numberOfCharacters = 0;
while (currentChar != EOF)
{
currentChar = fgetc(currentFile);
numberOfCharacters += 1;
}
fseek(currentFile, 0, SEEK_SET);
return (uint32_t) (numberOfCharacters - 1) / 4;
}
/**
* This method will extact a word from a file
* @param: program - the file where words a taken from
* @return: will return a 32 bit word
**/
uint32_t createWord(FILE *program)
{
uint32_t word = 0;
int bytesInWord[4] = {0};
for(int i = 0; i < 4; i++)
{
bytesInWord[i] = getc(program);
int bytePosition = 4 - i - 1; // in order to place bytes in reverse
word = Bitpack_newu(word, 8, bytePosition * 8, bytesInWord[i]);
}
return word;
}