-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
361 lines (318 loc) · 9.41 KB
/
main.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NAME "CtoCPUSimulator"
#define VERSION "Beta 1.2.0"
#define AUTHOR "Fardin Kamal"
#define MAX_LINE_LENGTH 1024
#define MEMORY_SIZE 1024
#define INPUT_FILE "io/input.c"
#define ASSEMBLY_FILE "io/assembly.s"
#define BINARY_FILE "io/binary.o"
typedef struct
{
int pc; // Program Counter
int memory[MEMORY_SIZE];
int accumulator; // Accumulator register
} CPU;
/**
* Load a program from a binary file into the CPU's memory
* @param cpu The CPU
* @param filename The name of the binary file
*/
void load_program(CPU *cpu, const char *filename)
{
FILE *file = fopen(filename, "rb");
if (file == NULL)
{
printf("Error: Cannot open file %s\n", filename);
return;
}
fread(cpu->memory, sizeof(int), MEMORY_SIZE, file);
fclose(file);
}
/**
* Execute the next instruction in the CPU's memory
* @param cpu The CPU
*/
void execute_instruction(CPU *cpu)
{
int instruction = cpu->memory[cpu->pc];
int opcode = instruction >> 24; // Extract opcode (first 8 bits)
int operand = instruction & 0xFFFFFF; // Extract operand (last 24 bits)
switch (opcode)
{
case 0: // Load instruction
cpu->accumulator = operand;
printf("Loaded %d into accumulator\n", operand);
break;
case 1: // Add instruction
cpu->accumulator += operand;
printf("Added %d to accumulator\n", operand);
break;
case 2: // Subtract instruction
cpu->accumulator -= operand;
printf("Subtracted %d from accumulator\n", operand);
break;
case 3: // Halt instruction
printf("Halted execution\n");
cpu->pc = MEMORY_SIZE; // Terminate execution
break;
default:
printf("Unknown opcode %d\n", opcode);
break;
}
cpu->accumulator += instruction;
cpu->pc++;
}
/**
* Print the binary representation of a byte
* @param byte The byte to print
*/
void print_binary(unsigned char byte)
{
for (int i = 7; i >= 0; --i)
{
putchar((byte & (1 << i)) ? '1' : '0');
}
putchar(' ');
}
/**
* View the contents of the binary file in human readable format in hexadecimal
*/
void view_binary_file()
{
FILE *file = fopen(BINARY_FILE, "rb");
if (file == NULL)
{
fprintf(stderr, "Error: Unable to open binary file\n");
exit(EXIT_FAILURE);
}
printf("\nBinary code:\n");
fseek(file, 0, SEEK_END);
long file_size = ftell(file);
rewind(file);
char *buffer = malloc(file_size);
if (buffer == NULL)
{
fprintf(stderr, "Error: Memory allocation failed\n");
fclose(file);
exit(EXIT_FAILURE);
}
fread(buffer, 1, file_size, file);
fclose(file);
for (int i = 0; i < file_size; i++)
{
print_binary(buffer[i]);
}
printf("\n");
free(buffer);
}
/**
* View the contents of the preprocessed file
*/
void view_preprocessed_file()
{
FILE *file = fopen(ASSEMBLY_FILE, "r");
if (file == NULL)
{
fprintf(stderr, "Error: Unable to open assembly file\n");
exit(EXIT_FAILURE);
}
printf("\nPreprocessed code:\n");
char line[MAX_LINE_LENGTH];
while (fgets(line, sizeof(line), file) != NULL)
{
printf("%s", line);
}
fclose(file);
printf("\n\n");
}
/**
* View the contents of the assembly file
*/
void view_assembly_file()
{
FILE *file = fopen(ASSEMBLY_FILE, "r");
if (file == NULL)
{
fprintf(stderr, "Error: Unable to open assembly file\n");
exit(EXIT_FAILURE);
}
printf("\nAssembly code:\n");
char line[MAX_LINE_LENGTH];
while (fgets(line, sizeof(line), file) != NULL)
{
printf("%s", line);
}
fclose(file);
printf("\n\n");
}
/**
* Generate the binary machine code from the assembly code
* The assembler (e.g., GNU as) translates the assembly code into binary machine code
*/
void *generate_binary_code()
{
printf("\nGenerating binary code...\n");
// Prepare the command to invoke the assembler (e.g., GNU as)
char command[MAX_LINE_LENGTH];
snprintf(command, sizeof(command), "as -o %s %s", BINARY_FILE, ASSEMBLY_FILE);
// Execute the assembler and check for errors
int result = system(command);
if (result != 0)
{
fprintf(stderr, "Error: Assembler failed to assemble the code\n");
exit(EXIT_FAILURE);
}
// Read the binary machine code from the output file
FILE *binary_file = fopen(BINARY_FILE, "rb");
if (binary_file == NULL)
{
fprintf(stderr, "Error: Unable to open binary file %s\n", BINARY_FILE);
exit(EXIT_FAILURE);
}
fseek(binary_file, 0, SEEK_END);
long binary_size = ftell(binary_file);
rewind(binary_file);
char *binary_code = malloc(binary_size);
if (binary_code == NULL)
{
fprintf(stderr, "Error: Memory allocation failed\n");
fclose(binary_file);
exit(EXIT_FAILURE);
}
fread(binary_code, 1, binary_size, binary_file);
fclose(binary_file);
free(binary_code);
printf("\nBinary code generated!\n");
}
/**
* Preprocess the input C code and write the preprocessed code to the output file
* Before compilation, the C preprocessor handles directives like #include and #define
* @param input_file The input file
* @param output_file The output file
*/
void preprocess(const char *input_file_path, const char *output_file_path)
{
FILE *input_file = fopen(input_file_path, "r");
if (input_file == NULL)
{
fprintf(stderr, "Error: Unable to open input file\n");
exit(EXIT_FAILURE);
}
FILE *output_file = fopen(output_file_path, "w");
if (output_file == NULL)
{
fprintf(stderr, "Error: Unable to create output file\n");
fclose(input_file);
exit(EXIT_FAILURE);
}
char line[MAX_LINE_LENGTH];
printf("\nPreprocessing...\n");
while (fgets(line, sizeof(line), input_file) != NULL)
{
// Check if the line starts with #include or #define
if (strncmp(line, "#include", strlen("#include")) == 0)
{
// Handle #include directive (read and output contents of included file)
char filename[MAX_LINE_LENGTH];
int scanned = sscanf(line, "#include \"%[^\"]\"", filename);
if (scanned == 1)
{
FILE *included_file = fopen(filename, "r");
if (included_file != NULL)
{
preprocess(filename, output_file_path);
fclose(included_file);
}
else
{
fprintf(stderr, "Error: Unable to open included file: %s\n", filename);
}
}
}
else if (strncmp(line, "#define", strlen("#define")) == 0)
{
// Handle #define directive (store macro and replacement text)
// (You may need to implement a data structure to store macros)
}
else
{
// Output the line as-is (after processing any macro replacements)
fprintf(output_file, "%s", line);
}
}
printf("\nPreprocessing done!\n");
fclose(input_file);
fclose(output_file);
}
/**
* Compile the input C code and return the generated assembly code
* The C compiler (e.g., GCC) translates the preprocessed C code into assembly code
* @param input_filename The name of the input file
*/
void *generate_assembly(const char *input_filename)
{
printf("\nGenerating assembly code...\n");
// Prepare the command to invoke GCC
char command[MAX_LINE_LENGTH];
snprintf(command, sizeof(command), "gcc -S -o %s %s", ASSEMBLY_FILE, input_filename);
// Execute GCC
if (system(command) != 0)
{
fprintf(stderr, "Error: GCC failed to generate assembly code.\n");
return NULL;
}
// Open the file containing the generated assembly code
FILE *assembly_file = fopen(ASSEMBLY_FILE, "r");
if (assembly_file == NULL)
{
fprintf(stderr, "Error: Unable to open assembly file %s\n", ASSEMBLY_FILE);
return NULL;
}
// Read the assembly code and store it in a dynamically allocated buffer
char *assembly_code = NULL;
char line[MAX_LINE_LENGTH];
size_t assembly_size = 0;
while (fgets(line, sizeof(line), assembly_file) != NULL)
{
size_t line_length = strlen(line);
assembly_code = realloc(assembly_code, assembly_size + line_length + 1);
if (assembly_code == NULL)
{
fprintf(stderr, "Error: Memory allocation failed\n");
fclose(assembly_file);
return NULL;
}
memcpy(assembly_code + assembly_size, line, line_length);
assembly_size += line_length;
}
// Null-terminate the assembly code string
assembly_code[assembly_size] = '\0';
// Close the assembly file
fclose(assembly_file);
printf("Assembly code generated successfully!\n");
return assembly_code;
}
int main()
{
printf("%s %s\n", NAME, VERSION);
preprocess(INPUT_FILE, ASSEMBLY_FILE);
view_preprocessed_file();
generate_assembly(INPUT_FILE);
view_assembly_file();
generate_binary_code();
view_binary_file();
CPU cpu;
cpu.pc = 0;
cpu.accumulator = 0;
load_program(&cpu, BINARY_FILE);
// Emulate execution loop
while (cpu.pc < MEMORY_SIZE)
{
execute_instruction(&cpu);
}
printf("Result in accumulator: %d\n", cpu.accumulator);
return EXIT_SUCCESS;
}