summaryrefslogtreecommitdiff
path: root/src/code/sim86.cpp
blob: e1ef6a9cc4a2fdf707d16d42925ce3ff7874daf2 (plain) (blame)
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
#include <stdio.h>
#include <string.h>

#include "sim86.h"
#include "sim86_shared.h"

global_variable u8 FlagToCharMapping[] = "CPAZSOIDT";

internal void
SetOrUnsetFlag(u32 *FlagsRegister, b32 Condition, flags_8086 Flag)
{
    if(Condition)
    {
        *FlagsRegister |= Flag;
    }
    else
    {
        *FlagsRegister &= (~Flag);
    }
}

internal u32
FlagsToString(char *Buffer, u32 Flags)
{
    u32 Length = 0;
    
    for(u32 MappingIndex = 0;
        MappingIndex < ArrayCount(FlagToCharMapping);
        MappingIndex++)
    {
        u8 Char = FlagToCharMapping[MappingIndex];
        b32 IsBitSet = (Flags & 1);
        Flags >>= 1;
        if(IsBitSet)
        {
            Buffer[Length++] = Char;
        }
    }
    
    return Length;
}

internal void
FlagsFromValue(u32 *FlagsRegister, u32 InstructionFlags, s32 Value)
{
    u32 OldFlagsRegister = *FlagsRegister;
    
    u32 SignMask = (1 << ((InstructionFlags & Inst_Wide) ? 15 : 7));
    SetOrUnsetFlag(FlagsRegister, (Value & SignMask), Flag_Sign);
    SetOrUnsetFlag(FlagsRegister, (Value == 0),       Flag_Zero);
    
    // NOTE(luca): Parity flag is set when in the lower 8 bits the number of set bits is even.
    u32 OneBitsCount = 0;
    for(u32 BitsIndex = 0;
        BitsIndex < 8;
        BitsIndex++)
    {
        OneBitsCount += (Value & 1);
        Value >>= 1;
    }
    SetOrUnsetFlag(FlagsRegister, (!(OneBitsCount & 1)), Flag_Parity);
    
    // TODO(luca): Overflow flag
    // Were we adding positive numbers but produced a negative number?
    
    // TODO(luca): Carry flag 
    // When twot numbers are added and the 17th bit would be set?
    
    // TODO(luca): Auxiliary carry flag
    // Carry for bottom 8 bits
    if(*FlagsRegister != OldFlagsRegister)
    {
        char OldFlagsString[ArrayCount(FlagToCharMapping)] = {};
        char FlagsString[ArrayCount(FlagToCharMapping)] = {};
        FlagsToString(OldFlagsString, OldFlagsRegister);
        FlagsToString(FlagsString, *FlagsRegister);
        
        printf(" flags:%s->%s", OldFlagsString, FlagsString);
    }
}

struct operands_to_values_result
{
    s32 *Destination;
    s32 *Source;
};
internal operands_to_values_result
OperandsToValues(s32 *Registers, u8 *Memory,
                 instruction_operand *DestinationOperand, instruction_operand *SourceOperand)
{
    operands_to_values_result Result = {};
    
    if(0) {}
    else if(DestinationOperand->Type == Operand_Register)
    {
        Result.Destination = Registers + DestinationOperand->Register.Index;
    }
    else if(DestinationOperand->Type == Operand_Memory)
    {
        Result.Destination = (s32 *)(Memory + DestinationOperand->Address.Displacement);
        
        s32 CompleteDisplacement = DestinationOperand->Address.Displacement;
        Assert(DestinationOperand->Address.Terms[0].Register.Count == DestinationOperand->Address.Terms[1].Register.Count);
        
        u32 Count = DestinationOperand->Address.Terms[0].Register.Index;
        u32 Mask = ((u32)((-1)) >> (16 + (16 - Count*8)));
        
        CompleteDisplacement += (Registers[DestinationOperand->Address.Terms[0].Register.Index] & Mask) +
        (Registers[DestinationOperand->Address.Terms[1].Register.Index] & Mask);
        
        Result.Destination = (s32 *)(Memory + CompleteDisplacement);
        Assert(0);
    }
    else if(DestinationOperand->Type == Operand_Immediate)
    {
        Result.Destination = &DestinationOperand->Immediate.Value;
    }
    else if(SourceOperand->Type != Operand_None)
    {
        Assert(0);
    }
    
    if(0) {}
    else if(SourceOperand->Type == Operand_Register)
    {
        Result.Source = Registers + SourceOperand->Register.Index;
    }
    else if(SourceOperand->Type == Operand_Immediate)
    {
        Result.Source = &SourceOperand->Immediate.Value;
    }
    else if(SourceOperand->Type == Operand_Memory)
    {
        Assert(0 && "not implemented yet.");
    }
    else if(SourceOperand->Type != Operand_None)
    {
        Assert(0);
    }
    
    return Result;
}


