r/Compilers 6d ago

x86-64 Assembler from scratch

Enable HLS to view with audio, or disable this notification

AmmAsm is an open-source, handwritten x86-64 assembler written in C from scratch.

Hello, my name is Ammar, and I'm 15 y. o. About a year ago I started writing AmmAsm, a handwritten x86-64 assembler in C as a way to learn how machine code, ELF, and linking actually work.

Today it can generate Linux x86-64 executables, PIE binaries, and ELF relocatable object files that can be linked with "ld" or "gcc". Along the way I implemented a lexer, parser, expression evaluator, x86-64 instruction encoder, ELF writer, relocations, and symbol resolution. It syntax is almost same with Intel, as it has major difference: using [b=, i=, s=, d=] addressing instead of Nasm's [base + index * scale + disp]. Also supports SSE (Float4), CMOVcc, SETcc.

it is bootstraped about 0.257% :)

The latest version(2.2.0) also includes a macro preprocessor.

I'd really appreciate any feedback on the project, code, or documentation. Thanks!

repo: https://github.com/LinuxCoder13/AmmAsm.git

132 Upvotes

10 comments sorted by

11

u/[deleted] 6d ago

[removed] — view removed comment

3

u/This-Assumption-5924 5d ago edited 5d ago

Nice, that's exactly what I was hoping to see. The bounds checks make it much safer now, and the -o handling will be fixed too as soon as possible. Good improvements. Thanks.

3

u/Polyscone 6d ago

Very nice.

I've been writing an encoder myself, so I mostly looked at that code.

It seems like you're writing a specialised function for each instruction, so unless I've missed it, do you plan on writing a more general encode function based on tables?

2

u/This-Assumption-5924 5d ago

in x86-64 there are 8 groups of instruction, each group has 1-7 instructions and their encoding are olmost same. So yep, I will try to refactor the encoders in order to make in less chaos

4

u/Polyscone 5d ago edited 5d ago

Yea you can basically just have a table of each instruction with metadata, then you just encode things like ModRM, SIB, immediates etc. the same and prefixes only change based on Legacy/VEX/EVEX encodings.

Then the general function can decide how to encode by combining operands and looking at table metadata.

EVEX also has compressed 8 bit displacement, but that's not too difficult to deal with either.

2

u/rex-j-w 3h ago

Pure torment and torture, I applaud you

1

u/This-Assumption-5924 2h ago

Thank you so much. I appreciate that ;)

-1

u/Status_Role181 5d ago

Is this AI-slop?

3

u/This-Assumption-5924 5d ago edited 4d ago

Good question, Alexander. As you can see in github repo. There's writen that, "AI-assisted", as it doesn't mean that project was entirely writen by ai. I used AI in order to eschew routine work. I am assuming that AI sloped it or not, doesn't even matter. People are evaluting the opportunity of software, not the way which software was implemented. Thanks.