c-programming

Simple C programs
git clone git://git.laack.co/c-programming.git
Log | Files | Refs

sim86_decode.cpp (9365B)


      1 /* ========================================================================
      2 
      3    (C) Copyright 2023 by Molly Rocket, Inc., All Rights Reserved.
      4    
      5    This software is provided 'as-is', without any express or implied
      6    warranty. In no event will the authors be held liable for any damages
      7    arising from the use of this software.
      8    
      9    Please see https://computerenhance.com for more information
     10    
     11    ======================================================================== */
     12 
     13 instruction_format InstructionFormats[] =
     14 {
     15 #include "sim86_instruction_table.inl"
     16 };
     17 
     18 static disasm_context DefaultDisAsmContext(void)
     19 {
     20     disasm_context Result = {};
     21     
     22     Result.DefaultSegment = Register_ds;
     23     
     24     return Result;
     25 }
     26 
     27 static instruction_operand GetRegOperand(u32 IntelRegIndex, b32 Wide)
     28 {
     29     // NOTE(casey): This maps Intel's REG and RM field encodings for registers to our encoding for registers.
     30     register_access RegTable[][2] =
     31     {
     32         {{Register_a, 0, 1}, {Register_a, 0, 2}},
     33         {{Register_c, 0, 1}, {Register_c, 0, 2}},
     34         {{Register_d, 0, 1}, {Register_d, 0, 2}},
     35         {{Register_b, 0, 1}, {Register_b, 0, 2}},
     36         {{Register_a, 1, 1}, {Register_sp, 0, 2}},
     37         {{Register_c, 1, 1}, {Register_bp, 0, 2}},
     38         {{Register_d, 1, 1}, {Register_si, 0, 2}},
     39         {{Register_b, 1, 1}, {Register_di, 0, 2}},
     40     };
     41     
     42     instruction_operand Result = {};
     43     Result.Type = Operand_Register;
     44     Result.Register = RegTable[IntelRegIndex & 0x7][(Wide != 0)];
     45     
     46     return Result;
     47 }
     48 
     49 // NOTE(casey): ParseDataValue is not a real function, it's basically just a macro that is used in
     50 // TryParse. It should never be called otherwise, but that is not something you can do in C++.
     51 // In other languages it would be a "local function".
     52 static u32 ParseDataValue(memory *Memory, segmented_access *Access, b32 Exists, b32 Wide, b32 SignExtended)
     53 {
     54     u32 Result = {};
     55     
     56     if(Exists)
     57     {
     58         if(Wide)
     59         {
     60             u8 D0 = ReadMemory(Memory, GetAbsoluteAddressOf(*Access, 0));
     61             u8 D1 = ReadMemory(Memory, GetAbsoluteAddressOf(*Access, 1));
     62             Result = (D1 << 8) | D0;
     63             Access->SegmentOffset += 2;
     64         }
     65         else
     66         {
     67             Result = ReadMemory(Memory, GetAbsoluteAddressOf(*Access));
     68             if(SignExtended)
     69             {
     70                 Result = (s32)*(s8 *)&Result;
     71             }
     72             Access->SegmentOffset += 1;
     73         }
     74     }
     75     
     76     return Result;
     77 }
     78 
     79 static instruction TryDecode(disasm_context *Context, instruction_format *Inst, memory *Memory, segmented_access At)
     80 {
     81     instruction Dest = {};
     82     u32 HasBits = 0;
     83     u32 Bits[Bits_Count] = {};
     84     b32 Valid = true;
     85     
     86     u32 StartingAddress = GetAbsoluteAddressOf(At);
     87     
     88     u8 BitsPendingCount = 0;
     89     u8 BitsPending = 0;
     90     for(u32 BitsIndex = 0; Valid && (BitsIndex < ArrayCount(Inst->Bits)); ++BitsIndex)
     91     {
     92         instruction_bits TestBits = Inst->Bits[BitsIndex];
     93         if((TestBits.Usage == Bits_Literal) && (TestBits.BitCount == 0))
     94         {
     95             // NOTE(casey): That's the end of the instruction format.
     96             break;
     97         }
     98         
     99         u32 ReadBits = TestBits.Value;
    100         if(TestBits.BitCount != 0)
    101         {
    102             if(BitsPendingCount == 0)
    103             {
    104                 BitsPendingCount = 8;
    105                 BitsPending = ReadMemory(Memory, GetAbsoluteAddressOf(At));
    106                 ++At.SegmentOffset;
    107             }
    108             
    109             // NOTE(casey): If this assert fires, it means we have an error in our table,
    110             // since there are no 8086 instructions that have bit values straddling a
    111             // byte boundary.
    112             assert(TestBits.BitCount <= BitsPendingCount);
    113             
    114             BitsPendingCount -= TestBits.BitCount;
    115             ReadBits = BitsPending;
    116             ReadBits >>= BitsPendingCount;
    117             ReadBits &= ~(0xff << TestBits.BitCount);
    118         }
    119         
    120         if(TestBits.Usage == Bits_Literal)
    121         {
    122             // NOTE(casey): This is a "required" sequence
    123             Valid = Valid && (ReadBits == TestBits.Value);
    124         }
    125         else
    126         {
    127             Bits[TestBits.Usage] |= (ReadBits << TestBits.Shift);
    128             HasBits |= (1 << TestBits.Usage);
    129         }
    130     }
    131     
    132     if(Valid)
    133     {
    134         u32 Mod = Bits[Bits_MOD];
    135         u32 RM = Bits[Bits_RM];
    136         u32 W = Bits[Bits_W];
    137         b32 S = Bits[Bits_S];
    138         b32 D = Bits[Bits_D];
    139         
    140         b32 HasDirectAddress = ((Mod == 0b00) && (RM == 0b110));
    141         b32 HasDisplacement = ((Bits[Bits_HasDisp]) || (Mod == 0b10) || (Mod == 0b01) || HasDirectAddress);
    142         b32 DisplacementIsW = ((Bits[Bits_DispAlwaysW]) || (Mod == 0b10) || HasDirectAddress);
    143         b32 DataIsW = ((Bits[Bits_WMakesDataW]) && !S && W);
    144         
    145         Bits[Bits_Disp] |= ParseDataValue(Memory, &At, HasDisplacement, DisplacementIsW, (!DisplacementIsW));
    146         Bits[Bits_Data] |= ParseDataValue(Memory, &At, Bits[Bits_HasData], DataIsW, S);
    147         
    148         Dest.Op = Inst->Op;
    149         Dest.Flags = Context->AdditionalFlags;
    150         Dest.Address = StartingAddress;
    151         Dest.Size = GetAbsoluteAddressOf(At) - StartingAddress;
    152         if(W)
    153         {
    154             Dest.Flags |= Inst_Wide;
    155         }
    156         
    157         u32 Disp = Bits[Bits_Disp];
    158         s16 Displacement = (s16)Disp;
    159         
    160         instruction_operand *RegOperand = &Dest.Operands[D ? 0 : 1];
    161         instruction_operand *ModOperand = &Dest.Operands[D ? 1 : 0];
    162         
    163         if(HasBits & (1 << Bits_SR))
    164         {
    165             RegOperand->Type = Operand_Register;
    166             RegOperand->Register.Index = (register_index)(Register_es + (Bits[Bits_SR] & 0x3));
    167             RegOperand->Register.Count = 2;
    168         }
    169         
    170         if(HasBits & (1 << Bits_REG))
    171         {
    172             *RegOperand = GetRegOperand(Bits[Bits_REG], W);
    173         }
    174         
    175         if(HasBits & (1 << Bits_MOD))
    176         {
    177             if(Mod == 0b11)
    178             {
    179                 *ModOperand = GetRegOperand(RM, W || (Bits[Bits_RMRegAlwaysW]));
    180             }
    181             else
    182             {
    183                 ModOperand->Type = Operand_Memory;
    184                 ModOperand->Address.Segment = Context->DefaultSegment;
    185                 ModOperand->Address.Displacement = Displacement;
    186                 
    187                 if((Mod == 0b00) && (RM == 0b110))
    188                 {
    189                     ModOperand->Address.Base = EffectiveAddress_direct;
    190                 }
    191                 else
    192                 {
    193                     ModOperand->Address.Base = (effective_address_base)(1+RM);
    194                 }
    195             }
    196         }
    197         
    198         //
    199         // NOTE(casey): Because there are some strange opcodes that do things like have an immediate as
    200         // a _destination_ ("out", for example), I define immediates and other "additional operands" to
    201         // go in "whatever slot was not used by the reg and mod fields".
    202         //
    203         
    204         instruction_operand *LastOperand = &Dest.Operands[0];
    205         if(LastOperand->Type)
    206         {
    207             LastOperand = &Dest.Operands[1];
    208         }
    209         
    210         if(Bits[Bits_RelJMPDisp])
    211         {
    212             LastOperand->Type = Operand_RelativeImmediate;
    213             LastOperand->ImmediateS32 = Displacement + Dest.Size;
    214         }
    215         
    216         if(Bits[Bits_HasData])
    217         {
    218             LastOperand->Type = Operand_Immediate;
    219             LastOperand->ImmediateU32 = Bits[Bits_Data];
    220         }
    221         
    222         if(HasBits & (1 << Bits_V))
    223         {
    224             if(Bits[Bits_V])
    225             {
    226                 LastOperand->Type = Operand_Register;
    227                 LastOperand->Register.Index = Register_c;
    228                 LastOperand->Register.Offset = 0;
    229                 LastOperand->Register.Count = 1;
    230             }
    231             else
    232             {
    233                 LastOperand->Type = Operand_Immediate;
    234                 LastOperand->ImmediateS32 = 1;
    235             }
    236         }
    237     }
    238     
    239     return Dest;
    240 }
    241 
    242 static instruction DecodeInstruction(disasm_context *Context, memory *Memory, segmented_access *At)
    243 {
    244     /* TODO(casey): Hmm. It seems like this is a very inefficient way to parse
    245        instructions, isn't it? For every instruction, we check every entry in the
    246        table until we find a match. Is this bad design? Or did the person who wrote
    247        it know what they were doing, and has a plan for how it can be optimized
    248        later? Only time will tell... :) */
    249     
    250     instruction Result = {};
    251     for(u32 Index = 0; Index < ArrayCount(InstructionFormats); ++Index)
    252     {
    253         instruction_format Inst = InstructionFormats[Index];
    254         Result = TryDecode(Context, &Inst, Memory, *At);
    255         if(Result.Op)
    256         {
    257             At->SegmentOffset += Result.Size;
    258             break;
    259         }
    260     }
    261     
    262     return Result;
    263 }
    264 
    265 static void UpdateContext(disasm_context *Context, instruction Instruction)
    266 {
    267     if(Instruction.Op == Op_lock)
    268     {
    269         Context->AdditionalFlags |= Inst_Lock;
    270     }
    271     else if(Instruction.Op == Op_rep)
    272     {
    273         Context->AdditionalFlags |= Inst_Rep;
    274     }
    275     else if(Instruction.Op == Op_segment)
    276     {
    277         Context->AdditionalFlags |= Inst_Segment;
    278         Context->DefaultSegment = Instruction.Operands[1].Register.Index;
    279     }
    280     else
    281     {
    282         Context->AdditionalFlags = 0;
    283         Context->DefaultSegment = Register_ds;
    284     }
    285 }