internal void
Run8086(psize DisassemblySize, u8 *Disassembly)
{
    s32 Registers[Register_count] = {}; 
    u32 FlagsRegister = 0;
    u32 IPRegister = 0;
    
    local_persist u8 Memory[1*1024*1024*1024] = {};
    
    while(IPRegister < DisassemblySize)
    {
        instruction Decoded;
        Sim86_Decode8086Instruction(DisassemblySize - IPRegister, Disassembly + IPRegister, &Decoded);
        if(Decoded.Op)
        {
            u32 OldIPRegister = IPRegister;
            IPRegister += Decoded.Size;
            
#if SIM86_INTERNAL           
            printf("Size:%u Op:%s Flags:0x%x ;", Decoded.Size, Sim86_MnemonicFromOperationType(Decoded.Op), Decoded.Flags);
#endif
            
            instruction_operand *DestinationOperand = Decoded.Operands;
            instruction_operand *SourceOperand = Decoded.Operands + 1;
            operands_to_values_result OperandsValues = OperandsToValues(Registers, Memory, DestinationOperand, SourceOperand);
            s32 *Destination = OperandsValues.Destination;
            s32 *Source = OperandsValues.Source;
            
            if(0) {}
            else if(Decoded.Op == Op_mov)
            {
                Assert(SourceOperand->Type == Operand_Register || SourceOperand->Type == Operand_Immediate);
                
                s32 Old = *Destination;
                if(Decoded.Flags & Inst_Wide)
                {
                    *Destination = *Source;
                }
                else
                {
                    // NOTE(luca): We assume that an immediate will have an Offset of 0.
                    u32 DestOffset = DestinationOperand->Register.Offset;
                    u32 SourceOffset = SourceOperand->Register.Offset;
                    
                    u8 *SourceByte = (u8 *)Source + SourceOffset;
                    u8 *DestByte = (u8 *)Destination + DestOffset;
                    
                    *DestByte = *SourceByte;
                }
                
#if SIM86_INTERNAL                    
                if(DestinationOperand->Type == Operand_Register)
                {
                    printf(" %s:0x%x->0x%x", Sim86_RegisterNameFromOperand(&DestinationOperand->Register),
                           Old, *Destination);
                }
#endif
            }
            else if(Decoded.Op == Op_cmp)
            {
                Assert(DestinationOperand->Type == Operand_Register);
                Assert(SourceOperand->Type == Operand_Register || SourceOperand->Type == Operand_Immediate);
                
                s32 Value = (u16)((u16)(*Destination) - ((u16)(*Source)));
                
                FlagsFromValue(&FlagsRegister, Decoded.Flags, Value);
            }
            else if(Decoded.Op == Op_sub)
            {
                Assert(DestinationOperand->Type == Operand_Register);
                Assert(SourceOperand->Type == Operand_Register || SourceOperand->Type == Operand_Immediate);
                
                s32 Old = *Destination;
                *Destination = (u16)((u16)(*Destination) - ((u16)(*Source)));
                printf(" %s:0x%x->0x%x", 
                       Sim86_RegisterNameFromOperand(&DestinationOperand->Register),
                       Old, *Destination);
                
                FlagsFromValue(&FlagsRegister, Decoded.Flags, *Destination);
                
            }
            else if(Decoded.Op == Op_add)
            {
                Assert(DestinationOperand->Type == Operand_Register);
                Assert(SourceOperand->Type == Operand_Register || SourceOperand->Type == Operand_Immediate);
                
                s32 Old = *Destination;
                *Destination = (u16)((u16)(*Destination) + ((u16)(*Source)));
                printf(" %s:0x%x->0x%x", 
                       Sim86_RegisterNameFromOperand(&DestinationOperand->Register),
                       Old, *Destination);
                
                FlagsFromValue(&FlagsRegister, Decoded.Flags, *Destination);
            }
            else if(Decoded.Op == Op_jne)
            {
                if(!(FlagsRegister & Flag_Zero))
                {
                    IPRegister += *Destination;
                }
            }
            else if(Decoded.Op == Op_je)
            {
                if((FlagsRegister & Flag_Zero))
                {
                    IPRegister += *Destination;
                }
            }
            else
            {
                Assert(0 && "Op not implemented yet.");
            }
            
#if SIM86_INTERNAL
            printf(" ip:0x%x->0x%x", OldIPRegister, IPRegister);
#endif
            
        }
        else
        {
            printf("Unrecognized instruction\n");
            break;
        }
        
#if SIM86_INTERNAL
        printf("\n");
#endif
        
    }
    
    printf("Final registers:\n");
    for(u32 RegisterIndex = Register_a;
        RegisterIndex < Register_ds + 1;
        RegisterIndex++)
    {
        register_access Register = {};
        Register.Index = RegisterIndex;
        Register.Offset = 0;
        Register.Count = 2;
        
        u32 Value = Registers[RegisterIndex];
        if(Value > 0)
        {
            printf("     %s: 0x%0x (%d)\n", 
                   Sim86_RegisterNameFromOperand(&Register),
                   Value, Value);
        }
    }
    printf("     ip: 0x%04x (%d)\n", IPRegister, IPRegister);
    
    char FlagsString[ArrayCount(FlagToCharMapping)] = {};
    FlagsToString(FlagsString, FlagsRegister);
    printf("  flags: %s\n", FlagsString);
}

