# Make assembly file from ELF symbols map
# Then link it to kernel so it's aware of symbol names
# then we can use that for the stack trace.

print("Extracting symbols from map file to assembly...")

with open("symbols.map", "r") as f:
    lines = f.readlines()

    symbols = []
    for line in lines:
        parts = line.split()
        # output is formed like "address name"
        symbols.append((parts[0], parts[1]))

with open("symbols.S", "w") as f:
    f.write("section .rodata\n")
    f.write("global symbol_table\n")
    f.write("global symbol_count\n")
    f.write("symbol_table:\n")

    for i, (addr, name) in enumerate(symbols):
        f.write(f"    dq 0x{addr}\n")
        f.write(f"    dq sym_name_{i}\n")

    f.write("\nsymbol_count: dq " + str(len(symbols)) + "\n\n")

    for i, (addr, name) in enumerate(symbols):
        # escaping quotes
        safe_name = name.replace('"', '\\"')
        f.write(f'sym_name_{i}: db "{safe_name}", 0\n')

print("Done!")