-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpqr5asm.py
2643 lines (2436 loc) · 112 KB
/
pqr5asm.py
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
#################################################################################################################################
## _______ _ __ __ _
## / ___/ / (_)__ __ _ __ _____ / /__ / / ___ ___ _(_)___ TM
## / /__/ _ \/ / _ \/ ' \/ // / _ \/ '_/ / /__/ _ \/ _ `/ / __/ //// O P E N - S O U R C E ////
## \___/_//_/_/ .__/_/_/_/\_,_/_//_/_/\_\ /____/\___/\_, /_/\__/
## /_/ /___/
#################################################################################################################################
# Script : pqr5asm RISC-V Assembler
# Developer : Mitu Raj, chip@chipmunklogic.com
# Vendor : Chipmunk Logic, https://chipmunklogic.com
#
# Description : This script interprets, parses, and translates RISC-V RV32I assembly instructions to
# 32-bit binary instructions.
# -- Compliant with RISC-V User Level ISA v2.2.
# -- Supports RV32I:
# -- 37 base instructions (ref. pqr5asm Instruction Manual for full list)
# -- Custom/Pseudo instructions (ref. pqr5asm Instruction Manual for full list)
# -- Doesn't support FENCE and CSR instructions.
# -- Input = assembly code file, Output = binary/hex code files (.txt/.bin)
# -- Supports ABI acronyms (ref. pqr5asm Instruction Manual for more details)
# -- Only one instruction per line.
# -- Supports .section .text for text (instructions) segment and .section .data for data/bss segment
# -- .section .text is mandatory.
# -- Base address of the section to be mentioned with linker directive .org <addr in hexa>
# -- .string, .ascii, .byte, .hword, .word types are supported for defining data symbols in memory
# -- BSS segment can be defined by explicitly defining variables with default value = 0
# or by defining .zero regions in the memory
# -- Base address of program (PC of first instruction) should be 4-byte aligned
# for eg: .org 0x00000004
# Binary file will be generated with this base address on the instr. memory to store instructions
# For relocatable binary code, the binary can be mapped to different base address from this
# -- Supports <space>, <comma>, and <linebreak> as delimiters for eg:
# LUI x5 255 <linebreak>
# LUI x5, 255 <linebreak>
# -- Use '#' for inline/newline comments, for eg: LUI x5 255 # This is a sample comment
# -- Supports 32-bit signed/unsigned integer, 0x hex literals for immediate.
# For eg: 255, 0xFF, -255
# -- Immediates support parenthesis format: addi x1, x0, 2 <=> addi x1, 2(x0)
# -- Immediates gets truncated to 20-bit or 12-bit based on instruction.
# -- U-type instr format: <OPCODE> <rdt> <imm> // imm = 20-bit signed offset
# -- J-type instr format: <OPCODE> <rdt> <imm> // imm = 20-bit signed offset
# -- I-type instr format: <OPCODE> <rdt> <rs1> <imm> // imm = 12-bit signed offset
# 5-bit for SLLI/SRLI/SRAI
# -- B-type instr format: <OPCODE> <rs1> <rs2> <imm> // imm = 12-bit signed offset
# -- S-type instr format: <OPCODE> <rs2> <rs1> <imm> // imm = 12-bit signed offset
# -- R-type instr format: <OPCODE> <rdt> <rs1> <rs2>
# -- Valid registers for operands rdt/rs1/rs2: x0 to x31 (or ABI acronyms)
# -- Supports labels for jump/branch/load/store instructions for addressing
# -- Label is recommended to be of max. 16 ASCII characters
# -- Label should be stand-alone in new line for eg: fibonacc:
# ADD x1, x1, x2
# -- Label is case-sensitive
# -- %hi() and %lo() can be used to extract MS 20-bit & LS 12-bit from a 32-bit symbol.
# This together can return the 32-bit absolute address of a symbol.
# This can be used to generate memory access offset for load/store operations. Or load 32-bit constant
# to a register.
# For eg:
# # myvar is a 32-bit symbol in memory, which has to be loaded to a register a4
# LUI a5, %hi(myvar)
# LW a4, %lo(myvar)(a5)
#
# # myvar2 is a 32-bit symbol in memory, which has to be stored with a 32-bit word from register a4
# LUI a5, %hi(myvar2)
# SW a4, %lo(myvar2)(a5)
#
# # Loading 32-bit constant to register
# LUI x1, %hi(0xdeadbeef) # Load the upper 20 bits into x1
# ADDI x1, x1, %lo(0xdeadbeef) # Add the lower 12 bits to x1
# -- %pcrel_hi() and %pcrel_lo() is similar to %hi() and %lo(), but the value returned is not absolute address
# But the value returned is the address relative to current PC.
# -- Immediate value supports ascii characters for instructions like MVI, LI
# For eg: LI r0, 'A' # Loads 0x41 to r0 register
# Supports '\n', '\r', '\t' escape sequences and all 7-bit ascii characters from 0x20 to 0x7E.
# -- Invoking the script from terminal:
# python pqr5asm.py -file=<source file path> -pcrel
# -file = Assembly source file <filepath/filename>.s
# -pcrel = Applying this flag uses PC relative addressing for instructions like LA, JA
# This flag hence directs assembler and linker to generate relocatable binary code.
# If this flag is not used, absolute address is loaded by the instructions.
# The generate binary code may not be relocatable.
# Binary/Hex code files are generated in same path
# If no arguments provided, source file = "./sample.s"
#
# Last modified on : Nov-2024
# Compatiblility : Python 3.9 tested
#
# User Manual : https://github.com/iammituraj/pqr5asm/blob/main/pqr5asm_imanual.pdf
#
# Copyright : Open-source license.
#################################################################################################################################
# Import Libraries
import numpy as np
import sys
import re
# --------------------------- Global Vars ----------------------------------- #
DEBUG = True
# List of registers supported
reglist = ['x0', 'x1', 'x2', 'x3', 'x4', 'x5', 'x6',
'x7', 'x8', 'x9', 'x10', 'x11', 'x12',
'x13', 'x14', 'x15', 'x16', 'x17', 'x18',
'x19', 'x20', 'x21', 'x22', 'x23', 'x24',
'x25', 'x26', 'x27', 'x28', 'x29', 'x30', 'x31',
'X0', 'X1', 'X2', 'X3', 'X4', 'X5', 'X6',
'X7', 'X8', 'X9', 'X10', 'X11', 'X12',
'X13', 'X14', 'X15', 'X16', 'X17', 'X18',
'X19', 'X20', 'X21', 'X22', 'X23', 'X24',
'X25', 'X26', 'X27', 'X28', 'X29', 'X30', 'X31',
'zero', 'ZERO', 'ra', 'RA', 'sp', 'SP', 'gp', 'GP', 'tp', 'TP',
't0', 'T0', 't1', 'T1', 't2', 'T2', 's0', 'S0',
's1', 'S1', 'a0', 'A0', 'a1', 'A1', 'a2', 'A2',
'a3', 'A3', 'a4', 'A4', 'a5', 'A5', 'a6', 'A6',
'a7', 'A7', 's2', 'S2', 's3', 'S3', 's4', 'S4',
's5', 'S5', 's6', 'S6', 's7', 'S7', 's8', 'S8',
's9', 'S9', 's10', 'S10', 's11', 'S11', 't3', 'T3',
't4', 'T4', 't5', 'T5', 't6', 'T6']
# ----------------------- User-defined functions ---------------------------- #
# Function to print debug message
def printdbg(s):
if DEBUG:
print(s)
# Function to print welcome message
def print_welcome():
print('')
print("/////////////////////////////////////////////////////")
#print("=====================================================")
print(" ______ ")
print(" ____ ____ ______/ ____/___ __________ ___ TM")
print(" / __ \/ __ `/ ___/___ \/ __ `/ ___/ __ `__ \\")
print(" / /_/ / /_/ / / ____/ / /_/ (__ ) / / / / /")
print(" / .___/\__, /_/ /_____/\__,_/____/_/ /_/ /_/ ")
print(" /_/ /_/ ")
print("")
print(" - RV32I Assembler for RISC-V CPUs")
print("=====================================================")
print('')
print(' OPEN-SOURCE licensed')
print('')
print(" Chipmunk Logic (TM) 2024")
print(" Visit us: chipmunklogic.com")
print('')
print("=====================================================")
print("/////////////////////////////////////////////////////")
print('')
# Function to print PASS
def print_pass():
print('')
print("==========================================")
print("'########:::::'###:::::'######:::'######::")
print("'##.... ##:::'## ##:::'##... ##:'##... ##:")
print("'##:::: ##::'##:. ##:: ##:::..:: ##:::..::")
print("'########::'##:::. ##:. ######::. ######::")
print("'##.....::: #########::..... ##::..... ##:")
print("'##:::::::: ##.... ##:'##::: ##:'##::: ##:")
print("'##:::::::: ##:::: ##:. ######::. ######::")
print("..:::::::::..:::::..:::......::::......:::")
print("==========================================")
print('')
# Function to print FAIL
def print_fail():
print('')
print("=====================================")
print("'########::::'###::::'####:'##:::::::")
print("'##.....::::'## ##:::. ##:: ##:::::::")
print("'##::::::::'##:. ##::: ##:: ##:::::::")
print("'######:::'##:::. ##:: ##:: ##:::::::")
print("'##...:::: #########:: ##:: ##:::::::")
print("'##::::::: ##.... ##:: ##:: ##:::::::")
print("'##::::::: ##:::: ##:'####: ########:")
print("..::::::::..:::::..::....::........::")
print("=====================================")
print('')
# Function to dump .bin file
def write2bin(datsize, baddr, dbytearray, binfile, memtype):
# Insert pre-amble 0xC0C0C0C0 (IMEM) / 0xD0D0D0D0 (DMEM)
if memtype == 1: # DMEM
dbytearray.insert(0, int("11010000", 2)) #MSB
dbytearray.insert(1, int("11010000", 2))
dbytearray.insert(2, int("11010000", 2))
dbytearray.insert(3, int("11010000", 2))
else: # IMEM
dbytearray.insert(0, int("11000000", 2)) #MSB
dbytearray.insert(1, int("11000000", 2))
dbytearray.insert(2, int("11000000", 2))
dbytearray.insert(3, int("11000000", 2))
# Insert program size
datsize_bytearray = datsize.to_bytes(4, 'big')
dbytearray.insert(4, datsize_bytearray[0]) #MSB
dbytearray.insert(5, datsize_bytearray[1])
dbytearray.insert(6, datsize_bytearray[2])
dbytearray.insert(7, datsize_bytearray[3])
# Insert PC base address
baddr_bytearray = baddr.to_bytes(4, 'big')
dbytearray.insert(8, baddr_bytearray[0]) #MSB
dbytearray.insert(9, baddr_bytearray[1])
dbytearray.insert(10, baddr_bytearray[2])
dbytearray.insert(11, baddr_bytearray[3])
# Insert post-amble 0xE0E0E0E0
dbytearray.append(int("11100000", 2)) #MSB
dbytearray.append(int("11100000", 2))
dbytearray.append(int("11100000", 2))
dbytearray.append(int("11100000", 2))
# Write to bin file
binfile.write(dbytearray)
# Function to print code in ascii
def print_code(mycode_text):
ln = 1
for line in mycode_text:
print('%+3s' % ln, ". ", line)
ln = ln + 1
# Function to print code in hex
def print_code_hex(mycode_text_bin):
ln = 1
for line in mycode_text_bin:
print('%+3s' % ln, ". ", "{:08x}".format(int(line, 2))) # "0x{:08x}" to display 0x in front
ln = ln + 1
# Function to print label table
def print_label_table(secname, labelcnt, label_list, label_addr_list):
if labelcnt[0] == 0:
return 1
print('')
print('+------------------+----------+-----------------')
print('| Label | Section | Address Mapping')
print('+------------------+----------+-----------------')
for i in range(labelcnt[0]):
print('| %+-16s' % label_list[i], '| %+-8s' %secname, "| 0x{:08x}".format(label_addr_list[i]))
print('+------------------+----------+-----------------')
print('')
# Function to validate label names
def is_validname_label(label):
# Check if label starts with a number
if label and label[0].isdigit():
return False
# Check if label contains only allowed characters (alphabets, digits, underscores)
if not re.fullmatch(r'[A-Za-z_][A-Za-z0-9_]*', label):
return False
return True
# Function to validate assembly source file
def validate_assembly(file_handler):
file_handler.seek(0) # Ensure file pointer is at the start
text_section_found = False
data_section_found = False
org_found = False
org_address = None
data_section_position = None
text_section_position = None
lines = file_handler.readlines()
i = 0
# Iterate thru each line
while i < len(lines):
line = lines[i].strip()
# Parse .text
if line.startswith(".section .text"):
if text_section_found:
print("| ERROR: Multiple occurrences of .section .text found.")
print_fail()
exit(1)
text_section_found = True
text_section_position = i
# Move to the next line(s) to find the .org directive
i += 1
while i < len(lines):
next_line = lines[i].strip()
# Remove comments from the line
next_line = next_line.split('#')[0].strip()
# Skip empty lines and comment-only lines
if not next_line:
i += 1
continue
# Check if the next valid line is an .org directive
if next_line.startswith(".org"):
org_parts = next_line.split()
if len(org_parts) != 2 or not (org_parts[1].startswith("0x") or org_parts[1].startswith("0X")):
print("| ERROR: Invalid format for .org directive in .section .text, only Hex supported!")
print_fail()
exit(1)
addr_str = org_parts[1]
try:
# Support only hexadecimal (0x or 0X) values
org_address = int(addr_str, 16)
# Round address to the next multiple of 4 if unaligned word addr
org_address = ((org_address + 3) // 4) * 4 if org_address % 4 != 0 else org_address
# Print the address in the desired format
print(f"| INFO : Parsed .text .org address: 0x{org_address:08x}")
except ValueError:
print("| ERROR: Invalid .org address format in .section .text")
print_fail()
exit(1)
org_found = True
break
else:
print("| ERROR: .org directive missing after .section .text")
print_fail()
exit(1)
if not org_found:
print("| ERROR: .org directive missing after .section .text")
print_fail()
exit(1)
# Parse .data
elif line.startswith(".section .data"):
if data_section_found:
print("| ERROR: Multiple occurrences of .section .data found!")
print_fail()
exit(1)
data_section_found = True
data_section_position = i
# Move to the next line(s) to find the .org directive
i += 1
while i < len(lines):
next_line = lines[i].strip()
# Remove comments from the line
next_line = next_line.split('#')[0].strip()
# Skip empty lines and comment-only lines
if not next_line:
i += 1
continue
# Check if the next valid line is an .org directive
if next_line.startswith(".org"):
org_parts = next_line.split()
if len(org_parts) != 2 or not (org_parts[1].startswith("0x") or org_parts[1].startswith("0X")):
print("| ERROR: Invalid format for .org directive in .section .data, , only Hex supported!")
print_fail()
exit(1)
addr_str = org_parts[1]
try:
# Support only hexadecimal (0x or 0X) values
org_address = int(addr_str, 16)
# Round address to the next multiple of 4 if unaligned word addr
if org_address % 4 != 0:
print("| WARNG: .data .org address should be 4-byte aligned.. remapping the base address...")
org_address = ((org_address + 3) // 4) * 4 if org_address % 4 != 0 else org_address
data_baseaddr[0] = org_address
# Print the address in the desired format
print(f"| INFO : Parsed .data .org address: 0x{org_address:08x}")
except ValueError:
print("| ERROR: Invalid .org address format in .section .data")
print_fail()
exit(1)
org_found = True
break
else:
print("| ERROR: .org directive missing after .section .data")
print_fail()
exit(1)
if not org_found:
print("| ERROR: .org directive missing after .section .data")
print_fail()
exit(1)
i += 1
# Check if .data section is defined before .text section
if data_section_found and text_section_found and data_section_position > text_section_position:
print("| ERROR: .section .data must be defined before .section .text")
print_fail()
exit(1)
# Check if .text section exists at all!
if not text_section_found:
print("| ERROR: Missing .section .text")
print_fail()
exit(1)
print("\n| INFO : Assembly code file validation successful!!\n")
return org_address
# Function to parse ascii char arguments and convert to hex
def char2hex(char):
if char == ' ':
return '0x20'
elif char == '!':
return '0x21'
elif char == '"':
return '0x22'
elif char == '#':
return '0x23'
elif char == '$':
return '0x24'
elif char == '%':
return '0x25'
elif char == '&':
return '0x26'
elif char == "'":
return '0x27'
elif char == '(':
return '0x28'
elif char == ')':
return '0x29'
elif char == '*':
return '0x2A'
elif char == '+':
return '0x2B'
elif char == ',':
return '0x2C'
elif char == '-':
return '0x2D'
elif char == '.':
return '0x2E'
elif char == '/':
return '0x2F'
elif char == '0':
return '0x30'
elif char == '1':
return '0x31'
elif char == '2':
return '0x32'
elif char == '3':
return '0x33'
elif char == '4':
return '0x34'
elif char == '5':
return '0x35'
elif char == '6':
return '0x36'
elif char == '7':
return '0x37'
elif char == '8':
return '0x38'
elif char == '9':
return '0x39'
elif char == ':':
return '0x3A'
elif char == ';':
return '0x3B'
elif char == '<':
return '0x3C'
elif char == '=':
return '0x3D'
elif char == '>':
return '0x3E'
elif char == '?':
return '0x3F'
elif char == '@':
return '0x40'
elif char == 'A':
return '0x41'
elif char == 'B':
return '0x42'
elif char == 'C':
return '0x43'
elif char == 'D':
return '0x44'
elif char == 'E':
return '0x45'
elif char == 'F':
return '0x46'
elif char == 'G':
return '0x47'
elif char == 'H':
return '0x48'
elif char == 'I':
return '0x49'
elif char == 'J':
return '0x4A'
elif char == 'K':
return '0x4B'
elif char == 'L':
return '0x4C'
elif char == 'M':
return '0x4D'
elif char == 'N':
return '0x4E'
elif char == 'O':
return '0x4F'
elif char == 'P':
return '0x50'
elif char == 'Q':
return '0x51'
elif char == 'R':
return '0x52'
elif char == 'S':
return '0x53'
elif char == 'T':
return '0x54'
elif char == 'U':
return '0x55'
elif char == 'V':
return '0x56'
elif char == 'W':
return '0x57'
elif char == 'X':
return '0x58'
elif char == 'Y':
return '0x59'
elif char == 'Z':
return '0x5A'
elif char == '[':
return '0x5B'
elif char == '\\':
return '0x5C'
elif char == ']':
return '0x5D'
elif char == '^':
return '0x5E'
elif char == '_':
return '0x5F'
elif char == '`':
return '0x60'
elif char == 'a':
return '0x61'
elif char == 'b':
return '0x62'
elif char == 'c':
return '0x63'
elif char == 'd':
return '0x64'
elif char == 'e':
return '0x65'
elif char == 'f':
return '0x66'
elif char == 'g':
return '0x67'
elif char == 'h':
return '0x68'
elif char == 'i':
return '0x69'
elif char == 'j':
return '0x6A'
elif char == 'k':
return '0x6B'
elif char == 'l':
return '0x6C'
elif char == 'm':
return '0x6D'
elif char == 'n':
return '0x6E'
elif char == 'o':
return '0x6F'
elif char == 'p':
return '0x70'
elif char == 'q':
return '0x71'
elif char == 'r':
return '0x72'
elif char == 's':
return '0x73'
elif char == 't':
return '0x74'
elif char == 'u':
return '0x75'
elif char == 'v':
return '0x76'
elif char == 'w':
return '0x77'
elif char == 'x':
return '0x78'
elif char == 'y':
return '0x79'
elif char == 'z':
return '0x7A'
elif char == '{':
return '0x7B'
elif char == '|':
return '0x7C'
elif char == '}':
return '0x7D'
elif char == '~':
return '0x7E'
elif char == '\\n':
return '0x0A'
elif char == '\\r':
return '0x0D'
elif char == '\\t':
return '0x09'
elif char == '':
return '0x00'
else:
return '#ERR'
# Function to parse char/string argument and convert to hex
def parseascii(arg, psts):
if arg:
s = arg[0]
parts = s.split("'")
if ((len(parts) == 3 and len(parts[1]) == 1) or
(len(parts) == 3 and len(parts[1]) == 0) or
((len(parts) == 3 and len(parts[1]) == 2) and (parts[1] == '\\n' or parts[1] == '\\r' or parts[1] == '\\t'))):
arghex = char2hex(parts[1])
psts[0] = True
if arghex != "#ERR":
modified_expr = parts[0] + arghex + parts[2]
arg[0] = modified_expr
else:
arg[0] = arg
elif ((len(parts) == 3 and len(parts[1]) == 2) and (parts[1] == '\\\\')): # For backslash character: \\
psts[0] = True
arg[0] = "0x5C"
elif ((len(parts) == 4 and len(parts[1]) == 1) and (parts[1] == '\\')): # For single quote character: \'
psts[0] = True
arg[0] = "0x27"
# Function to generate hex instructions from binary instructions
def gen_instr_hex(instr_bin, instr_hex):
for line in instr_bin:
instr_hex.append("{:08x}".format(int(line, 2))) # 32-bit hex from binary string
# Function to return address of label
def addr_of_label(labelname, labelid):
for i in range(labelcnt[0]):
if labelname == label_list[i]:
labelid[0] = i
return label_addr_list[i]
for i in range(dlabelcnt[0]):
if labelname == dlabel_list[i]:
labelid[0] = i
return dlabel_addr_list[i]
return 0
# Function to check if a register operand is valid or not
def is_invalid_reg(reg):
if reg not in reglist:
return 1
else:
return 0
# Function to check if a label is valid or not
def is_valid_label(lbl, isjbinstr=False):
if lbl in label_list:
is_text_label[0] = True
else:
is_text_label[0] = False
if lbl in dlabel_list:
is_data_label[0] = True
else:
is_data_label[0] = False
if not isjbinstr: # Not Jump/Branch instruction's label
if (lbl in label_list) or (lbl in dlabel_list):
return 1
else:
return 0
else:
if (lbl in label_list):
return 1
else:
return 0
# Function to convert register (x0-x31) to its binary code
def reg2bin(reg):
if reg == 'x0' or reg == 'X0' or reg == 'zero' or reg == 'ZERO':
return '00000'
elif reg == 'x1' or reg == 'X1' or reg == 'ra' or reg == 'RA':
return '00001'
elif reg == 'x2' or reg == 'X2' or reg == 'sp' or reg == 'SP':
return '00010'
elif reg == 'x3' or reg == 'X3' or reg == 'gp' or reg == 'GP':
return '00011'
elif reg == 'x4' or reg == 'X4' or reg == 'tp' or reg == 'TP':
return '00100'
elif reg == 'x5' or reg == 'X5' or reg == 't0' or reg == 'T0':
return '00101'
elif reg == 'x6' or reg == 'X6' or reg == 't1' or reg == 'T1':
return '00110'
elif reg == 'x7' or reg == 'X7' or reg == 't2' or reg == 'T2':
return '00111'
elif reg == 'x8' or reg == 'X8' or reg == 'fp' or reg == 'FP' or reg == 's0' or reg == 'S0':
return '01000'
elif reg == 'x9' or reg == 'X9' or reg == 's1' or reg == 'S1':
return '01001'
elif reg == 'x10' or reg == 'X10' or reg == 'a0' or reg == 'A0':
return '01010'
elif reg == 'x11' or reg == 'X11' or reg == 'a1' or reg == 'A1':
return '01011'
elif reg == 'x12' or reg == 'X12' or reg == 'a2' or reg == 'A2':
return '01100'
elif reg == 'x13' or reg == 'X13' or reg == 'a3' or reg == 'A3':
return '01101'
elif reg == 'x14' or reg == 'X14' or reg == 'a4' or reg == 'A4':
return '01110'
elif reg == 'x15' or reg == 'X15' or reg == 'a5' or reg == 'A5':
return '01111'
elif reg == 'x16' or reg == 'X16' or reg == 'a6' or reg == 'A6':
return '10000'
elif reg == 'x17' or reg == 'X17' or reg == 'a7' or reg == 'A7':
return '10001'
elif reg == 'x18' or reg == 'X18' or reg == 's2' or reg == 'S2':
return '10010'
elif reg == 'x19' or reg == 'X19' or reg == 's3' or reg == 'S3':
return '10011'
elif reg == 'x20' or reg == 'X20' or reg == 's4' or reg == 'S4':
return '10100'
elif reg == 'x21' or reg == 'X21' or reg == 's5' or reg == 'S5':
return '10101'
elif reg == 'x22' or reg == 'X22' or reg == 's6' or reg == 'S6':
return '10110'
elif reg == 'x23' or reg == 'X23' or reg == 's7' or reg == 'S7':
return '10111'
elif reg == 'x24' or reg == 'X24' or reg == 's8' or reg == 'S8':
return '11000'
elif reg == 'x25' or reg == 'X25' or reg == 's9' or reg == 'S9':
return '11001'
elif reg == 'x26' or reg == 'X26' or reg == 's10' or reg == 'S10':
return '11010'
elif reg == 'x27' or reg == 'X27' or reg == 's11' or reg == 'S11':
return '11011'
elif reg == 'x28' or reg == 'X28' or reg == 't3' or reg == 'T3':
return '11100'
elif reg == 'x29' or reg == 'X29' or reg == 't4' or reg == 'T4':
return '11101'
elif reg == 'x30' or reg == 'X30' or reg == 't5' or reg == 'T5':
return '11110'
else:
return '11111'
# Function to define .data labels address mapping
def define_dlabel(code_text, dlabel_list, dlabel_addr_list, dlabelcnt):
valid_directives = {".p2align", ".zero", ".string", ".ascii", ".byte", ".hword", ".word"}
current_label = None
is_start_of_label = False
# Iterate thru each line
for i, line in enumerate(code_text):
# Remove inline comments and strip whitespace
stripped_line = line.split('#', 1)[0].strip()
# Skip lines that are comments or blank
if not stripped_line:
continue
# Check if the line contains .section .text directive
if stripped_line.startswith('.section'):
if '.text' in stripped_line:
return
# Check if the line ends with a colon (potential label)
if stripped_line.endswith(':'):
label = stripped_line.rstrip(':').strip()
# Ensure the label does not contain whitespace
if ' ' in label:
print(f"| ERROR: Line {i + 1}: The label '{label}' is invalid due to spaces!")
print_fail()
exit(1)
# Check if the label already exists in the list
if label in dlabel_list:
print(f"| ERROR: Line {i + 1}: The label '{label}' has multiple definitions!")
print_fail()
exit(1)
elif not is_validname_label(label):
print(f"| ERROR: Line {i + 1}: The label '{label}' has naming violations!")
print_fail()
exit(1)
# Valid label, hence update the current label
current_label = label
dlabel_list.append(label)
dlabel_addr_list.append(dptr[0])
dlabelcnt[0] = dlabelcnt[0] + 1
is_start_of_label = True
#print("\nalignment override disabled")#dbg
#print(current_label)#dbg
#print(f"DPTR[0] --> 0x{dptr[0]:08x}")#dbg
continue # Move to the next line for processing directives
# If there is no current label, skip processing
if current_label is None:
continue
# Ensure proper format between directive and argument
if ' ' in stripped_line:
directive, _, argument = stripped_line.partition(' ')
if directive not in valid_directives:
print(f"| ERROR: Line {i + 1}: The directive '{directive}' is invalid!")
print_fail()
exit(1)
if not argument:
print(f"| ERROR: Line {i + 1}: No argument provided for the directive '{directive}'!")
print_fail()
exit(1)
else:
# No space between directive and argument
print(f"| ERROR: Line {i + 1}: No argument provided for the directive '{stripped_line}'!")
print_fail()
exit(1)
# Validate the argument based on the directive
# .p2align <n> ==> 2^n align
if directive == ".p2align" and is_start_of_label:
if not is_valid_align_argument(argument):
print(f"| ERROR: Line {i + 1}: Invalid argument for .p2align directive!")
print_fail()
exit(1)
align_bound_override = 2**int(argument, 0)
#print("alignment override active = ", align_bound_override, "bytes")#dbg
dptr[0] = addr_of_label(current_label, labelid)
#print(f"DPTR[0] original = 0x{dptr[0]:08x}")#dbg
zsize = (align_bound_override - (dptr[0] % align_bound_override)) % align_bound_override
#print("alignment zero-padding =", zsize, "bytes")#dbg
dptr[0] = zsize + dptr[0]
#print(f"DPTR[0] modified = 0x{dptr[0]:08x}")#dbg
# Update data label addresses
dlabel_addr_list[labelid[0]] = dptr[0]
# Update dmem binary data
upd_dmem_data("zero", zsize, 0, "0x00")
# .zero <no. of zero-padding bytes>
elif directive == ".zero":
if not is_valid_zero_argument(argument):
print(f"| ERROR: Line {i + 1}: Invalid argument for .zero directive!")
print_fail()
exit(1)
# {Zero padding, data} size calculation
is_start_of_label = False
align_bound = 1
zsize = int(argument, 0)
dsize = 0
tsize = zsize + dsize
#print("ZERO, zero-padding =", zsize, "bytes, dsize =", dsize, "bytes")#dbg
# Update data pointer
dptr[0] = dptr[0] + tsize
#print(f"DPTR[0] --> 0x{dptr[0]:08x}")#dbg
# Update dmem binary data
upd_dmem_data("zero", zsize, dsize, "0x00")
# .string "<auto null terminated string>"
elif directive == ".string":
if not is_valid_string_argument(argument):
print(f"| ERROR: Line {i + 1}: Invalid argument for .string directive!")
print_fail()
exit(1)
# {Zero padding, data} size calculation
is_start_of_label = False
align_bound = 1
zsize = (align_bound - (dptr[0] % align_bound)) % align_bound
dsize = calculate_string_size(argument)
tsize = zsize + dsize
#print("STRING, zero-padding =", zsize, "bytes, dsize =", dsize, "bytes")#dbg
# Update data pointer
dptr[0] = dptr[0] + tsize
#print(f"DPTR[0] --> 0x{dptr[0]:08x}")#dbg
write_str2dmem(argument)
# .ascii '<char>'
elif directive == ".ascii":
if not is_valid_ascii_argument(argument):
print(f"| ERROR: Line {i + 1}: Invalid argument for .ascii directive!")
print_fail()
exit(1)
# {Zero padding, data} size calculation
is_start_of_label = False
align_bound = 1
zsize = (align_bound - (dptr[0] % align_bound)) % align_bound
dsize = 1
tsize = zsize + dsize
#print("ASCII CHAR, zero-padding =", zsize, "bytes, dsize =", dsize, "bytes")#dbg
# Update data pointer
dptr[0] = dptr[0] + tsize
#print(f"DPTR[0] --> 0x{dptr[0]:08x}")#dbg
arghexval = [argument]
parseascii(arghexval, [0])
# Update dmem binary data
upd_dmem_data("byte", 0, 1, arghexval[0])
# .byte <byte>
elif directive == ".byte":
if not is_valid_byte_argument(argument):
print(f"| ERROR: Line {i + 1}: Invalid argument for .byte directive!")
print_fail()
exit(1)
# {Zero padding, data} size calculation
is_start_of_label = False
align_bound = 1
zsize = (align_bound - (dptr[0] % align_bound)) % align_bound
dsize = 1
tsize = zsize + dsize
#print("BYTE, zero-padding =", zsize, "bytes, dsize =", dsize, "bytes")#dbg
# Update data pointer
dptr[0] = dptr[0] + tsize
#print(f"DPTR[0] --> 0x{dptr[0]:08x}")#dbg
# Update dmem binary data
upd_dmem_data("byte", zsize, dsize, argument)
# .hword <naturally aligned half word of two bytes>
elif directive == ".hword":
if not is_valid_hword_argument(argument):
print(f"| ERROR: Line {i + 1}: Invalid argument for .hword directive!")
print_fail()
exit(1)
# {Zero padding, data} size calculation
if is_start_of_label:
align_bound_override = 2
#print("Re-alignment active = ", align_bound_override, "bytes")#dbg
dptr[0] = addr_of_label(current_label, labelid)
#print(f"DPTR[0] original = 0x{dptr[0]:08x}")#dbg
dptr[0] = (align_bound_override - (dptr[0] % align_bound_override)) % align_bound_override + dptr[0]
#print(f"DPTR[0] modified = 0x{dptr[0]:08x}")#dbg
dlabel_addr_list[labelid[0]] = dptr[0]
is_start_of_label = False
align_bound = 2
zsize = (align_bound - (dptr[0] % align_bound)) % align_bound
dsize = 2
tsize = zsize + dsize
#print("HWORD, zero-padding =", zsize, "bytes, dsize =", dsize, "bytes")#dbg
# Update data pointer
dptr[0] = dptr[0] + tsize
#print(f"DPTR[0] --> 0x{dptr[0]:08x}")#dbg
# Update dmem binary data
upd_dmem_data("hword", zsize, dsize, argument)
# .word <naturally aligned word of 4 bytes>
elif directive == ".word":
if not is_valid_word_argument(argument):
print(f"| ERROR: Line {i + 1}: Invalid argument for .word directive!")
print_fail()
exit(1)
# {Zero padding, data} size calculation
if is_start_of_label:
align_bound_override = 4
#print("Re-alignment active = ", align_bound_override, "bytes")#dbg
dptr[0] = addr_of_label(current_label, labelid)
#print(f"DPTR[0] original = 0x{dptr[0]:08x}")#dbg
dptr[0] = (align_bound_override - (dptr[0] % align_bound_override)) % align_bound_override + dptr[0]
#print(f"DPTR[0] modified = 0x{dptr[0]:08x}")#dbg
dlabel_addr_list[labelid[0]] = dptr[0]
is_start_of_label = False
align_bound = 4
zsize = (align_bound - (dptr[0] % align_bound)) % align_bound
dsize = 4
tsize = zsize + dsize
#print("WORD, zero-padding =", zsize, "bytes, dsize =", dsize, "bytes")#dbg
# Update data pointer
dptr[0] = dptr[0] + tsize
#print(f"DPTR[0] --> 0x{dptr[0]:08x}")#dbg
# Update dmem binary data
upd_dmem_data("word", zsize, dsize, argument)
# Function to verify the align argument is valid
def is_valid_align_argument(argument):
try:
# Check if the argument allows alignment up to 4k bytes
if argument.isdigit() and int(argument) >= 0 and int(argument) <= 12 :
return 1
# Check if the argument is a valid hexadecimal number with '0x' or '0X' prefix
if argument.lower().startswith('0x'):
int(argument, 16) # Try to convert it to an integer using base 16
return 1
except ValueError:
# Catch the exception if the conversion fails
return 0
# If neither condition is met, return 0
return 0
# Function to verify if the zero argument is valid