cpp-programming

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

sim.cpp (11207B)


      1 #include <cstdint>
      2 #include <filesystem>
      3 #include <unordered_map>
      4 #include <fstream>
      5 #include <string>
      6 #include <vector>
      7 #include <unistd.h>
      8 #include <iostream>
      9 
     10 enum Mnemonic {
     11     MOV,
     12     ADD,
     13     SUB,
     14     CMP,
     15     JNZ,
     16     FN,
     17     UNKNOWN
     18 };
     19 
     20 void printMnemonic(Mnemonic mn) {
     21     switch(mn) {
     22         case (MOV):
     23             std::cout << "mov";
     24             break;
     25         case (SUB):
     26             std::cout << "sub";
     27             break;
     28         case (ADD):
     29             std::cout << "add";
     30             break;
     31         case (CMP):
     32             std::cout << "cmp";
     33             break;
     34         case (JNZ):
     35             std::cout << "jnz";
     36             break;
     37         case (UNKNOWN):
     38             std::cout << "unknown";
     39             break;
     40     }
     41 }
     42 
     43 int isHalfReg(std::string reg) {
     44     if(reg[1] == 'l' || reg[1] == 'h') {
     45         return 1;
     46     }
     47     return 0;
     48 }
     49 
     50 Mnemonic getMnemonic(std::string line) {
     51     if(line.substr(0,3) == "mov") {
     52         return MOV;
     53     }
     54     if(line.substr(0,3) == "add") {
     55         return ADD;
     56     }
     57     if(line.substr(0,3) == "sub") {
     58         return SUB;
     59     }
     60     if(line.substr(0,3) == "cmp") {
     61         return CMP;
     62     }
     63     if(line.substr(0,3) == "jnz") {
     64         return JNZ;
     65     }
     66     if(line.find(":") != std::string::npos) {
     67         return FN;
     68     }
     69     return UNKNOWN;
     70 }
     71 
     72 std::string readFileToString(std::string filePath) {
     73     auto in = std::ifstream(filePath);
     74     std::ostringstream sstr;
     75     sstr << in.rdbuf();
     76     return sstr.str();
     77 }
     78 
     79 
     80 // assumes entire instruction is input
     81 std::pair<std::string, bool> parseDestination(std::string st) { 
     82     std::string source = st.substr(st.find(' ')+1);
     83     if(source.substr(0,4) == "word") {
     84         source = source.substr(5);
     85     }
     86     source = source.substr(source.find(' ')+1);
     87     bool word = false;
     88     if(source.substr(0,4) == "word") {
     89         source = source.substr(5);
     90         word = true;
     91     }
     92     return {source, word};
     93 }
     94 
     95 
     96 // assumes entire instruction is input
     97 std::pair<std::string, bool> parseSource(std::string st, Mnemonic mn) { 
     98     if(mn == FN) {
     99         return {st.substr(0,st.size() - 1), false};
    100     }
    101     else {
    102         std::string source = st.substr(st.find(' ')+1);
    103         source = source.substr(0,source.find(','));
    104         bool word = false;
    105         if(source.substr(0,4) == "word") {
    106             source = source.substr(5);
    107             word = true;
    108         }
    109         return {source, word};
    110     }
    111 }
    112 
    113 void printRegisters(std::vector<std::pair<std::string,uint16_t>> registers) {
    114     for(auto& reg : registers) {
    115         printf("\t%s:\t0x%.2X\n", reg.first.c_str(), reg.second);
    116     }
    117 }
    118 
    119 
    120 // return -1 for not register or byte offset into register vector
    121 int8_t getReg(std::string location) {
    122     if (location == "ax") {
    123         return 0;
    124     }
    125     if (location == "bx") {
    126         return 2;
    127     }
    128     if (location == "cx") {
    129         return 4;
    130     }
    131     if (location == "dx") {
    132         return 6;
    133     }
    134     if (location == "sp") {
    135         return 8;
    136     }
    137     if (location == "bp") {
    138         return 10;
    139     }
    140     if (location == "si") {
    141         return 12;
    142     }
    143     if (location == "di") {
    144         return 14;
    145     }
    146 
    147     return -1;
    148 }
    149 
    150 
    151 
    152 uint16_t valueAt(std::vector<std::pair<std::string,uint16_t>> registers, int idx) {
    153     return registers[idx/2].second;
    154 }
    155 
    156 
    157 uint16_t setSignFlag(bool value, uint16_t original) {
    158     original = original & 0b1101111111111111;
    159     return original + (value << 13);
    160 }
    161 
    162 uint16_t setZeroFlag(bool value, uint16_t original) {
    163     original = original & 0b0111111111111111;
    164     return original + (value << 15);
    165 }
    166 
    167 // return where to jump to
    168 std::pair<std::string, int> handleInstruction(std::string source, std::string dest, std::vector<std::pair<std::string,uint16_t>>& registers, Mnemonic mn, uint16_t in, bool word, std::vector<unsigned char>& memory) {
    169 
    170     if(mn == JNZ) {
    171         if((registers[8].second & 0b1000000000000000) == 0) {
    172             return {source,0};
    173         }
    174         return {"", 0};
    175     }
    176 
    177     auto reg = getReg(source);
    178     int cycles = 0;
    179     if(reg != -1) {
    180         uint32_t cb = 0;
    181         try {
    182             if(isHalfReg(source)) {
    183                 auto before = registers[reg/2].second;
    184                 auto current = registers[reg/2].second;
    185                 if(reg%2 == 1) {
    186                     // lower (right)
    187                     current -= current & 0b0000000011111111;
    188                     current += std::stoi(dest);
    189                 } else {
    190                     // upper (left)
    191                     current -= current & 0b1111111100000000;
    192                     current += std::stoi(dest) << 8;
    193                 }
    194                 registers[reg/2].second = current;
    195                 cb = current;
    196                 printf("\t; 0x%.2X->0x%.2X", before , current);
    197             } else {
    198                 auto before = registers[reg/2].second;
    199                 auto current = std::stoi(dest);
    200                 // immediate -> register
    201                 cycles = 4;
    202 
    203                 if(mn == ADD) {
    204                     current += before; 
    205                 }
    206                 if(mn == SUB || mn == CMP) {
    207                     current = before - current; 
    208                     auto pf = registers[8].second;
    209                     registers[8].second = setZeroFlag(current == 0,registers[8].second);
    210                     registers[8].second = setSignFlag((current & 0x8000)  != 0,registers[8].second);
    211                     printf("\t; start in: 0x%.2X, flag: 0x%.2X->0x%.2X", in, pf , registers[8].second);
    212                 }
    213 
    214                 cb = current;
    215                 if(mn != CMP && mn != FN) {
    216                     registers[reg/2].second = current;
    217                     if(mn == SUB) {
    218                         printf("\t\tval: 0x%.2X->0x%.2X", before , current);
    219                     } else {
    220                         printf("\t; start in: 0x%.2X \t\t\t\tval: 0x%.2X->0x%.2X", in, before , current);
    221                     }
    222                 }
    223             }
    224         
    225         } catch (...) {
    226             auto num = getReg(dest);
    227             if(num == -1) {
    228                 cycles = 14; // ea + mov  reg, mem
    229                 uint16_t destAddr = std::stoi(dest.substr(1,dest.size()-2));
    230                 uint16_t val1 = (memory[destAddr]);
    231                 uint16_t val2 = (memory[destAddr+1]);
    232                 val1 = (val1 << 8);
    233                 uint16_t val = val1 + val2;
    234                 auto src = getReg(source);
    235                 auto before = registers[src/2].second;
    236                 printf("\t; start in: 0x%.2X \t\tval: 0x%.2X->0x%.2X", in, before , val);
    237                 registers[src/2].second = val;
    238                 return {"",cycles};
    239             }
    240             cycles = 2;
    241             auto destVal = valueAt(registers,num);
    242 
    243             auto before = registers[reg/2].second;
    244             auto current = destVal;
    245 
    246             if(mn == ADD) {
    247                 cycles = 3;
    248                 current += before; 
    249             }
    250 
    251             if(mn == SUB || mn == CMP) {
    252                 current = before - current; 
    253                 auto pf = registers[8].second;
    254                 registers[8].second = setZeroFlag(current == 0,registers[8].second);
    255                 registers[8].second = setSignFlag((current & 0x8000)  != 0,registers[8].second);
    256                 printf("\t; start in: 0x%.2X, flag: 0x%.2X->0x%.2X", in, pf , registers[8].second);
    257             }
    258 
    259             if(mn != CMP && mn != FN) {
    260                 registers[reg/2].second = current;
    261                 if(mn == SUB) {
    262                     printf("\t\tval: 0x%.2X->0x%.2X", before , current);
    263                 } else {
    264                     printf("\t; start in: 0x%.2X \t\t\t\tval: 0x%.2X->0x%.2X", in, before , current);
    265                 }
    266             }
    267         }
    268     } else {
    269 
    270         if(mn == FN) {
    271             return {"", 0};
    272         }
    273 
    274         // not moving to register (e.g. store)
    275         std::string sourceVS = source.substr(1);
    276         sourceVS = sourceVS.substr(0,sourceVS.size() - 1);
    277         
    278         uint16_t sourceAddr;
    279 
    280         if(getReg(sourceVS.substr(0,2)) != -1) {
    281             sourceAddr = registers[getReg(sourceVS.substr(0,2)) / 2].second;
    282             sourceAddr += std::stoi(sourceVS.substr(5));
    283         } else {
    284             sourceAddr = std::stoi(sourceVS);
    285         }
    286 
    287         uint16_t destV =  std::stoi(dest); 
    288         // little endian so re-order bytes
    289         uint16_t lower = (destV << 8);
    290         uint16_t upper = (destV >> 8);
    291         destV = lower + upper;
    292 
    293         printf("; start in: 0x%.2X \t\t\tval: 0x%.2X->0x%.2X", memory[sourceAddr] , destV);
    294         memory[sourceAddr]   = upper;
    295         memory[sourceAddr+1] = (lower >> 8);
    296     }
    297     return {"",cycles};
    298 }
    299 int main(int argc, char** argv) {
    300 
    301     std::vector<std::pair<std::string,uint16_t>> registers{};
    302     registers.push_back({"ax",0});
    303     registers.push_back({"bx",0});
    304     registers.push_back({"cx",0});
    305     registers.push_back({"dx",0});
    306     registers.push_back({"sp",0});
    307     registers.push_back({"bp",0});
    308     registers.push_back({"si",0});
    309     registers.push_back({"di",0});
    310     registers.push_back({"flags",0});
    311 
    312     // one limitation of this is we aren't loading the instructions into memory
    313     // but they really do exist there. This is a limitation of the non-binary
    314     // approach where we are basically creating an 8086 interpreter.
    315 
    316     std::vector<unsigned char> memory(1024*1024,0);
    317 
    318     std::string ftext = readFileToString(argv[1]);
    319     std::vector<std::string> lines {};
    320 
    321     std::string acc = "";
    322 
    323     for(size_t i = 0; i < ftext.size(); ++i) {
    324         if(ftext[i] == '\n') {
    325             lines.push_back(acc);
    326             acc = "";
    327         }
    328         else {
    329             acc += ftext[i];
    330         }
    331     }
    332     if(acc != "") {
    333         lines.push_back(acc);
    334     }
    335 
    336 
    337     std::cout << "INSTRUCTIONS:" << std::endl;
    338     
    339     std::unordered_map<std::string, size_t> knownFunctions{};
    340 
    341     int cycles = 0;
    342     for(size_t in = 0; in < lines.size() ; ) {
    343 
    344         auto& line = lines[in];
    345         Mnemonic mne = getMnemonic(line);
    346 
    347         printMnemonic(mne);
    348         if(mne != FN) {
    349             std::cout << " ";
    350         }
    351 
    352         std::pair<std::string, bool> sourceP = parseSource(line, mne);
    353         std::pair<std::string, bool> destP = parseDestination(line);
    354 
    355         auto source = sourceP.first;
    356         auto dest = destP.first;
    357 
    358         if(dest[0] == '+') {
    359             dest = dest.substr(dest.find(']') + 3);
    360         }
    361 
    362         if(mne != FN) {
    363             if(mne != JNZ) {
    364 
    365                 std::cout << source << ", " << dest;
    366             } else {
    367                 std::cout << source;
    368             }
    369         } else {
    370             std::cout << source;
    371             knownFunctions[source] = in;
    372         }
    373         auto pr = handleInstruction(source, dest, registers, mne,in, sourceP.second || destP.second, memory);
    374         std::string res = pr.first;
    375         std::cout << "\tClocks: " << pr.second;
    376         cycles += pr.second;
    377         std::cout <<  std::endl;
    378         
    379         if(res != "") {
    380             in = knownFunctions[source];
    381         } else {
    382             in += 1;
    383         }
    384     }
    385 
    386     std::cout << std::endl;
    387     std::cout << "FINAL REGISTERS:" << std::endl;
    388     printRegisters(registers);
    389     std::cout << std::endl;
    390     std::cout << "CYCLE COUNT:" << std::endl;
    391     std::cout << '\t' << cycles << std::endl;
    392 
    393 }