Repository navigation
Expand file tree
/
Copy pathmain.c
More file actions
64 lines (54 loc) · 1.48 KB
/
Copy pathmain.c
File metadata and controls
64 lines (54 loc) · 1.48 KB
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
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include "disasm.h"
// Detect if host is little endian (1) or big endian (0)
static int is_little_endian() {
uint16_t x = 1;
return *((uint8_t*)&x) == 1;
}
// Swap bytes for 32-bit integer (big <-> little endian)
static uint32_t swap32(uint32_t val) {
return ((val >> 24) & 0xFF) |
((val >> 8) & 0xFF00) |
((val << 8) & 0xFF0000) |
((val << 24) & 0xFF000000);
}
int main(int argc, char *argv[]) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <binary_file>\n", argv[0]);
return 1;
}
FILE *file = fopen(argv[1], "rb");
if (!file) {
perror("Error opening file");
return 1;
}
// Check file size to ensure it's multiple of 4
fseek(file, 0, SEEK_END);
long filesize = ftell(file);
rewind(file);
if (filesize % 4 != 0) {
fprintf(stderr, "Error: file size (%ld) is not a multiple of 4 bytes\n", filesize);
fclose(file);
return 1;
}
int host_le = is_little_endian();
uint32_t instr;
size_t count = 0;
while (fread(&instr, sizeof(instr), 1, file) == 1) {
if (!host_le) {
instr = swap32(instr);
}
printf("Instruction %zu: ", count++);
disassemble(instr);
}
if (ferror(file)) {
perror("Error reading file");
fclose(file);
return 1;
}
fclose(file);
printf("Total instructions: %zu\n", count);
return 0;
}