Created
November 10, 2023 02:02
-
-
Save deckarep/7d49561703abac84d2e00a500644883e to your computer and use it in GitHub Desktop.
A quick and dirty work-in-progress script that can help align blocks of assembly language since doing it manually is tedious and boring and hurts my eyes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import sys | |
class NasmAligner: | |
def __init__(self, start_address=0): | |
self.alignments = {'DB': 1, 'DW': 2, 'DD': 4, 'DQ': 8} | |
self.output_lines = [] | |
self.current_address = start_address | |
def align_statements(self, statements): | |
for statement in statements: | |
parts = statement.split(maxsplit=1) | |
directive, rest = parts[0], parts[1] if len(parts) > 1 else '' | |
alignment = self.alignments.get(directive, 1) | |
# Align the current address if necessary | |
padding_needed = (-self.current_address) % alignment | |
self.current_address += padding_needed | |
# If padding is needed, insert ALIGN directive | |
if padding_needed: | |
self.output_lines.append(f"ALIGN {alignment}") | |
# Append the original statement with a comment indicating the address after alignment | |
address_comment = f"; address: {self.current_address:06X}h" | |
self.output_lines.append(f"{statement: <22} {address_comment: >22}") | |
# Calculate the new address, assuming the rest part contains one define statement | |
defined_count = rest.count(',') + 1 if rest else 1 | |
self.current_address += defined_count * alignment | |
return self.output_lines | |
if __name__ == "__main__": | |
if len(sys.argv) > 1: | |
starting_addr = int(sys.argv[1], 16) | |
else: | |
starting_addr = 0 | |
# Example usage with a predefined starting address | |
na = NasmAligner(starting_addr) | |
statements = [ | |
'DB 0x55', | |
'DB 0x10, 0x20', | |
'DW 0x1234', | |
'DD 0x12345678', | |
'DB 0xAA', | |
'DW 0x9876', | |
'DD 0xABCDEF01', | |
'DQ 0x123456789ABCDEF0' | |
] | |
# Running the aligner with a predefined starting address | |
results = na.align_statements(statements) | |
for x in results: | |
print(x) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment