sim: fixed for tilab
[calu.git] / 3b_sim / sim.cpp
1 #include <iostream>
2 #include <iomanip>
3 #include <fstream>
4 #include <boost/tokenizer.hpp>
5 #include <boost/program_options.hpp>
6 #include <boost/lexical_cast.hpp>
7 #include <string>
8 #include <map>
9 #include <list>
10
11 #include <boost/function.hpp>
12 #include <boost/functional.hpp>
13 #include <boost/tuple/tuple.hpp>
14
15 #include "disasm.h"
16 #include "ccpu.hpp"
17 #include "CInstrFactory.hpp"
18 #include "uint32_from_hex.hpp"
19
20 #include "SReadline/SReadline.h"
21 using namespace swift;
22
23 #define RAM_END (1000)
24 #define PROG_END (1000)
25 #define REG_COUNT (16)
26
27 typedef boost::function<void (const vector<string> &)> Func;
28 typedef boost::tuple<string, Func, string> CompleterElement;
29
30 typedef list<CompleterElement> MyCompleterContainer;
31
32 class LookupFunctor
33 {
34         public:
35                 // Creates a functor and memorises tokens
36                 LookupFunctor(const vector<string>&  tokens) : Tokens(tokens) {}
37
38                 // Compares the first token only
39                 bool operator()(const CompleterElement& ele) const
40                 {
41                         return (strncmp(Tokens.begin()->c_str(), ele.get<0>().c_str(), Tokens.begin()->size()) == 0);
42                 }
43
44         private:
45                 const vector<string> &Tokens;
46 };
47
48
49
50
51 class CHelpExec
52 {
53         private:
54                 const MyCompleterContainer &m_completers;
55
56         public:
57                 CHelpExec(const MyCompleterContainer &cont) : m_completers(cont) {}
58
59                 void operator() (const vector<string>&)
60                 {
61                         cout << "Available commands: " << endl;
62                         for(auto iter = m_completers.begin(); iter != m_completers.end(); ++iter) {
63                                 cout << setw(15) << (*iter).get<0>() << ": " << (*iter).get<2>() << endl;
64                         }
65                 }
66 };
67
68 void close_prog(const std::vector<std::string> &);
69
70 CCpu* Iinstr::m_cpu;
71
72 CCpu* global_cpu = NULL;
73
74 vector<CDat> breakpoints;
75
76 bool ignoreBreak = false;
77
78 void doExit(const vector<string>&)
79 {
80         exit(EXIT_SUCCESS);
81 }
82
83 unsigned int convertStringToNum(const std::string& in)
84 {
85         if(in.substr(0,2) == "0x") {
86                 return lexical_cast<uint32_from_hex>(in);
87         }
88         else {
89                 return lexical_cast<unsigned int>(in);
90         }
91 }
92
93
94 void execStep(const vector<string>& in)
95 {
96         int count = 1;
97         if(in.size() == 2) {
98                 try {
99                         count = convertStringToNum(in.back());
100                 }
101                 catch(bad_cast&) {
102                         cerr << "given parameter to step is not a number" << endl;
103                 }
104         }
105         while(count > 0) {
106                 try {
107                         auto breakp = find(breakpoints.begin(), breakpoints.end(), global_cpu->getNextPC());
108                         if(breakp == breakpoints.end() || ignoreBreak) {
109                                 global_cpu->tick();
110                                 ignoreBreak = false;
111                         }
112                         else {
113                                 ignoreBreak = true;
114                                 cout << "Breakpoint 0x" << std::hex << setw(8) << setfill('0') << *breakp << std::hex << " hit" << endl;
115                                 break;
116                         }
117                 }
118                 catch(std::string& e) {
119                         cerr << e << endl;
120                 }
121                 count--;
122         }
123 }
124
125 void execRun(const vector<string>&)
126 {
127         while(1) {
128                 try {
129                         auto breakp = find(breakpoints.begin(), breakpoints.end(), global_cpu->getNextPC());
130                         if(breakp == breakpoints.end() || ignoreBreak) {
131                                 global_cpu->tick();
132                                 ignoreBreak = false;
133                         }
134                         else {
135                                 ignoreBreak = true;
136                                 cout << "Breakpoint 0x" << std::hex << setw(8) << setfill('0') << *breakp << std::hex << " hit" << endl;
137                                 return;
138                         }
139                 }
140                 catch(std::string& e) {
141                         cerr << e << endl;
142                         return;
143                 }
144         }
145 }
146
147 void setPC(const vector<string>& in)
148 {
149         CDat addr = 0;
150         if(in.size() == 2) {
151                 try {
152                         addr = convertStringToNum(in.back());
153                 }
154                 catch(bad_cast&) {
155                         cerr << "given parameter is not a number" << endl;
156                         return;
157                 }
158         }
159         global_cpu->setNextPC(addr);
160         cout << "Set programcounter to 0x" << std::hex << setw(8) << setfill('0') << addr << std::dec << endl;
161 }
162
163
164 void printReg(const vector<string>& in)
165 {
166         int i, start = 0, end = REG_COUNT-1;
167         /* Todo: 
168          * 1) make 2 columns
169          */
170
171         if(in.size() >= 2) {
172                 try {
173                         start = convertStringToNum(in[1]);
174                         if(start < 0 || start > (REG_COUNT-1)) {
175                                 cerr << "start is out of range" << endl;
176                                 return;
177                         }
178                         end = start;
179                 }
180                 catch(bad_cast&) {
181                         cerr << "given parameter is not a number" << endl;
182                         return;
183                 }
184         }
185
186         if(in.size() >= 3) {
187                 try {
188                         end = convertStringToNum(in[2]);
189                         if(start > end || end > (REG_COUNT-1)) {
190                                 cerr << "end is out of range or smaller than start" << endl;
191                                 return;
192                         }
193                 }
194                 catch(bad_cast&) {
195                         cerr << "given parameter is not a number" << endl;
196                         return;
197                 }
198         }
199         
200         for(i = start; i <= end; i++) {
201                 cout << setw(2) << setfill('0') << i << ": 0x";
202                 cout << std::hex <<  setw(8) << setfill('0') << global_cpu->getRegister(i) << " ";
203                 cout << std::dec << setw(10) << setfill(' ') << global_cpu->getRegister(i) << " ";
204                 cout << std::dec << setw(10) << setfill(' ') << (int)global_cpu->getRegister(i) << endl;
205         }
206 }
207
208 void setReg(const vector<string>& in)
209 {
210         int reg = 0;
211         CDat val = 0;
212
213         if(in.size() >= 3) {
214                 try {
215                         reg = convertStringToNum(in[1]);
216                         if(reg < 0 || reg > (REG_COUNT-1)) {
217                                 cerr << "register is out of range" << endl;
218                                 return;
219                         }
220
221                         val = convertStringToNum(in[2]);
222
223                         cout << "Setting register " << reg << " to 0x" << std::hex << setw(8) << setfill('0') << val << std::dec << endl;
224                         global_cpu->setRegister(reg,val);
225                 }
226                 catch(bad_cast&) {
227                         cerr << "given parameter is not a number" << endl;
228                         return;
229                 }
230         }
231 }
232
233 void printRAM(const vector<string>& in)
234 {
235         int i, start = 0, end = 15;
236         /* Todo: 
237          * 1) make 2 columns
238          */
239
240         if(in.size() >= 2) {
241                 try {
242                         start = convertStringToNum(in[1]);
243                         if(start < 0 || start > (RAM_END-1)) {
244                                 cerr << "start is out of range" << endl;
245                                 return;
246                         }
247                         start = (start & (~(BYTE_COUNT-1))) / BYTE_COUNT;
248                         end = start;
249                 }
250                 catch(bad_cast&) {
251                         cerr << "given parameter is not a number" << endl;
252                         return;
253                 }
254         }
255
256         if(in.size() >= 3) {
257                 try {
258                         end = convertStringToNum(in[2]);
259                         if(start > end || end > (RAM_END-1)) {
260                                 cerr << "end is out of range or smaller than start" << endl;
261                                 return;
262                         }
263                         if(end % BYTE_COUNT != 0) {
264                                 end = ((end & (~(BYTE_COUNT-1))) / BYTE_COUNT)+1;
265                         }
266                         else {
267                                 end = ((end & (~(BYTE_COUNT-1))) / BYTE_COUNT);
268                         }
269                 }
270                 catch(bad_cast&) {
271                         cerr << "given parameter is not a number" << endl;
272                         return;
273                 }
274         }
275         for(i = start*BYTE_COUNT; i <= end*BYTE_COUNT; i += BYTE_COUNT) {
276                 cout << std::hex << "0x" << setw(8) << setfill('0') << i << ": 0x";
277                 cout << std::hex << setw(8)  << setfill('0') << global_cpu->getRAM(i) << " ";
278                 cout << std::dec << setw(10) << setfill(' ') << global_cpu->getRAM(i) << " ";
279                 cout << std::dec << setw(10) << setfill(' ') << (int)global_cpu->getRAM(i) << endl;
280         }
281 }
282
283 void setRam(const vector<string>& in)
284 {
285         int addr = 0;
286         CDat val = 0;
287
288         if(in.size() >= 3) {
289                 try {
290                         addr = convertStringToNum(in[1]);
291                         if(addr < 0 || addr > (RAM_END-1)) {
292                                 cerr << "RAM-Address is out of range" << endl;
293                                 return;
294                         }
295
296                         addr = (addr & (~(BYTE_COUNT-1))) / BYTE_COUNT;
297                         val = convertStringToNum(in[2]);
298
299                         cout << "Setting RAM-Address " << addr << " to 0x" << std::hex << setw(8) << setfill('0') << val << std::dec << endl;
300                         global_cpu->setRAM(addr,val);
301                 }
302                 catch(bad_cast&) {
303                         cerr << "given parameter is not a number" << endl;
304                         return;
305                 }
306         }
307 }
308 void printPROG(const vector<string>& in)
309 {
310         int i, start = 0, end = 15;
311         /* Todo: 
312          * 1) make 2 columns
313          */
314
315         if(in.size() >= 2) {
316                 try {
317                         start = convertStringToNum(in[1]);
318                         if(start < 0 || start > (PROG_END-1)) {
319                                 cerr << "start is out of range" << endl;
320                                 return;
321                         }
322                         start = (start & (~(BYTE_COUNT-1))) / BYTE_COUNT;
323                         end = start;
324                 }
325                 catch(bad_cast&) {
326                         cerr << "given parameter is not a number" << endl;
327                         return;
328                 }
329         }
330
331         if(in.size() >= 3) {
332                 try {
333                         end = convertStringToNum(in[2]);
334                         if(start > end || end > (PROG_END-1)) {
335                                 cerr << "end is out of range or smaller than start" << endl;
336                                 return;
337                         }
338                         if(end % BYTE_COUNT != 0) {
339                                 end = ((end & (~(BYTE_COUNT-1))) / BYTE_COUNT)+1;
340                         }
341                         else {
342                                 end = ((end & (~(BYTE_COUNT-1))) / BYTE_COUNT);
343                         }
344
345                 }
346                 catch(bad_cast&) {
347                         cerr << "given parameter is not a number" << endl;
348                         return;
349                 }
350         }
351         
352         for(i = start*BYTE_COUNT; i <= end*BYTE_COUNT; i += BYTE_COUNT) {
353                 Iinstr* pi = global_cpu->getProg(i);
354                 if(pi == NULL) {
355                         cout << std::hex << "0x" << setw(8) << setfill('0') << i << ": NOP" << endl;
356                 }
357                 else {
358                         cout << std::hex << "0x" << setw(8) << setfill('0') << i << ": " << std::dec << pi->toString() << endl;
359                 }
360         }
361 }
362
363 void setBreak(const vector<string>& in)
364 {
365         unsigned int addr = 0;
366         if(in.size() == 2) {
367                 try {
368                         addr = convertStringToNum(in.back());
369                         breakpoints.push_back(addr);
370                         cout << "Breakpoint 0x" << std::hex << setw(8) << setfill('0') << addr << std::dec << " set" << endl;
371                 }
372                 catch(bad_cast&) {
373                         cerr << "Given parameter is not a valid address" << endl;
374                 }
375         }
376         else {
377                 cerr << "Invalid parameter count!" << endl;
378         }
379 }
380
381 void listBreaks(const vector<string>&)
382 {
383         for(auto iter = breakpoints.begin(); iter != breakpoints.end(); ++iter) {
384                 cout << "Breakpoint at 0x" << std::hex << setw(8) << setfill('0') << *iter << std::dec << endl;
385         }
386 }
387
388 void printStatus(const vector<string>&)
389 {
390         CDat stackp = global_cpu->getStack();
391         CDat stackd = global_cpu->getRAM(stackp);
392         cout << "Stack pointer: " << stackp << " @stackpointer: " << stackd << endl;
393         cout << "PSW: 0x" << std::hex << setw(8) << setfill('0') << global_cpu->getFlags() << std::dec << endl;
394         cout << "cur PC: 0x" << std::hex << setw(8) << setfill('0') << global_cpu->getCurPC() << " next PC: 0x" << setw(8) << setfill('0') << global_cpu->getNextPC() << std::dec << endl;
395
396 }
397
398 using boost::lexical_cast;
399 using boost::bad_lexical_cast;
400
401 using namespace std;
402
403 using namespace boost::program_options;
404 namespace po = boost::program_options;
405
406 std::string progName;
407
408 int main(int argc, char* argv[])
409 {
410         progName = argv[0];
411         ifstream inFile;
412         try {
413                 po::options_description desc("Allowed options");
414                 desc.add_options()
415                 ("help,h","produce help message")
416                 ("file,f",value<string>(), "input file")
417                 ;
418
419                 po::positional_options_description p;
420                 p.add("file",1);
421
422                 po::variables_map vm;
423                 po::store(po::command_line_parser(argc, argv).options(desc).positional(p).run(), vm);
424                 po::notify(vm);
425
426                 if(vm.count("help")) {
427                         cout << desc << endl;
428                         return EXIT_FAILURE;
429                 }
430
431                 if(vm.count("file")) {
432 #ifdef DEBUG 
433                         cout << "going to open file " << vm["file"].as<string>() << endl;
434 #endif
435                         inFile.open(vm["file"].as<string>(), ios::in);
436                         if(!inFile) {
437                                 cerr << "Error opening file " << vm["file"].as<string>() << endl;
438                                 return EXIT_FAILURE;
439                         }
440                 }
441                 else {
442                         cout << "not input file given!" << endl << endl;
443                         cout << desc << endl;
444                         return EXIT_FAILURE;
445                 }
446         }
447         catch(std::exception& ex) {
448                 cout << ex.what() << endl;
449         }
450
451
452         string dir = "./instr/";
453
454         map<short, Iinstr*> instr;
455
456         CInstrFactory instrFab;
457         try {
458                 instrFab.loadLibsIntoMap(instr, dir);
459         }
460         catch(std::bad_alloc& e) {
461                 cerr << progName << ": bad_alloc caught " << e.what() << endl;
462                 exit(EXIT_FAILURE); 
463         }
464         catch(std::string& s) {
465                 cerr << progName << ": " << s << endl;
466                 exit(EXIT_FAILURE);
467         }
468
469         CCpu cpu(REG_COUNT, RAM_END, PROG_END);
470
471         global_cpu = &cpu;
472
473         Iinstr::setCPU(&cpu);
474
475
476         std::string str = "";
477         int addr = 0;
478         boost::char_separator<char> sep(";", "", boost::keep_empty_tokens);
479         boost::tokenizer<boost::char_separator<char> > tokens(str, sep);
480         disasm disasm(instr);
481         while(getline(inFile, str)) {
482                 int count = 0;
483                 tokens.assign(str);
484                 stringstream out;
485                 int type = 0;
486                 for(auto tok_iter = tokens.begin(); tok_iter != tokens.end(); ++tok_iter) {
487                         if(tok_iter == tokens.begin()) {
488                                 try {
489                                         type = lexical_cast<int>(*tok_iter);
490                                         count++;
491                                         continue;
492                                 }
493                                 catch(bad_lexical_cast &) {
494                                         break;
495                                 }
496                                 cout << endl;
497                         }
498                         switch(type) {
499                                 case 0:
500                                         if(count == 1) {
501                                                 try {
502                                                         addr = lexical_cast<uint32_from_hex>(*tok_iter);
503                                                 }
504                                                 catch(bad_lexical_cast& e) {
505                                                         cerr << e.what() << endl;
506                                                         exit(EXIT_FAILURE);
507                                                 }
508                                         }
509                                         else if(count == 2) {
510                                                 try {
511                                                         CDat data = lexical_cast<uint32_from_hex>(*tok_iter);
512                                                         cpu.setRAM(addr, data);
513                                                 }
514                                                 catch(bad_lexical_cast& e) {
515                                                         cerr << e.what() << endl;
516                                                         exit(EXIT_FAILURE);
517                                                 }
518                                         }
519                                         break;
520                                 case 1:
521                                         if(count == 1) {
522                                                 try {
523                                                         addr = lexical_cast<uint32_from_hex>(*tok_iter);
524                                                 }
525                                                 catch(bad_lexical_cast& e) {
526                                                         cerr << e.what() << endl;
527                                                         exit(EXIT_FAILURE);
528                                                 }
529                                         }
530                                         else if(count == 2) {
531                                                 Iinstr *pi = disasm.decode(*tok_iter);
532                                                 cpu.setProg(addr, pi);
533                                         }
534                                         break;
535                                 case 2:
536                                 case 3:
537                                         cerr << "ignoring labels and comments for now" << endl;
538                                         break;
539                                 default:
540                                         cerr << "i was to lazy to implement the other format types for now" << endl;
541                         }
542                         count++;
543                 }
544         }
545         inFile.close();
546
547         cout << endl;
548
549 /*
550         for(int i = 0; i <= 32; i += 4) {
551                 Iinstr *pinstr = cpu.getProg(i);
552                 if(pinstr != NULL) {
553                         cout << i << " : " << std::hex << i << std::dec << " " << pinstr->toString() << endl;
554                 }
555                 else {
556                         cout << "Null at " << i << " : " << std::hex << i << endl;
557                 }
558         }
559
560         for(int i = 0; i <= 32; i += 4) {
561                 CDat data = cpu.getRAM(i);
562                 cout << i << " : " << std::hex << i << std::dec << " " << data << endl;
563         }
564 */
565         cpu.setRegister(1, 4);
566         cpu.setRegister(2, 0);
567         cpu.setRAM(0,5);
568         cpu.setRAM(4,50);
569         cpu.setRAM(8,32);
570         cpu.setRAM(12,45);
571
572         // following: job of the bootloader
573         //set stackpointer
574         cpu.setStack(500);
575         //set return to nowhere for ret
576         cpu.setRAM(500,50);
577
578         SReadline Reader;
579
580         MyCompleterContainer Completers;
581
582         CHelpExec HelpExec(Completers);
583
584         Completers.push_back(CompleterElement("help", boost::bind1st( boost::mem_fun( &CHelpExec::operator()), &HelpExec), "Prints this message"));
585         Completers.push_back(CompleterElement("quit", &doExit, "Exits program"));
586         Completers.push_back(CompleterElement("exit", &doExit, "Exits program"));
587         Completers.push_back(CompleterElement("step [count]",&execStep, "Runs [count] ticks. if count is not given one tick is executed."));
588         Completers.push_back(CompleterElement("dreg [s] [e]",&printReg, "Prints registers. if s is given, only register s is printed. if s and e are given the registers from s to e are printed. if omitted all registers a printed."));
589         Completers.push_back(CompleterElement("ddata [s] [e]",&printRAM, "Prints RAM. if s is given, only RAM-Addr. s is printed. if s and e are given the RAM-Addrs from s to e are printed. if omitted the first 16 RAM-Addrs are printed."));
590         Completers.push_back(CompleterElement("dprog [s] [e]",&printPROG, "Prints program. if s is given, only Prog-Addr. s is printed. if s and e are given the Prog-Addrs from s to e are printed. if omitted the first 16 Prog-Addrs are printed."));
591         Completers.push_back(CompleterElement("break addr",&setBreak, "Sets a breakpoint for address addr."));
592         Completers.push_back(CompleterElement("listbreaks",&listBreaks, "Lists all breakpoints."));
593         Completers.push_back(CompleterElement("run",&execRun, "Runs till next breakpoint or end of program."));
594         Completers.push_back(CompleterElement("setpc [num]",&setPC, "Sets PC to num. if num is omitted 0 is used."));
595         Completers.push_back(CompleterElement("setreg [s] [num]",&setReg, "Sets Register s to num."));
596         Completers.push_back(CompleterElement("setdata [s] [num]",&setRam, "Sets RAM-Addr s to num."));
597         Completers.push_back(CompleterElement("status",&printStatus, "Prints status of CPU."));
598
599         Reader.RegisterCompletions(Completers);
600
601         string UserInput;
602         vector<string> Tokens, lastTokens;
603         bool EndOfInput = false;
604
605         //tilab g++44 doesn't like auto here
606         MyCompleterContainer::iterator Found(Completers.end());
607
608         Func lastFunc = NULL;
609
610
611         while(1) {
612                 UserInput = Reader.GetLine("> ", Tokens, EndOfInput);
613                 if(EndOfInput) {
614                         break;
615                 }
616
617                 if(!Tokens.empty()) {
618                         Found = find_if(Completers.begin(), Completers.end(), LookupFunctor(Tokens));
619
620                         if(Found != Completers.end()) {
621                                 if((*Found).get<1>() != 0) {
622                                         lastFunc = (*Found).get<1>();
623                                         lastFunc(Tokens);
624                                         lastTokens = Tokens;
625                                         //(*Found).get<1>()(Tokens);
626                                 }
627                         }
628                         else {
629                                 lastFunc = NULL;
630                                 cout << "Unknown command. 'help' displays help" << endl;
631                         }
632                 }
633                 else {
634                         if(lastFunc != NULL) {
635                                 lastFunc(lastTokens);
636                         }
637                         else {
638                                 cout << "Unknown command. 'help' displays help" << endl;
639                         }
640                 }
641         }
642
643
644 /*
645         for(int i = 0; ; i++) {
646                 try {
647                         cpu.tick();
648                         cout << " reg0: " << cpu.getRegister(0) <<  " reg1: " << cpu.getRegister(1);
649                         cout << " reg2: " << cpu.getRegister(2) <<  " reg3: " << cpu.getRegister(3);
650                         cout << " reg4: " << cpu.getRegister(4) <<  " reg5: " << cpu.getRegister(5);
651                         cout << endl << endl;
652
653                 }
654                 catch(string& e) {
655                         cerr << e << endl;
656                         break;
657                 }
658         }
659 */
660         return EXIT_SUCCESS;
661 }