1
Fork 0
hare-nix/pkgs/hare-as.py

68 lines
1.8 KiB
Python
Raw Normal View History

#!python3
2024-05-14 19:06:04 +00:00
import re
import sys
from subprocess import Popen, PIPE
2024-05-14 19:06:04 +00:00
def header(filename):
return f"""
# ------------------
.file "{filename}"
# ------------------
"""
REPLACEMENTS = [
(r'^\.section "\.text([^"]*)"(,"([^"]*))?"$', r'.text ; \1, \3'),
(r'^\.section "\.data([^"]*)"$', r'.data ; \1'),
(r'^\.section "\.bss([^"]*)"$', r'.bss ; \1'),
(r'^\.section "\.init_array"(,"([^"]*)")?', r'.section __DATA, .init_array ; \2'),
(r'^\.section "\.fini_array"(,"([^"]*)")?', r'.section __DATA, .fini_array ; \2'),
(r'^\.section "\.test_array"(,"([^"]*)")?', r'.section __DATA, .test_array ; \2'),
(r'^\.section \.abort "([^"]+)"', r'.section __DATA, .abort $COMMENT \1'),
(r'^(\.type .+)', '; \1'),
(r'^(\.global) (rt\..+)', r'\1 _\2'),
(r'^(rt\..+:)', r'_\1'),
(r'^(crypto\.aes\.x86ni_.+:)', r'_\1'),
(r'^(debug\.getfp:)', r'_\1'),
(r'adrp x0, _environ@page', r'adrp x0, _environ@GOTPAGE'),
(r'add x0, x0, _environ@pageoff', r'ldr x0, [x0, _environ@GOTPAGEOFF]'),
]
def fix_asm(code):
for (pattern, repl) in REPLACEMENTS:
code = re.sub(pattern, repl, code, flags=re.MULTILINE)
return code
args = ['as']
files = []
argv = sys.argv[1:]
while len(argv):
if argv[0] == "--":
args.append("--")
elif argv[0] in ["-o", "-I", "-arch"]:
args.append(argv[0])
args.append(argv[1])
argv.pop(0)
elif argv[0][0] == "-":
argv.append(argv[0])
else:
files.append(argv[0])
argv.pop(0)
args.append("-")
code = ""
for file in files:
with open(file) as fp:
content = fp.read()
code += header(file)
code += "\n"
code += fix_asm(content)
code += "\n"
p = Popen(args, stdout=PIPE, stdin=PIPE, stderr=PIPE, text=True)
data = p.communicate(input=code)
print(data[1], end='', file=sys.stderr)
print(data[0], end='')