-
Notifications
You must be signed in to change notification settings - Fork 2
/
EmuMipsElf.c
2353 lines (2151 loc) · 66.3 KB
/
EmuMipsElf.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
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (c) 2013-2015, Alexey Frunze
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
/*****************************************************************************/
/* */
/* EmuMipsElf */
/* */
/* A simple 32-bit MIPS emulator with SPIM system calls support. */
/* */
/* Supports 32-bit ELF executables and non-privileged integer instructions. */
/* */
/* MIPS64, floating point, privileged/system instructions are not */
/* supported. */
/* */
/*****************************************************************************/
#include <limits.h>
#include <stdarg.h>
#include <ctype.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
typedef unsigned char uchar, uint8;
typedef signed char schar, int8;
typedef unsigned short ushort, uint16;
typedef short int16;
#if UINT_MAX >= 0xFFFFFFFF
typedef unsigned uint32;
typedef int int32;
#else
typedef unsigned long uint32;
typedef long int32;
#endif
typedef unsigned uint;
typedef unsigned long ulong;
typedef long long longlong;
typedef unsigned long long ulonglong;
#if ULONG_MAX >= 0xFFFFFFFFFFFFFFFFULL
typedef unsigned long uint64;
typedef long int64;
#else
typedef unsigned long long uint64;
typedef long long int64;
#endif
#define C_ASSERT(expr) extern char CAssertExtern[(expr)?1:-1]
C_ASSERT(CHAR_BIT == 8);
C_ASSERT(sizeof(uint16) == 2);
C_ASSERT(sizeof(uint32) == 4);
C_ASSERT(sizeof(uint64) == 8);
C_ASSERT(sizeof(size_t) >= 4);
#define MAX_FILES 16
FILE* files[MAX_FILES];
FILE* ElfFile = NULL;
char* SectNames = NULL;
uint32 EntryPointAddr = 0;
ulonglong EmulateCnt = 0;
uint32 StartSp, MinSp;
void mycloseall(void);
void error(char* format, ...)
{
va_list vl;
va_start(vl, format);
if (ElfFile)
fclose(ElfFile);
mycloseall();
puts("");
vprintf(format, vl);
printf(" # %lu bytes of stack used\n", (ulong)(StartSp - MinSp));
printf(" # %llu instruction(s) emulated\n\n", EmulateCnt);
va_end(vl);
exit(-1);
}
#pragma pack(push,1)
typedef struct
{
uint8 e_ident[16];
uint16 e_type;
uint16 e_machine;
uint32 e_version;
uint32 e_entry;
uint32 e_phoff;
uint32 e_shoff;
uint32 e_flags;
uint16 e_ehsize;
uint16 e_phentsize;
uint16 e_phnum;
uint16 e_shentsize;
uint16 e_shnum;
uint16 e_shstrndx;
} Elf32Hdr;
typedef struct
{
uint32 sh_name;
uint32 sh_type;
uint32 sh_flags;
uint32 sh_addr;
uint32 sh_offset;
uint32 sh_size;
uint32 sh_link;
uint32 sh_info;
uint32 sh_addralign;
uint32 sh_entsize;
} Elf32SectHdr;
typedef struct
{
uint32 a_magic; /* magic number */
#define OMAGIC 0407 /* old impure format */
uint32 a_text; /* size of text segment */
uint32 a_data; /* size of initialized data */
uint32 a_bss; /* size of uninitialized data */
uint32 a_reltext; /* size of text relocation info */
uint32 a_reldata; /* size of data relocation info */
uint32 a_syms; /* size of symbol table */
uint32 a_entry; /* entry point */
} AoutHdr;
#pragma pack(pop)
C_ASSERT(sizeof(Elf32Hdr) == 52);
C_ASSERT(sizeof(Elf32SectHdr) == 40);
C_ASSERT(sizeof(AoutHdr) == 32);
typedef struct
{
void* Data;
uint32 Addr;
uint32 Size;
uint32 Flags;
} tSection;
tSection* Sections = NULL;
uint SectionCnt = 0;
#define STACK_SIZE 0x10000
#define HEAP_SIZE 0x80000
C_ASSERT(STACK_SIZE >= 256 && STACK_SIZE < 0xFFFFFFFF && STACK_SIZE % 4 == 0); // less than 4GB, multiple of 4
C_ASSERT(HEAP_SIZE >= 256 && HEAP_SIZE < 0xFFFFFFFF && HEAP_SIZE % 4 == 0); // less than 4GB, multiple of 4
C_ASSERT(HEAP_SIZE < 0xFFFFFFFF - STACK_SIZE); // HEAP_SIZE + STACK_SIZE < 4GB
uint32 HeapStartAddr;
uint32 HeapSbrkAddr;
#define REG_T8 24
#define REG_SP 29
#define REG_RA 31
#define REG_LO 32
#define REG_HI 33
#define REG_PC 34
uint32 Regs[32 + 3];
int IsaMode; // 0=MIPS32, 1=MIPS16e
uint32 minAddr = 0xFFFFFFFF;
uint32 maxAddr = 0;
int isElf(void)
{
Elf32Hdr elfHdr;
int is = fread(&elfHdr, 1, sizeof elfHdr, ElfFile) == sizeof elfHdr &&
memcmp(elfHdr.e_ident, "\x7F""ELF", 4) == 0;
if (fseek(ElfFile, 0, SEEK_SET))
error("Can't read file\n");
return is;
}
void loadElf(void)
{
Elf32Hdr elfHdr;
Elf32SectHdr sectHdr;
uint idx;
int unsupported = 0;
if (fread(&elfHdr, 1, sizeof elfHdr, ElfFile) != sizeof elfHdr)
error("Can't read file\n");
if (memcmp(elfHdr.e_ident, "\x7F""ELF", 4))
error("Not an ELF file\n");
if (elfHdr.e_ident[6] != 1)
error("Not a v1 ELF file\n");
if (elfHdr.e_ehsize != sizeof elfHdr)
error("Unexpected ELF header size\n");
if (elfHdr.e_shentsize != sizeof sectHdr)
error("Unexpected ELF section size\n");
if (elfHdr.e_ident[4] != 1)
error("Not a 32-bit file\n");
if (elfHdr.e_ident[5] != 1)
error("Not a little-endian file\n");
if (elfHdr.e_type != 2)
error("Not an executable file\n");
if (elfHdr.e_machine != 8)
error("Not a MIPS executable\n");
if (fseek(ElfFile, elfHdr.e_shoff + elfHdr.e_shstrndx * sizeof sectHdr, SEEK_SET))
error("Can't read file\n");
if (fread(§Hdr, 1, sizeof sectHdr, ElfFile) != sizeof sectHdr)
error("Can't read file\n");
if ((SectNames = malloc(sectHdr.sh_size)) == NULL)
error("Out of memory\n");
if (fseek(ElfFile, sectHdr.sh_offset, SEEK_SET))
error("Can't read file\n");
if (fread(SectNames, 1, sectHdr.sh_size, ElfFile) != sectHdr.sh_size)
error("Can't read file\n");
if ((Sections = malloc((elfHdr.e_shnum + 1) * sizeof(tSection))) == NULL)
error("Out of memory\n");
printf(" # # Type XAW VirtAddr FileOffs Size Name\n");
for (idx = 0; idx < elfHdr.e_shnum; idx++)
{
const char* typeName = "????????";
const char* const typeNames[] =
{
"NULL",
"PROGBITS",
"SYMTAB",
"STRTAB",
"RELA",
"HASH",
"DYNAMIC",
"NOTE",
"NOBITS",
"REL",
"SHLIB",
"DYNSYM",
};
const char* name = "";
if (fseek(ElfFile, elfHdr.e_shoff + idx * sizeof sectHdr, SEEK_SET))
error("Can't read file\n");
if (fread(§Hdr, 1, sizeof sectHdr, ElfFile) != sizeof sectHdr)
error("Can't read file\n");
if (sectHdr.sh_type == 0)
memset(§Hdr, 0, sizeof sectHdr);
if (sectHdr.sh_name)
name = SectNames + sectHdr.sh_name;
unsupported |=
(!strcmp(name, ".dynsym") ||
!strcmp(name, ".dynstr") ||
!strcmp(name, ".dynamic") ||
!strcmp(name, ".hash") ||
!strcmp(name, ".got") ||
!strcmp(name, ".plt") ||
sectHdr.sh_type == 5 || // SHT_HASH
sectHdr.sh_type == 6 || // SHT_DYNAMIC
sectHdr.sh_type == 11); // SHT_DYNSYM
if (sectHdr.sh_type < sizeof typeNames / sizeof typeNames[0])
typeName = typeNames[sectHdr.sh_type];
printf(" # %2u %-8s %c%c%c 0x%08lX 0x%08lX %10lu %s\n",
idx,
typeName,
"-X"[(sectHdr.sh_flags / 4) & 1],
"-A"[(sectHdr.sh_flags / 2) & 1],
"-W"[(sectHdr.sh_flags / 1) & 1],
(ulong)sectHdr.sh_addr,
(ulong)sectHdr.sh_offset,
(ulong)sectHdr.sh_size,
name);
if ((sectHdr.sh_flags & 2) && sectHdr.sh_size) // SHF_ALLOC and size > 0
{
if ((Sections[SectionCnt].Data = malloc(sectHdr.sh_size)) == NULL)
error("Out of memory\n");
Sections[SectionCnt].Addr = sectHdr.sh_addr;
Sections[SectionCnt].Size = sectHdr.sh_size;
Sections[SectionCnt].Flags = (sectHdr.sh_flags & 1) | ((sectHdr.sh_flags & 4) >> 1); // bit0=Writable,bit1=eXecutable
if (sectHdr.sh_type == 1) // SHT_PROGBITS
{
if (fseek(ElfFile, sectHdr.sh_offset, SEEK_SET))
error("Can't read file\n");
if (fread(Sections[SectionCnt].Data, 1, Sections[SectionCnt].Size, ElfFile) != Sections[SectionCnt].Size)
error("Can't read file\n");
}
else // SHT_NOBITS, .bss, etc
{
memset(Sections[SectionCnt].Data, 0, Sections[SectionCnt].Size);
}
SectionCnt++;
if (minAddr > sectHdr.sh_addr)
minAddr = sectHdr.sh_addr;
if (maxAddr < sectHdr.sh_addr + sectHdr.sh_size - 1)
maxAddr = sectHdr.sh_addr + sectHdr.sh_size - 1;
}
}
EntryPointAddr = elfHdr.e_entry;
printf(" # Entry Point: 0x%08lX\n", (ulong)EntryPointAddr);
puts("");
if (unsupported)
error("Dynamically linked or unsupported type of executable\n");
}
void loadAout(void)
{
AoutHdr aoutHdr;
if (fread(&aoutHdr, 1, sizeof aoutHdr, ElfFile) != sizeof aoutHdr)
error("Can't read file\n");
if (aoutHdr.a_magic != OMAGIC)
error("Not an a.out file\n");
if ((Sections = malloc((1 + 1) * sizeof(tSection))) == NULL)
error("Out of memory\n");
#define USER_DATA_START 0x7F008000
#define MAXMEM (96*1024)
#define USER_DATA_END (USER_DATA_START + MAXMEM)
Sections[SectionCnt].Addr = USER_DATA_START;
Sections[SectionCnt].Size = aoutHdr.a_text + aoutHdr.a_data + aoutHdr.a_bss;
Sections[SectionCnt].Flags = 3; // bit0=Writable,bit1=eXecutable
printf(" # # XAW VirtAddr FileOffs Size Name\n");
printf(" # 0 XAW 0x%08lX 0x%08lX %10lu .text + .data + .bss\n",
(ulong)Sections[SectionCnt].Addr,
(ulong)sizeof(AoutHdr),
(ulong)Sections[SectionCnt].Size);
if (Sections[SectionCnt].Size > MAXMEM)
error("Section(s) bigger than %lu bytes\n", (ulong)MAXMEM);
// Allow the entire address space in case library's (s)brk()
// uses the space between _end and MAXMEM.
Sections[SectionCnt].Size = MAXMEM;
if ((Sections[SectionCnt].Data = calloc(1, Sections[SectionCnt].Size)) == NULL)
error("Out of memory\n");
if (fread(Sections[SectionCnt].Data, 1, aoutHdr.a_text + aoutHdr.a_data, ElfFile) != aoutHdr.a_text + aoutHdr.a_data)
error("Can't read file\n");
if (minAddr > Sections[SectionCnt].Addr)
minAddr = Sections[SectionCnt].Addr;
if (maxAddr < Sections[SectionCnt].Addr + Sections[SectionCnt].Size - 1)
maxAddr = Sections[SectionCnt].Addr + Sections[SectionCnt].Size - 1;
SectionCnt++;
EntryPointAddr = aoutHdr.a_entry;
printf(" # Entry: 0x%08lX\n", (ulong)EntryPointAddr);
puts("");
}
void Prepare(int argc, char** argv)
{
uint idx;
uint32 heapAndStackSize = HEAP_SIZE + STACK_SIZE;
uint32 cmdLineLen = 0;
// Pseudo-section for the heap, stack and command line parameters
// compute the size of argv[] and its strings
for (idx = 0; idx < (uint)argc; idx++)
cmdLineLen += strlen(argv[idx]) + 1;
heapAndStackSize += (cmdLineLen + 3) / 4 * 4; // argc ASCIIZ strings from argv[] (round up to whole 32-bit words)
heapAndStackSize += argc * 4; // argc pointers
// TBD!!! Ideally, there should be argc+1 pointers (the last pointer being NULL)
// allocate stack buffer
if ((Sections[SectionCnt].Data = calloc(1, heapAndStackSize)) == NULL)
error("Out of memory\n");
// find a place for the heap and the stack in the address space
if (maxAddr <= 0xFFFFFFFF - heapAndStackSize &&
maxAddr + heapAndStackSize <= 0xFFFFFFF0)
Sections[SectionCnt].Addr = -heapAndStackSize - 16; // top of address space
else if (heapAndStackSize <= 0xFFFFFFFF - 65536 &&
minAddr >= 65536 + heapAndStackSize)
Sections[SectionCnt].Addr = 65536; // bottom of address space (64K reserved to catch NULL pointer dereferences)
else
error("Can't allocate heap and stack\n");
Sections[SectionCnt].Size = heapAndStackSize;
Sections[SectionCnt].Flags = 1; // Writable
// set up argv[]
cmdLineLen = 0;
for (idx = 0; idx < (uint)argc; idx++)
{
uint32* ArgV = (uint32*)((char*)Sections[SectionCnt].Data + STACK_SIZE) + idx;
char* param = (char*)Sections[SectionCnt].Data + STACK_SIZE + 4 * argc + cmdLineLen;
strcpy(param, argv[idx]);
cmdLineLen += strlen(argv[idx]) + 1;
*ArgV = (param - (char*)Sections[SectionCnt].Data) + Sections[SectionCnt].Addr;
}
HeapSbrkAddr = HeapStartAddr =
Sections[SectionCnt].Addr + STACK_SIZE + 4 * argc + (cmdLineLen + 3) / 4 * 4;
Regs[REG_PC] = EntryPointAddr;
Regs[REG_SP] = Sections[SectionCnt++].Addr + STACK_SIZE;
Regs[4] = argc; // argc
Regs[5] = Regs[REG_SP]; // argv
Regs[6] = 0; // env
Regs[REG_SP] -= 16; // just in case the entry point is a C function, reserve 16 bytes of stack for its 4 params
StartSp = MinSp = Regs[REG_SP];
}
void DumpState(void);
void Emulate(void);
int main(int argc, char** argv)
{
uint32 ui32 = 0x44434241;
uint16 ui16 = 0x3231;
if (memcmp(&ui32, "ABCD", sizeof ui32) || memcmp(&ui16, "12", sizeof ui16))
error("EmuMipsElf runs on little-endian platforms only\n");
if (argc < 2 || !(ElfFile = fopen(argv[1], "rb")))
error("Usage:\n EmuMipsElf <mips32 elf executable or RetroBSD mips32 a.out executable> [params]\n");
if (isElf())
loadElf();
else
loadAout();
Prepare(argc - 1, argv + 1);
Emulate();
fclose(ElfFile);
return 0;
}
const char* AccessToStr(uint32 access, int allowed)
{
switch (access + 4 * !!allowed)
{
case 0: return "R";
case 1: return "W";
case 2: return "X";
case 4: return "R";
case 5: return "RW";
case 6: return "RX";
case 7: return "RWX";
}
return "?";
}
void* TryTranslateAddr(uint32 Addr, uint32 Size, uint32 Access)
{
uint i;
void* p = NULL;
for (i = 0; i < SectionCnt; i++)
if (Sections[i].Addr <= Addr &&
Addr <= (uint32)0 - Size &&
Addr + Size - 1 <= Sections[i].Addr + Sections[i].Size - 1)
{
p = (char*)Sections[i].Data + Addr - Sections[i].Addr;
break;
}
if (Size > 1 && (Addr & (Size - 1)))
p = NULL;
if (Access && !(Sections[i].Flags & Access)) // if write or execute but read-only or non-executable
p = NULL;
return p;
}
void* TranslateAddr(uint32 Addr, uint32 Size, uint32 Access)
{
uint i;
void* p = NULL;
for (i = 0; i < SectionCnt; i++)
if (Sections[i].Addr <= Addr &&
Addr <= (uint32)0 - Size &&
Addr + Size - 1 <= Sections[i].Addr + Sections[i].Size - 1)
{
p = (char*)Sections[i].Data + Addr - Sections[i].Addr;
break;
}
if (!p)
{
DumpState();
error("Access violation at PC = 0x%08lX: Unmapped address (addr=0x%08lX,size=%lu,access=%s)\n",
(ulong)Regs[REG_PC], (ulong)Addr, (ulong)Size, AccessToStr(Access, 0));
}
if (Size > 1 && (Addr & (Size - 1)))
{
DumpState();
error("Access violation at PC = 0x%08lX: Misaligned address (addr=0x%08lX,size=%lu,access=%s,allowed access=%s)\n",
(ulong)Regs[REG_PC], (ulong)Addr, (ulong)Size, AccessToStr(Access, 0), AccessToStr(Sections[i].Flags, 1));
}
if (Access && !(Sections[i].Flags & Access)) // if write or execute but read-only or non-executable
{
DumpState();
error("Access violation at PC = 0x%08lX: Disallowed access (addr=0x%08lX,size=%lu,access=%s,allowed access=%s)\n",
(ulong)Regs[REG_PC], (ulong)Addr, (ulong)Size, AccessToStr(Access, 0), AccessToStr(Sections[i].Flags, 1));
}
return p;
}
uint8 ReadByte(uint32 Addr)
{
return *(uint8*)TranslateAddr(Addr, 1, 0);
}
void WriteByte(uint32 Addr, uint8 Val)
{
*(uint8*)TranslateAddr(Addr, 1, 1) = Val;
}
uint16 ReadHalfWord(uint32 Addr)
{
return *(uint16*)TranslateAddr(Addr, 2, 0);
}
void WriteHalfWord(uint32 Addr, uint16 Val)
{
*(uint16*)TranslateAddr(Addr, 2, 1) = Val;
}
uint32 ReadWord(uint32 Addr)
{
return *(uint32*)TranslateAddr(Addr, 4, 0);
}
void WriteWord(uint32 Addr, uint32 Val)
{
*(uint32*)TranslateAddr(Addr, 4, 1) = Val;
}
uint32 FetchProgramHalfWord(uint32 Addr)
{
return *(uint16*)TranslateAddr(Addr, 2, 2);
}
uint32 FetchProgramWord(uint32 Addr)
{
return *(uint32*)TranslateAddr(Addr, 4, 2);
}
/*
Supported MIPS32 instructions:
add, addi, addiu, addu, and, andi,
bal, beq, beql, bgez, bgezal, bgezall,
bgezl, bgtz, bgtzl, blez, blezl, bltz,
bltzal, bltzall, bltzl, bne, bnel, break,
clo, clz,
div, divu,
ext,
ins,
j, jal, jalr, jalx, jr,
lb, lbu, lh, lhu, lui, lw, lwl, lwr,
madd, maddu, mfhi, mflo, movn, movz, msub,
msubu, mthi, mtlo, mul, mult, multu,
nop, nor,
or, ori,
rotr, rotrv,
sb, seb, seh, sh, sll, sllv, slt, slti, sltiu,
sltu, sra, srav, srl, srlv, sub, subu, sw,
swl, swlr, synci, syscall,
teq, teqi, tge, tgei, tgeiu, tgeu, tlt, tlti,
tltiu, tltu, tne, tnei,
wsbh,
xor, xori
Supported MIPS16e instructions:
all except sdbbp
Unsupported instructions:
bc2f, bc2fl, bc2t, bc2tl,
cache, cfc2, cop0, cop2, ctc2,
deret, di,
ehb, ei, eret,
jalr.hb, jr.hb,
ll, lwc2,
mfc0, mfc2, mtc0, mtc2, mthc2,
pref,
rdhwr, rdpgpr,
sc, sdbbp, ssnop, swc2, sync,
wait, wrpgpr
*/
uint32 DoSysCall(uint32 instr);
void DoBreak(uint32 code);
void DoTrap(uint32 code);
void DoOverflow(void);
void DoInvalidInstruction(uint32 instr);
uint CountLeadingZeroes(uint32 n)
{
uint c = 0;
if (n == 0)
return 32;
while (n < 0x80000000)
n <<= 1, c++;
return c;
}
uint CountLeadingOnes(uint32 n)
{
uint c = 0;
while (n >= 0x80000000)
n <<= 1, c++;
return c;
}
uint32 ShiftRightArithm(uint32 n, uint32 c)
{
uint32 s = -(n >> 31);
n >>= c;
n |= s << (31 - c) << 1;
return n;
}
uint32 RotateRight(uint32 n, uint32 c)
{
return (n >> c) | (n << (31 - c) << 1);
}
// Define this macro to do a more rigorous check
// for invalid/unsupported instructions
// (at the expense of performance, of course).
#define CHECK_INVALID_INSTR
void Emulate32(void)
{
int delaySlot = 0;
int cont16 = 0;
uint32 postDelaySlotPc = 0;
uint32 instr = 0;
IsaMode = 0;
for (;;)
{
const uint32 pc = Regs[REG_PC];
uint32 nextPc = pc + 4;
/*const uint32*/ instr = FetchProgramWord(pc);
#if 0
const uint32 op = instr >> 26;
const uint32 r1 = (instr >> 21) & 0x1F;
const uint32 r2 = (instr >> 16) & 0x1F;
const uint32 r3 = (instr >> 11) & 0x1F;
const uint32 shft = (instr >> 6) & 0x1F;
const uint32 fxn = instr & 0x3F;
const uint32 imm16 = instr & 0xFFFF;
const uint32 simm16 = (int16)imm16;
const uint32 jtgt = instr & 0x3FFFFFF;
#else
#define op (instr >> 26)
#define r1 ((instr >> 21) & 0x1F)
#define r2 ((instr >> 16) & 0x1F)
#define r3 ((instr >> 11) & 0x1F)
#define shft ((instr >> 6) & 0x1F)
#define fxn (instr & 0x3F)
#define imm16 (instr & 0xFFFF)
#define simm16 ((int16)imm16)
#define jtgt (instr & 0x3FFFFFF)
#endif
switch (op)
{
case 0:
switch (fxn)
{
case 0:
#ifdef CHECK_INVALID_INSTR
if (r1)
goto lInvalidInstruction;
#endif
Regs[r3] = Regs[r2] << shft;
break; // sll d,w,shft
case 2:
switch (r1)
{
case 0: Regs[r3] = Regs[r2] >> shft; break; // srl d,w,shft
case 1: Regs[r3] = RotateRight(Regs[r2], shft); break; // rotr d,w,shft
default: goto lInvalidInstruction;
}
break;
case 3:
#ifdef CHECK_INVALID_INSTR
if (r1)
goto lInvalidInstruction;
#endif
Regs[r3] = ShiftRightArithm(Regs[r2], shft);
break; // sra d,w,shft
case 4:
#ifdef CHECK_INVALID_INSTR
if (shft)
goto lInvalidInstruction;
#endif
Regs[r3] = Regs[r2] << (Regs[r1] & 31);
break; // sllv d,w,s
case 6:
switch (shft)
{
case 0: Regs[r3] = Regs[r2] >> (Regs[r1] & 31); break; // srlv d,w,s
case 1: Regs[r3] = RotateRight(Regs[r2], Regs[r1] & 31); break; // rotrv d,w,s
default: goto lInvalidInstruction;
}
break;
case 7:
#ifdef CHECK_INVALID_INSTR
if (shft)
goto lInvalidInstruction;
#endif
Regs[r3] = ShiftRightArithm(Regs[r2], Regs[r1] & 31);
break; // srav d,w,s
case 8:
#ifdef CHECK_INVALID_INSTR
if (r2 | r3 | shft)
goto lInvalidInstruction;
#endif
nextPc = Regs[r1];
cont16 = nextPc & 1; // may switch to MIPS16e
nextPc &= 0xFFFFFFFE;
delaySlot = 1;
break; // jr s
case 9:
#ifdef CHECK_INVALID_INSTR
if (r2 | shft)
goto lInvalidInstruction;
#endif
Regs[r3] = nextPc + 4;
nextPc = Regs[r1];
cont16 = nextPc & 1; // may switch to MIPS16e
nextPc &= 0xFFFFFFFE;
delaySlot = 1;
break; // jalr [d,] s
case 10:
#ifdef CHECK_INVALID_INSTR
if (shft)
goto lInvalidInstruction;
#endif
if (Regs[r2] == 0) Regs[r3] = Regs[r1];
break; // movz d,s,t
case 11:
#ifdef CHECK_INVALID_INSTR
if (shft)
goto lInvalidInstruction;
#endif
if (Regs[r2]) Regs[r3] = Regs[r1];
break; // movn d,s,t
case 12:
{
// RetroBSD may advance PC on returning from a syscall handler,
// skipping 2 instructions that follow the syscall instruction.
// Those 2 instructions typically set C's errno variable and
// are either executed on error or skipped on success.
// Account for this peculiarity.
uint32 skip = DoSysCall(instr);
nextPc += skip * 4;
}
break; // syscall code
case 13: goto lBreak; break; // break code
case 16:
#ifdef CHECK_INVALID_INSTR
if (r1 | r2 | shft)
goto lInvalidInstruction;
#endif
Regs[r3] = Regs[REG_HI];
break; // mfhi d
case 17:
#ifdef CHECK_INVALID_INSTR
if (r2 | r3 | shft)
goto lInvalidInstruction;
#endif
Regs[REG_HI] = Regs[r1];
break; // mthi s
case 18:
#ifdef CHECK_INVALID_INSTR
if (r1 | r2 | shft)
goto lInvalidInstruction;
#endif
Regs[r3] = Regs[REG_LO];
break; // mflo d
case 19:
#ifdef CHECK_INVALID_INSTR
if (r2 | r3 | shft)
goto lInvalidInstruction;
#endif
Regs[REG_LO] = Regs[r1];
break; // mtlo s
case 24:
#ifdef CHECK_INVALID_INSTR
if (r3 | shft)
goto lInvalidInstruction;
#endif
{
int64 p = (int64)(int32)Regs[r1] * (int32)Regs[r2];
Regs[REG_LO] = (uint32)p;
Regs[REG_HI] = (uint32)(p >> 32);
}
break; // mult s,t
case 25:
#ifdef CHECK_INVALID_INSTR
if (r3 | shft)
goto lInvalidInstruction;
#endif
{
uint64 p = (uint64)Regs[r1] * Regs[r2];
Regs[REG_LO] = (uint32)p;
Regs[REG_HI] = (uint32)(p >> 32);
}
break; // multu s,t
case 26:
#ifdef CHECK_INVALID_INSTR
if (r3 | shft)
goto lInvalidInstruction;
#endif
if (!(Regs[r2] == 0 || (Regs[r1] == 0x80000000 && Regs[r2] == 0xFFFFFFFF)))
Regs[REG_LO] = (int32)Regs[r1] / (int32)Regs[r2], Regs[REG_HI] = (int32)Regs[r1] % (int32)Regs[r2];
break; // div s,t
case 27:
#ifdef CHECK_INVALID_INSTR
if (r3 | shft)
goto lInvalidInstruction;
#endif
if (Regs[r2])
Regs[REG_LO] = Regs[r1] / Regs[r2], Regs[REG_HI] = Regs[r1] % Regs[r2];
break; // divu s,t
case 32:
#ifdef CHECK_INVALID_INSTR
if (shft)
goto lInvalidInstruction;
#endif
{
uint32 sum = Regs[r1] + Regs[r2];
if (((Regs[r1] ^ Regs[r2] ^ 0x80000000) & 0x80000000) &&
((sum ^ Regs[r1]) & 0x80000000))
goto lOverflow;
Regs[r3] = sum;
}
break; // add d,s,t
case 33:
#ifdef CHECK_INVALID_INSTR
if (shft)
goto lInvalidInstruction;
#endif
Regs[r3] = Regs[r1] + Regs[r2];
break; // addu d,s,t
case 34:
#ifdef CHECK_INVALID_INSTR
if (shft)
goto lInvalidInstruction;
#endif
{
uint32 diff = Regs[r1] - Regs[r2];
if (((Regs[r1] ^ Regs[r2]) & 0x80000000) &&
((diff ^ Regs[r1]) & 0x80000000))
goto lOverflow;
Regs[r3] = diff;
}
break; // sub d,s,t
case 35:
#ifdef CHECK_INVALID_INSTR
if (shft)
goto lInvalidInstruction;
#endif
Regs[r3] = Regs[r1] - Regs[r2];
break; // subu d,s,t
case 36:
#ifdef CHECK_INVALID_INSTR
if (shft)
goto lInvalidInstruction;
#endif
Regs[r3] = Regs[r1] & Regs[r2];
break; // and d,s,t
case 37:
#ifdef CHECK_INVALID_INSTR
if (shft)
goto lInvalidInstruction;
#endif
Regs[r3] = Regs[r1] | Regs[r2];
break; // or d,s,t
case 38:
#ifdef CHECK_INVALID_INSTR
if (shft)
goto lInvalidInstruction;
#endif
Regs[r3] = Regs[r1] ^ Regs[r2];
break; // xor d,s,t
case 39:
#ifdef CHECK_INVALID_INSTR
if (shft)
goto lInvalidInstruction;
#endif
Regs[r3] = ~(Regs[r1] | Regs[r2]);
break; // nor d,s,t
case 42:
#ifdef CHECK_INVALID_INSTR
if (shft)
goto lInvalidInstruction;
#endif
Regs[r3] = (int32)Regs[r1] < (int32)Regs[r2];
break; // slt d,s,t
case 43:
#ifdef CHECK_INVALID_INSTR
if (shft)
goto lInvalidInstruction;
#endif
Regs[r3] = Regs[r1] < Regs[r2];
break; // sltu d,s,t
case 48: if ((int32)Regs[r1] >= (int32)Regs[r2]) goto lTrap; break; // tge s,t
case 49: if (Regs[r1] >= Regs[r2]) goto lTrap; break; // tgeu s,t
case 50: if ((int32)Regs[r1] < (int32)Regs[r2]) goto lTrap; break; // tlt s,t
case 51: if (Regs[r1] < Regs[r2]) goto lTrap; break; // tltu s,t
case 52: if (Regs[r1] == Regs[r2]) goto lTrap; break; // teq s,t
case 53: if (Regs[r1] != Regs[r2]) goto lTrap; break; // tne s,t
default: goto lInvalidInstruction;
}
break;
case 1:
switch (r2)
{
case 0: if ((int32)Regs[r1] < 0) nextPc += simm16 << 2, delaySlot = 1; break; // bltz s,p
case 1: if ((int32)Regs[r1] >= 0) nextPc += simm16 << 2, delaySlot = 1; break; // bgez s,p
case 2: if ((int32)Regs[r1] < 0) nextPc += simm16 << 2, delaySlot = 1; else nextPc += 4; break; // bltzl s,p
case 3: if ((int32)Regs[r1] >= 0) nextPc += simm16 << 2, delaySlot = 1; else nextPc += 4; break; // bgezl s,p
case 8: if ((int32)Regs[r1] >= (int32)simm16) goto lTrap; break; // tgei s,j
case 9: if (Regs[r1] >= (uint32)simm16) goto lTrap; break; // tgeiu s,j
case 10: if ((int32)Regs[r1] < (int32)simm16) goto lTrap; break; // tlti s,j
case 11: if (Regs[r1] < (uint32)simm16) goto lTrap; break; // tltiu s,j
case 12: if (Regs[r1] == (uint32)simm16) goto lTrap; break; // teqi s,j
case 14: if (Regs[r1] != (uint32)simm16) goto lTrap; break; // tnei s,j
case 16: Regs[REG_RA] = nextPc + 4; if ((int32)Regs[r1] < 0) nextPc += simm16 << 2, delaySlot = 1; break; // bltzal s,p
case 17: Regs[REG_RA] = nextPc + 4; if ((int32)Regs[r1] >= 0) nextPc += simm16 << 2, delaySlot = 1; break; // bgezal s,p
case 18: Regs[REG_RA] = nextPc + 4; if ((int32)Regs[r1] < 0) nextPc += simm16 << 2, delaySlot = 1; else nextPc += 4; break; // bltzall s,p
case 19: Regs[REG_RA] = nextPc + 4; if ((int32)Regs[r1] >= 0) nextPc += simm16 << 2, delaySlot = 1; else nextPc += 4; break; // bgezall s,p
case 31: break; // synci o(b)
default: goto lInvalidInstruction;
}
break;
case 2: nextPc = (pc & 0xF0000000) | (jtgt << 2); delaySlot = 1; break; // j target
case 3: Regs[REG_RA] = nextPc + 4; nextPc = (nextPc & 0xF0000000) | (jtgt << 2); delaySlot = 1; break; // jal target
case 4: if (Regs[r1] == Regs[r2]) nextPc += simm16 << 2, delaySlot = 1; break; // beq s,t,p
case 5: if (Regs[r1] != Regs[r2]) nextPc += simm16 << 2, delaySlot = 1; break; // bne s,t,p
case 6:
#ifdef CHECK_INVALID_INSTR
if (r2)
goto lInvalidInstruction;
#endif
if ((int32)Regs[r1] <= 0) nextPc += simm16 << 2, delaySlot = 1; break; // blez s,p
case 7:
#ifdef CHECK_INVALID_INSTR
if (r2)
goto lInvalidInstruction;
#endif
if ((int32)Regs[r1] > 0) nextPc += simm16 << 2, delaySlot = 1; break; // bgtz s,p