-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFasFile.cs
958 lines (843 loc) · 39.5 KB
/
FasFile.cs
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
using System.Collections.ObjectModel;
using System.Text;
namespace FasToSym;
// Documentation of the FAS file format: https://fossies.org/linux/fasm/tools/fas.txt
public class FasFile
{
private static readonly Encoding Encoding = Encoding.GetEncoding(65001/*UTF-8*/);
private const int MayorVersion = 1;
private const int MinorVersion = 73;
private static class Utils
{
static public string CstrToString(byte[] data)
{
int inx = Array.FindIndex(data, 0, (x) => x == 0); //search for 0
if (inx >= 0)
return (Encoding.GetString(data, 0, inx));
else
return (Encoding.GetString(data));
}
}
private struct Header
{
public byte mayorVersion;
public byte minorVersion;
public uint offsetInputFileNameStringsTable;
public uint offsetOutputFileNameStringsTable;
public uint offsetStringsTable;
public int lengthStringsTable;
public uint offsetSymbolsTable;
public int lengthSymbolsTable;
public uint offsetPreprocessedSource;
public int lengthPreprocessedSource;
public uint offsetAssemblyDump;
public int lengthAssemblyDump;
public uint offsetSectionNamesTable;
public int lengthSectionNamesTable;
public uint offsetSymbolReferencesDump;
public int lengthSymbolReferencesDump;
public const int Size = 64;
}
public struct ExtendedSIB
{
public RegisterCode registerCode;
public ushort scale;
}
public class SymbolTable
{
public ulong address;
public ushort flags;
public byte dataSize;
public SymbolValueType addressType;
public ExtendedSIB extendedSIB;
public short numberOfPassDefined;
public short numberOfPassUsed;
public uint relativeSection;
public uint offsetSymbolName;
public uint offsetInPreprocessedSource;
public const int Size = 32;
}
public class PreprocessedSourceLine
{
public uint offset; //< This is the offset of each line of preprocessed source.
public string sourceFile = string.Empty;
public uint lineNumber;
public LoadedFrom loadedFrom;
public uint characterOffsetInSourceFile;
public uint macroinstructionOffset;
public string line = string.Empty;
public bool ignoredByAssembler;
}
public class AssemblyDump
{
public uint offsetOutputFile;
public uint offsetPreprocessedSourceLine;
public ulong address;
public ExtendedSIB extendedSIB;
public uint sectionOrExternalSymbol;
public byte typeOfAddressValue;
public byte typeOfCode;
public byte assemblyWasTakingPlaceVirtualBlock;
public byte higerBitsOfValueOfAddress;
public const int Size = 28;
}
public class SymbolReferencesDump
{
public uint offsetSymbol;
public uint offsetStructure;
public const int Size = 8;
}
public enum LoadedFrom
{
Source = 0,
GeneratedByMicroinstruction
}
private readonly string _inputFile = string.Empty;
private Header _header;
private readonly Collection<string> _stringTable = [];
private readonly Collection<SymbolTable> _symbols = [];
private readonly Collection<int> _sectionNames = [];
private readonly Collection<PreprocessedSourceLine> _preprocessedSourceLines = [];
private readonly Collection<AssemblyDump> _assemblyDumps = [];
private readonly Collection<SymbolReferencesDump> _referencesDump = [];
private int _offsetOfEndOfAssemblyInOutputFile = 0;
public Collection<string> Errors { get; } = [];
public string ParentDirectory { get; } = string.Empty;
public string FileNameNoExtension { get; } = string.Empty;
public Collection<string> StringTable { get => _stringTable; }
public Collection<SymbolTable> SymbolsTable { get => _symbols; }
public Collection<int> SectionNames { get => _sectionNames; }
public Collection<PreprocessedSourceLine> PreprocessedSourceLines { get => _preprocessedSourceLines; }
public Collection<AssemblyDump> AssemblyDumps { get => _assemblyDumps; }
public Collection<SymbolReferencesDump> SymbolReferencesDumps { get => _referencesDump; }
public int OffsetOfEndOfAssemblyInOutputFile { get => _offsetOfEndOfAssemblyInOutputFile; }
public string InputFileName { get; private set; } = string.Empty;
public string OutputFileName { get; private set; } = string.Empty;
public FasFile(string fasFilePath)
{
if (string.IsNullOrEmpty(fasFilePath) ||
!File.Exists(fasFilePath))
{
Errors.Add("Error: Input file is missing");
return;
}
_inputFile = fasFilePath;
string fileName = Path.GetFileNameWithoutExtension(fasFilePath);
string? parentDirectory = Path.GetDirectoryName(fasFilePath);
if (string.IsNullOrEmpty(parentDirectory))
{
Errors.Add("Error: Problem getting the parent directory from the input file.");
return;
}
ParentDirectory = parentDirectory;
FileNameNoExtension = fileName;
ProcessFile();
}
public bool IsValid()
{
return Errors.Count == 0;
}
private void ProcessFile()
{
using FileStream fs = new(_inputFile, FileMode.Open, FileAccess.Read);
using BinaryReader br = new(fs);
br.BaseStream.Position = 0;
if (!ReadHeader(br))
return;
if (!ReadStringTable(br))
return;
if (!ReadSymbolsTable(br))
return;
if (!ReadPreprocessedSource(br))
return;
if (!ReadAssemblyDump(br))
return;
if (!ReadSectionNamesTable(br))
return;
if (!ReadSymbolReferenceDump(br))
return;
if (br.BaseStream.Position != br.BaseStream.Length)
{
Errors.Add("Error: The end of the file does not match the current read poisition.");
}
}
// Table 1 Header
// /-------------------------------------------------------------------------\
// | Offset | Size | Description |
// |========|=========|======================================================|
// | +0 | dword | Signature 1A736166h (little-endian). |
// |--------|---------|------------------------------------------------------|
// | +4 | byte | Major version of flat assembler. |
// |--------|---------|------------------------------------------------------|
// | +5 | byte | Minor version of flat assembler. |
// |--------|---------|------------------------------------------------------|
// | +6 | word | Length of header. |
// |--------|---------|------------------------------------------------------|
// | +8 | dword | Offset of input file name in the strings table. |
// |--------|---------|------------------------------------------------------|
// | +12 | dword | Offset of output file name in the strings table. |
// |--------|---------|------------------------------------------------------|
// | +16 | dword | Offset of strings table. |
// |--------|---------|------------------------------------------------------|
// | +20 | dword | Length of strings table. |
// |--------|---------|------------------------------------------------------|
// | +24 | dword | Offset of symbols table. |
// |--------|---------|------------------------------------------------------|
// | +28 | dword | Length of symbols table. |
// |--------|---------|------------------------------------------------------|
// | +32 | dword | Offset of preprocessed source. |
// |--------|---------|------------------------------------------------------|
// | +36 | dword | Length of preprocessed source. |
// |--------|---------|------------------------------------------------------|
// | +40 | dword | Offset of assembly dump. |
// |--------|---------|------------------------------------------------------|
// | +44 | dword | Length of assembly dump. |
// |--------|---------|------------------------------------------------------|
// | +48 | dword | Offset of section names table. |
// |--------|---------|------------------------------------------------------|
// | +52 | dword | Length of section names table. |
// |--------|---------|------------------------------------------------------|
// | +56 | dword | Offset of symbol references dump. |
// |--------|---------|------------------------------------------------------|
// | +60 | dword | Length of symbol references dump. |
// \-------------------------------------------------------------------------/
private bool ReadHeader(BinaryReader br)
{
// Verify signature
byte[] chunk = br.ReadBytes(4);
if (chunk.Length < 4)
{
Errors.Add("Error: File is empty.");
return false;
}
if (chunk[0] != 'f' ||
chunk[1] != 'a' ||
chunk[2] != 's' ||
chunk[3] != 0x1a)
{
Errors.Add("Error: Error in the header.");
return false;
}
_header.mayorVersion = br.ReadByte();
_header.minorVersion = br.ReadByte();
if (_header.mayorVersion != MayorVersion ||
_header.minorVersion != MinorVersion)
{
Errors.Add("Error: Unexpected FAS version. " +
$"The version from the input file is {_header.mayorVersion}.{_header.minorVersion} " +
$"and the expected version is {MayorVersion}.{MinorVersion}");
return false;
}
int lenghtOfHeader = br.ReadInt16();
if (lenghtOfHeader != Header.Size)
{
Errors.Add("Error: Error in the header.");
return false;
}
_header.offsetInputFileNameStringsTable = br.ReadUInt32();
_header.offsetOutputFileNameStringsTable = br.ReadUInt32();
_header.offsetStringsTable = br.ReadUInt32();
_header.lengthStringsTable = br.ReadInt32();
_header.offsetSymbolsTable = br.ReadUInt32();
_header.lengthSymbolsTable = br.ReadInt32();
_header.offsetPreprocessedSource = br.ReadUInt32();
_header.lengthPreprocessedSource = br.ReadInt32();
_header.offsetAssemblyDump = br.ReadUInt32();
_header.lengthAssemblyDump = br.ReadInt32();
_header.offsetSectionNamesTable = br.ReadUInt32();
_header.lengthSectionNamesTable = br.ReadInt32();
_header.offsetSymbolReferencesDump = br.ReadUInt32();
_header.lengthSymbolReferencesDump = br.ReadInt32();
return true;
}
// The strings table contains just a sequence of ASCIIZ strings, which may
// be referred to by other parts of the file. It contains the names of
// main input file, the output file, and the names of the sections and
// external symbols if there were any.
private bool ReadStringTable(BinaryReader br)
{
if (_header.offsetStringsTable != br.BaseStream.Position)
{
Errors.Add("Error: String table is read at the wrong position");
return false;
}
byte[] strTableArray = br.ReadBytes(_header.lengthStringsTable);
if (strTableArray.Length < 1)
{
Errors.Add("Error: Error while processing string table.");
return false;
}
int offset = 0;
int index = 0;
while (offset < strTableArray.Length)
{
byte[] tmp = new byte[strTableArray.Length - offset];
Array.Copy(strTableArray, offset, tmp, 0, tmp.Length);
string str = Utils.CstrToString(tmp);
_stringTable.Add(str);
if (offset == _header.offsetInputFileNameStringsTable)
InputFileName = str;
else if (offset == _header.offsetOutputFileNameStringsTable)
OutputFileName = str;
index++;
if (!string.IsNullOrEmpty(str))
{
offset += str.Length + 1 /* plus null terminator */;
}
}
return true;
}
// Table 2 Symbol structure
// /-------------------------------------------------------------------------\
// | Offset | Size | Description |
// |========|=======|========================================================|
// | +0 | qword | Value of symbol. |
// |--------|-------|--------------------------------------------------------|
// | +8 | word | Flags (table 2.1). |
// |--------|-------|--------------------------------------------------------|
// | +10 | byte | Size of data labelled by this symbol (zero means plain |
// | | | label without size attached). |
// |--------|-------|--------------------------------------------------------|
// | +11 | byte | Type of value (table 2.2). Any value other than zero |
// | | | means some kind of relocatable symbol. |
// |--------|-------|--------------------------------------------------------|
// | +12 | dword | Extended SIB, the first two bytes are register codes |
// | | | and the second two bytes are corresponding scales. |
// |--------|-------|--------------------------------------------------------|
// | +16 | word | Number of pass in which symbol was defined last time. |
// |--------|-------|--------------------------------------------------------|
// | +18 | word | Number of pass in which symbol was used last time. |
// |--------|-------|--------------------------------------------------------|
// | +20 | dword | If the symbol is relocatable, this field contains |
// | | | information about section or external symbol, to which |
// | | | it is relative - otherwise this field has no meaning. |
// | | | When the highest bit is cleared, the symbol is |
// | | | relative to a section, and the bits 0-30 contain |
// | | | the index (starting from 1) in the table of sections. |
// | | | When the highest bit is set, the symbol is relative to |
// | | | an external symbol, and the bits 0-30 contain the |
// | | | the offset of the name of this symbol in the strings |
// | | | table. |
// |--------|-------|--------------------------------------------------------|
// | +24 | dword | If the highest bit is cleared, the bits 0-30 contain |
// | | | the offset of symbol name in the preprocessed source. |
// | | | This name is a pascal-style string (byte length |
// | | | followed by string data). |
// | | | Zero in this field means an anonymous symbol. |
// | | | If the highest bit is set, the bits 0-30 contain the |
// | | | offset of the symbol name in the strings table, and |
// | | | this name is a zero-ended string in this case (as are |
// | | | all the strings there). |
// |--------|-------|--------------------------------------------------------|
// | +28 | dword | Offset in the preprocessed source of line that defined |
// | | | this symbol (see table 3). |
// \-------------------------------------------------------------------------/
//
// The symbols table is an array of 32-byte structures, each one in format
// specified by table 2.
private bool ReadSymbolsTable(BinaryReader br)
{
if (_header.offsetSymbolsTable != br.BaseStream.Position)
{
Errors.Add("Error: Symbols table is read at the wrong position");
return false;
}
int numSymbols = _header.lengthSymbolsTable / SymbolTable.Size;
for (int i = 0; i < numSymbols; i++)
{
SymbolTable symbolTable = new()
{
address = br.ReadUInt64(),
flags = br.ReadUInt16(),
dataSize = br.ReadByte(),
addressType = (SymbolValueType)br.ReadByte(),
extendedSIB = ReadExtendedSIB(br),
numberOfPassDefined = br.ReadInt16(),
numberOfPassUsed = br.ReadInt16(),
relativeSection = br.ReadUInt32(),
offsetSymbolName = br.ReadUInt32(),
offsetInPreprocessedSource = br.ReadUInt32()
};
_symbols.Add(symbolTable);
}
return true;
}
// Table 3 Preprocessed line
// /--------------------------------------------------------------------------\
// | Offset | Size | Value |
// |========|=================================================================|
// | +0 | dword | When the line was loaded from source, this field |
// | | | contains either zero (if it is the line from the main |
// | | | input file), or an offset inside the preprocessed |
// | | | source to the name of file, from which this line was |
// | | | loaded (the name of file is zero-ended string). |
// | | | When the line was generated by macroinstruction, this |
// | | | field contains offset inside the preprocessed source to |
// | | | the pascal-style string specifying the name of |
// | | | macroinstruction, which generated this line. |
// |--------|-------|---------------------------------------------------------|
// | +4 | dword | Bits 0-30 contain the number of this line. |
// | | | If the highest bit is zeroed, this line was loaded from |
// | | | source. |
// | | | If the highest bit is set, this line was generated by |
// | | | macroinstruction. |
// |--------|-------|---------------------------------------------------------|
// | +8 | dword | If the line was loaded from source, this field contains |
// | | | the position of the line inside the source file, from |
// | | | which it was loaded. |
// | | | If line was generated by macroinstruction, this field |
// | | | contains the offset of preprocessed line, which invoked |
// | | | the macroinstruction. |
// | | | If line was generated by instantaneous macro, this |
// | | | field is equal to the next one. |
// |--------|-------|---------------------------------------------------------|
// | +12 | dword | If the line was generated by macroinstruction, this |
// | | | field contains offset of the preprocessed line inside |
// | | | the definition of macro, from which this one was |
// | | | generated. |
// |--------|-------|---------------------------------------------------------|
// | +16 | ? | The tokenized contents of line. |
// \--------------------------------------------------------------------------/
//
// The preprocessed source is a sequence of preprocessed lines, each one
// in format as defined in table 3.
private bool ReadPreprocessedSource(BinaryReader br)
{
if (_header.offsetPreprocessedSource != br.BaseStream.Position)
{
Errors.Add("Error: Preprocessed source is read at the wrong position");
return false;
}
for (int i = 0; i < _header.lengthPreprocessedSource;)
{
PreprocessedSourceLine line = new()
{
offset = (uint)(br.BaseStream.Position - _header.offsetPreprocessedSource)
};
uint offsetSourceFile = br.ReadUInt32();
if (offsetSourceFile == 0)
{
line.sourceFile = InputFileName;
}
else
{
line.sourceFile = GetNameOfFile(br, offsetSourceFile);
}
uint secondInteger = br.ReadUInt32();
uint lineNumberMask = (1 << 30) - 1;
line.lineNumber = secondInteger & lineNumberMask;
uint loadedFromSourceMask = 0xC0000000;
uint loadedFromSource = (secondInteger & loadedFromSourceMask) >> 30;
line.loadedFrom = loadedFromSource == 0 ? LoadedFrom.Source : LoadedFrom.GeneratedByMicroinstruction;
line.characterOffsetInSourceFile = br.ReadUInt32();
line.macroinstructionOffset = br.ReadUInt32();
string actualLine = string.Empty;
bool ignoredByAssembler = false;
i += ProcessTokenLines(br, ref actualLine, ref ignoredByAssembler);
i += (sizeof(int) * 4);
line.line = actualLine;
line.ignoredByAssembler = ignoredByAssembler;
_preprocessedSourceLines.Add(line);
}
return true;
}
private string GetNameOfFile(BinaryReader br, uint offset)
{
const int MAX_PATH = 260;
long cachePos = br.BaseStream.Position;
long nameOfFileOffset = _header.offsetPreprocessedSource + offset;
br.BaseStream.Seek(nameOfFileOffset, SeekOrigin.Begin);
byte[] strTableArray = br.ReadBytes(MAX_PATH);
string filePath = Utils.CstrToString(strTableArray);
br.BaseStream.Seek(cachePos, SeekOrigin.Begin);
return filePath;
}
// Returns the number of bytes read
private static int ProcessTokenLines(BinaryReader br, ref string actualLine, ref bool ignoredByAssembler)
{
StringBuilder sb = new();
int bytesCounter = 0;
bool tokenUsed = false;
byte[] ReadBytes(int numberOfBytes)
{
bytesCounter += numberOfBytes;
return br.ReadBytes(numberOfBytes);
}
byte ReadByte()
{
return ReadBytes(1)[0];
}
byte token = ReadByte();
while (token != 0x00)
{
switch (token)
{
case 0x1A: // normal token, followed by size and then the characters
case 0x3B: // ignore line
{
if (token == 0x3B)
ignoredByAssembler = true;
if (tokenUsed)
{
sb.Append(' ');
}
int numberOfCharacter = ReadByte();
byte[] characters = ReadBytes(numberOfCharacter);
sb.Append(Encoding.GetString(characters));
tokenUsed = true;
}
break;
case 0x22: // quote token, followed by a double word representing number of characters
{
sb.Append(" \'");
uint numberOfCharacters = BitConverter.ToUInt32(ReadBytes(4));
byte[] characters = ReadBytes(Convert.ToInt32(numberOfCharacters));
sb.Append(Encoding.GetString(characters));
sb.Append('\'');
tokenUsed = true;
}
break;
default: // Non token character
{
string character = Encoding.GetString([token]);
sb.Append(character);
if (character == ":")
{
sb.Append(' ');
}
tokenUsed = false;
}
break;
}
token = ReadByte();
}
actualLine = sb.ToString().Trim();
return bytesCounter;
}
// Table 4 Row of the assembly dump
// /-------------------------------------------------------------------------\
// | Offset | Size | Description |
// |========|=======|========================================================|
// | +0 | dword | Offset in output file. |
// |--------|-------|--------------------------------------------------------|
// | +4 | dword | Offset of line in preprocessed source. |
// |--------|-------|--------------------------------------------------------|
// | +8 | qword | Value of $ address. |
// |--------|-------|--------------------------------------------------------|
// | +16 | dword | Extended SIB for the $ address, the first two bytes |
// | | | are register codes and the second two bytes are |
// | | | corresponding scales. |
// |--------|-------|--------------------------------------------------------|
// | +20 | dword | If the $ address is relocatable, this field contains |
// | | | information about section or external symbol, to which |
// | | | it is relative - otherwise this field is zero. |
// | | | When the highest bit is cleared, the address is |
// | | | relative to a section, and the bits 0-30 contain |
// | | | the index (starting from 1) in the table of sections. |
// | | | When the highest bit is set, the address is relative |
// | | | to an external symbol, and the bits 0-30 contain the |
// | | | the offset of the name of this symbol in the strings |
// | | | table. |
// |--------|-------|--------------------------------------------------------|
// | +24 | byte | Type of $ address value (as in table 2.2). |
// |--------|-------|--------------------------------------------------------|
// | +25 | byte | Type of code - possible values are 16, 32, and 64. |
// |--------|-------|--------------------------------------------------------|
// | +26 | byte | If the bit 0 is set, then at this point the assembly |
// | | | was taking place inside the virtual block, and the |
// | | | offset in output file has no meaning here. |
// | | | If the bit 1 is set, the line was assembled at the |
// | | | point, which was not included in the output file for |
// | | | some other reasons (like inside the reserved data at |
// | | | the end of section). |
// |--------|-------|--------------------------------------------------------|
// | +27 | byte | The higher bits of value of $ address. |
// \-------------------------------------------------------------------------/
//
// The assembly dump contains an array of 28-byte structures, each one in
// format specified by table 4, and at the end of this array an additional
// double word containing the offset in output file at which the assembly
// was ended.
private bool ReadAssemblyDump(BinaryReader br)
{
if (_header.offsetAssemblyDump != br.BaseStream.Position)
{
Errors.Add("Error: Assembly dump is read at the wrong position");
return false;
}
int length = _header.lengthAssemblyDump / AssemblyDump.Size;
for (int i = 0; i < length; i++)
{
AssemblyDump assemblyDump = new()
{
offsetOutputFile = br.ReadUInt32(),
offsetPreprocessedSourceLine = br.ReadUInt32(),
address = br.ReadUInt64(),
extendedSIB = ReadExtendedSIB(br),
sectionOrExternalSymbol = br.ReadUInt32(),
typeOfAddressValue = br.ReadByte(),
typeOfCode = br.ReadByte(),
assemblyWasTakingPlaceVirtualBlock = br.ReadByte(),
higerBitsOfValueOfAddress = br.ReadByte()
};
_assemblyDumps.Add(assemblyDump);
}
_offsetOfEndOfAssemblyInOutputFile = br.ReadInt32();
return true;
}
// The section names table exists only when the output format was an object
// file (ELF or COFF), and it is an array of 4-byte entries, each being an
// offset of the name of the section in the strings table.
// The index of section in this table is the same, as the index of section
// in the generated object file.
private bool ReadSectionNamesTable(BinaryReader br)
{
if (_header.offsetSectionNamesTable != br.BaseStream.Position)
{
Errors.Add("Error: Section names is read at the wrong position");
return false;
}
int numSections = _header.lengthSectionNamesTable / sizeof(int);
for (int i = 0; i < numSections; i++)
{
_sectionNames.Add(br.ReadInt32());
}
return true;
}
// Table 2.1 Symbol flags
// /-----------------------------------------------------------------\
// | Bit | Value | Description |
// |=====|=======|===================================================|
// | 0 | 1 | Symbol was defined. |
// |-----|-------|---------------------------------------------------|
// | 1 | 2 | Symbol is an assembly-time variable. |
// |-----|-------|---------------------------------------------------|
// | 2 | 4 | Symbol cannot be forward-referenced. |
// |-----|-------|---------------------------------------------------|
// | 3 | 8 | Symbol was used. |
// |-----|-------|---------------------------------------------------|
// | 4 | 10h | The prediction was needed when checking |
// | | | whether the symbol was used. |
// |-----|-------|---------------------------------------------------|
// | 5 | 20h | Result of last predicted check for being used. |
// |-----|-------|---------------------------------------------------|
// | 6 | 40h | The prediction was needed when checking |
// | | | whether the symbol was defined. |
// |-----|-------|---------------------------------------------------|
// | 7 | 80h | Result of last predicted check for being defined. |
// |-----|-------|---------------------------------------------------|
// | 8 | 100h | The optimization adjustment is applied to |
// | | | the value of this symbol. |
// |-----|-------|---------------------------------------------------|
// | 9 | 200h | The value of symbol is negative number encoded |
// | | | as two's complement. |
// |-----|-------|---------------------------------------------------|
// | 10 | 400h | Symbol is a special marker and has no value. |
// \-----------------------------------------------------------------/
[Flags]
public enum SymbolFlags
{
SymbolWasDefined = 0x000,
SymbolInAssemblyTimeVariable = 0x002,
SymbolCannotBeForwardReferenced = 0x004,
SymbolWasUsed = 0x008,
PredictionWasNeededWasUsed = 0x010,
ResultLastPredictedUsed = 0x020,
PredictionWasNeededWasDefined = 0x040,
ResultLastPredictionDefined = 0x080,
OptimizationAppliedToValue = 0x100,
ValueIsNegativeNumberEncoded = 0x200,
SymbolIsSpecialMarker = 0x400
}
// Table 2.2 Symbol value types
// /-------------------------------------------------------------------\
// | Value | Description |
// |=======|===========================================================|
// | 0 | Absolute value. |
// |-------|-----------------------------------------------------------|
// | 1 | Relocatable segment address (only with MZ output). |
// |-------|-----------------------------------------------------------|
// | 2 | Relocatable 32-bit address. |
// |-------|-----------------------------------------------------------|
// | 3 | Relocatable relative 32-bit address (value valid only for |
// | | symbol used in the same place where it was calculated, |
// | | it should not occur in the symbol structure). |
// |-------|-----------------------------------------------------------|
// | 4 | Relocatable 64-bit address. |
// |-------|-----------------------------------------------------------|
// | 5 | [ELF only] GOT-relative 32-bit address. |
// |-------|-----------------------------------------------------------|
// | 6 | [ELF only] 32-bit address of PLT entry. |
// |-------|-----------------------------------------------------------|
// | 7 | [ELF only] Relative 32-bit address of PLT entry (value |
// | | valid only for symbol used in the same place where it |
// | | was calculated, it should not occur in the symbol |
// | | structure). |
// \-------------------------------------------------------------------/
public enum SymbolValueType
{
AbsoluteValue = 0,
RelocatableSegmentAddress = 1,
Relocatable32bitAddress = 2,
RelocatableRelative32bitAddress = 3,
Relocatable64bitAddress = 4,
GOTRelative32bitAddress = 5,
AddressPLTEntry = 6,
AddressPLTEntryRelative = 7
}
// Table 2.3 Register codes for extended SIB
// /------------------\
// | Value | Register |
// |=======|==========|
// | 23h | BX |
// |-------|----------|
// | 25h | BP |
// |-------|----------|
// | 26h | SI |
// |-------|----------|
// | 27h | DI |
// |-------|----------|
// | 40h | EAX |
// |-------|----------|
// | 41h | ECX |
// |-------|----------|
// | 42h | EDX |
// |-------|----------|
// | 43h | EBX |
// |-------|----------|
// | 44h | ESP |
// |-------|----------|
// | 45h | EBP |
// |-------|----------|
// | 46h | ESI |
// |-------|----------|
// | 47h | EDI |
// |-------|----------|
// | 48h | R8D |
// |-------|----------|
// | 49h | R9D |
// |-------|----------|
// | 4Ah | R10D |
// |-------|----------|
// | 4Bh | R11D |
// |-------|----------|
// | 4Ch | R12D |
// |-------|----------|
// | 4Dh | R13D |
// |-------|----------|
// | 4Eh | R14D |
// |-------|----------|
// | 4Fh | R15D |
// |-------|----------|
// | 80h | RAX |
// |-------|----------|
// | 81h | RCX |
// |-------|----------|
// | 82h | RDX |
// |-------|----------|
// | 83h | RBX |
// |-------|----------|
// | 84h | RSP |
// |-------|----------|
// | 85h | RBP |
// |-------|----------|
// | 86h | RSI |
// |-------|----------|
// | 87h | RDI |
// |-------|----------|
// | 88h | R8 |
// |-------|----------|
// | 89h | R9 |
// |-------|----------|
// | 8Ah | R10 |
// |-------|----------|
// | 8Bh | R11 |
// |-------|----------|
// | 8Ch | R12 |
// |-------|----------|
// | 8Dh | R13 |
// |-------|----------|
// | 8Eh | R14 |
// |-------|----------|
// | 8Fh | R15 |
// |-------|----------|
// | 94h | EIP |
// |-------|----------|
// | 98h | RIP |
// \------------------/
public enum RegisterCode
{
None = 0x00,
BX = 0x23,
BP = 0x25,
SI = 0x26,
DI = 0x27,
EAX = 0x40,
ECX = 0x41,
EDX = 0x42,
EBX = 0x43,
ESP = 0x44,
EBP = 0x45,
ESI = 0x46,
EDI = 0x47,
R8D = 0x48,
R9D = 0x49,
R10D = 0x4A,
R11D = 0x4B,
R12D = 0x4C,
R13D = 0x4D,
R14D = 0x4E,
R15D = 0x4F,
RAX = 0x80,
RCX = 0x81,
RDX = 0x82,
RBX = 0x83,
RSP = 0x84,
RBP = 0x85,
RSI = 0x86,
RDI = 0x87,
R8 = 0x88,
R9 = 0x89,
R10 = 0x8A,
R11 = 0x8B,
R12 = 0x8C,
R13 = 0x8D,
R14 = 0x8E,
R15 = 0x8F,
EIP = 0x94,
RIP = 0x98
}
// The symbol references dump contains an array of 8-byte structures, each
// one describes an event of some symbol being used.The first double word
// of such structure contains an offset of symbol in the symbols table,
// and the second double word is an offset of structure in assembly dump,
// which specifies at what moment the symbol was referenced.
private bool ReadSymbolReferenceDump(BinaryReader br)
{
if (_header.offsetSymbolReferencesDump != br.BaseStream.Position)
{
Errors.Add("Error: Symbol references is read at the wrong position");
return false;
}
int length = _header.lengthSymbolReferencesDump / SymbolReferencesDump.Size;
for (int i = 0; i < length; i++)
{
SymbolReferencesDump referenceDump = new()
{
offsetSymbol = br.ReadUInt32(),
offsetStructure = br.ReadUInt32()
};
_referencesDump.Add(referenceDump);
}
return true;
}
private static ExtendedSIB ReadExtendedSIB(BinaryReader br)
{
ExtendedSIB extendedSIB = new()
{
registerCode = (RegisterCode)br.ReadInt16(),
scale = br.ReadUInt16()
};
return extendedSIB;
}
}