void PrintUsage(char *ExePath)
{
    fprintf(stderr, "usage: %s [-exec] <assembly>\n", ExePath);
}

int main(int ArgCount, char *Args[])
{
    u32 Version = Sim86_GetVersion();
    
#if SIM86_INTERNAL    
    printf("Sim86 Version: %u (expected %u)\n", Version, SIM86_VERSION);
#endif
    
    if(Version != SIM86_VERSION)
    {
        printf("ERROR: Header file version doesn't match DLL.\n");
        return -1;
    }
    
    instruction_table Table;
    Sim86_Get8086InstructionTable(&Table);
    
#if SIM86_INTERNAL    
    printf("8086 Instruction Instruction Encoding Count: %u\n", Table.EncodingCount);
#endif
    
    // print (default)
    // -exec (also execute the disassembled instructinos)
    
    b32 Execute = false;
    char *FileName = 0;
    if(ArgCount == 2)
    {
        FileName = Args[1];
        Execute = false;
        // Print disassembly from assembly
    }
    else if(ArgCount == 3)
    {
        char *Command = Args[1];
        FileName = Args[2];
        if(!strcmp(Command, "-exec"))
        {
            Execute = true;
        }
        else
        {
            fprintf(stderr, "ERROR: Unknown command %s.\n", Command);
            PrintUsage(Args[0]);
        }
    }
    else
    {
        PrintUsage(Args[0]);
    }
    
    u8 Memory[1024] = {};
    if(FileName)
    {
        FILE *File = fopen(FileName, "rb");
        if(File)
        {
            psize Result = fread(Memory, 1, sizeof(Memory), File);
            fclose(File);
            
            if(Execute)
            {
                printf("--- %s execution ---\n", FileName);
                
                Run8086(Result, Memory);
            }
            else
            {
                fprintf(stderr, "ERROR: Disassembling not implemented yet.\n");
            }
            
        }
        else
        {
            fprintf(stderr, "ERROR: Unable to open %s.\n", FileName);
            PrintUsage(Args[0]);
        }
    }
    
    return 0;
}