-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.c
133 lines (110 loc) · 2.64 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
#include "nanac.h"
#include <stdio.h>
#include <stdlib.h>
static void load_file (struct nanac_s *cpu, const char *filename)
{
FILE *fp;
long lSize;
char *buffer;
fp = fopen ( filename , "rb" );
if( !fp )
{
perror(filename);
exit(1);
}
fseek( fp, 0L, SEEK_END);
lSize = ftell( fp );
rewind( fp );
if( (lSize < 4) || (lSize % 4) )
{
fclose(fp);
fputs("invalid size",stderr);
exit(1);
}
/* allocate memory for entire content */
buffer = calloc( 1, lSize+1 );
if( !buffer )
{
fclose(fp);
fputs("memory alloc fails",stderr);
exit(1);
}
/* copy the file into the buffer */
if( 1 != fread( buffer, lSize, 1, fp) )
{
fclose(fp);
free(buffer);
fputs("entire read fails",stderr);
exit(1);
}
/* do your work here, buffer is a string contains the whole text */
cpu->ops = (struct nanac_op_s*)buffer;
cpu->ops_sz = lSize / 4;
fclose(fp);
}
static int print_mods (struct nanac_mods_s *mods)
{
struct nanac_mod_s *mod;
unsigned char mod_idx;
unsigned char cmd_idx;
for( mod_idx = 0; mod_idx < mods->cnt; mod_idx++ )
{
mod = &mods->idx[mod_idx];
for( cmd_idx = 0; cmd_idx < mod->cmds_len; cmd_idx++ )
{
printf("%02X %02X %s %s\n", mod_idx, cmd_idx, mod->name,
mod->cmds[cmd_idx].name);
}
}
return 0;
}
static int print_help (char *name)
{
fprintf(stderr, "Usage: %s [-tX] [file.bin ...]\n", name);
fprintf(stderr, " -t Trace opcodes at runtime\n");
fprintf(stderr, " -X Display opcode hex reference\n");
return 10;
}
int main( int argc, char **argv )
{
int flag_trace = 0;
int i = 1;
struct nanac_mods_s mods;
struct nanac_s ctx;
nanac_mods_init(&mods);
nanac_mods_builtins(&mods);
if( argc < 2 )
{
return print_help(argv[0]);
}
if( argv[1][0] == '-' )
{
char *flags_ptr = &argv[1][1];
i = 2;
while( *flags_ptr != 0 )
{
switch( *flags_ptr ) {
case 't':
flag_trace++;
break;
case 'X':
return print_mods(&mods);
default:
fprintf(stderr, "error: invalid option %c\n", *flags_ptr);
return print_help(argv[0]);
}
flags_ptr++;
}
}
for( ; i < argc; i++ )
{
nanac_init(&ctx, &mods);
load_file(&ctx, argv[i]);
nanac_run(&ctx);
if( ctx.ops )
{
free(ctx.ops);
}
}
return 0;
}