Hacker News new | past | comments | ask | show | jobs | submit login
A gentle intro to assembly with Rust (lfn3.net)
135 points by lfn3 on Aug 3, 2020 | hide | past | favorite | 16 comments



Looking at the output of a compiler is a great way to quickly learn the basics of assembly coding for a particular platform, but learning the principles of programming in assembler and machine architecture is an entirely different story. Knuth's 1st volume remains the best in that regard.


TAOCP?


> And indeed, inside main we can see push rax - saving the value in the register rax to the stack, then a call to our add function, then we pop rax off the stack. The push call pop sequence is to preserve whatever values are in the registers used in add.

There's really no need to save rax here; I know that optimizations are off but I'm still curious why rustc thinks this is necessary…


The compiler is using push and pop here just for their side effect of adjusting the stack pointer, to keep the stack pointer 16-byte aligned.


Shouldn't the C runtime do that before calling main?


It does; the stack pointer starts out aligned, but then the function does a call, and the call instruction adjusts the stack pointer by 8 bytes to push the return address, which would cause it to be misaligned. The push pushes an extra 8 bytes so that the stack pointer is aligned in the callee.


Any reason not to just do some other “increment stack pointer” option?


The instruction is smaller. Push rax is encoded into 1 bytes, while an increment stack pointer would be 4.


But there is a missing feature: how do you generate assembly at runtime?


You need to use an external code generator library like llvm or cranelift, just like in any other language.


Not quite. Some languages bundle their compiler and code generated as part of the language runtime. Common Lisp is the one that comes to mind first.


Assemble learnt via high level language would encounter a lot of issues as the language provide a lot of feature.

Stacks, stack frames .bss, heap etc. And variable scoping and where doesn’t it store hence.

And interesting issues like interrupt, memory mapped io (volitile ) etc.

Plus many low end features like CAN ...

Only do c and assembly (ignore 370) and the mapping is not easy.


You are correct, Sir, but application-level people are happy to write a few lines of funny looking mnemonics to optimize their boring sort functions and then brag on LinkedIn. Also, if you are still in "_hk", please stop wasting time and get your friends and family out.


Why setb-test-jne? Couldn't you just do jc?


Yeah, it's just being built without optimizations in that case.


I didn't know Rust was an assembler.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: