Get under the hood of Rust Language with Assembly!! Rust Programming Tutorial

  Рет қаралды 32,776

Chris Hay

Chris Hay

Күн бұрын

If you want to truly understand how Rust works and what happens under the hood, it's worth learning the assembly that rust generates during the compile. By understanding Rust Assembly you can truly understand Rust Programming and become a master of the Rust Language (RustLang).
By the end of this video, you'll understand how to generate assembly from rust, how stack memory allocation works in rust programming and how rustlang is represented in assembly. You'll even be comfortable with assembly language statements, registers, stack and memory storage, and be able to walkthrough rust generated assembly yourself.
In this video we take a simple rust program and we convert it to assembly on your machine using native compilation (apple silicon) and cross compiling to x64 and emitting intel assembly. In addition we use a simple online tool called godbot which makes it easier to understand the assembly.
We then take our simple rust program and break down the generated assembly line by line, so understand what's happening underneath the hood.
Understanding assembly Language and the assembly rust generates will help you on that journey to becoming and Advanced Rust Programming expert.
00:00 - introduction
01:03 - create our rust project
03:36 - target folder and rust compile
04:27 - emitting rust assembly during compile
05:42 - cross compiling rust from apple silicon arm to x64 assembly
08:26 - emitting x64 assembly
09:10 - cargo show asm
09:23 - emitting rust assembly interleaved with rust using cargo show asm
11:10 - generating x64 intel assembly using rust and godbolt
12:30 - understanding stack frame memory allocation, stack pointer, rsp and sub
14:22 - variable assignment, mov and virtual registers
15:45 - assembly multiplication using imul
17:30 - storing local variables in the stack / stack frame memory for later use
19:10 - overflow checks and panickibng
21:10 - more calculations and some compiler optmizations
22:11 - understanding stack memory and primitive sizes and fixed memory
23:48 - jmp's are goto's in disguise
24:20 - more stack memory and compiler optimizations
27:45 - printing the result
28:08 - To Be Continued

Пікірлер: 120
@bestformspielt
@bestformspielt Жыл бұрын
Important to note: the overflow check after the calculations will only be done in the debug/dev build. In a release build they won't be done at all.
@chrishayuk
@chrishayuk Жыл бұрын
yes, will be covering releasing builds in a later part to this
@stephenJpollei
@stephenJpollei Жыл бұрын
Yeah, I assume the release build has a lot less. The multiplication and addition should be compile-time and should just spit-out the final result as a constant
@dyslexicsteak897
@dyslexicsteak897 Жыл бұрын
the register "a1" you mentioned is actually register "al" (that's an L) because it's the lower byte of 16 bit (2 byte) register ax, it has a sister register ah which is the higher byte.
@cerulity32k
@cerulity32k Жыл бұрын
I’ve always wondered: With 8 bit computers/consoles, is the register just labelled a? There are no high or low segments and no combined segment, so there would be no prefix/suffix.
@cmilkau
@cmilkau Жыл бұрын
@@cerulity32k Yes, the register is called A on the 8080.
@cmilkau
@cmilkau Жыл бұрын
long live 8086
@chrishayuk
@chrishayuk Жыл бұрын
yeah my intel assembly sucks... i will do a tutorial on this mainly to educate myself
@rsa5991
@rsa5991 Жыл бұрын
@@cerulity32k Intel 8008 and 8080 did have 8-bit registers be called A, B, C, D, E, H, and L, but it also had 16-bit pairs BC, DE, and HL. So Intel always had some kind of combined registers. On Intel 4004 registers are called r0..r15 and are combined in pairs 0P..7P. No letters.
@SimonClarkstone
@SimonClarkstone Жыл бұрын
I like this format for showing your face and the code at once; it's like you are reflected in the screen:
@chrishayuk
@chrishayuk Жыл бұрын
thanks... glad you like. i like the effect also, really glad you do too
@richsadowsky8580
@richsadowsky8580 Жыл бұрын
Instant subscriber. This is how I learned Z80, 8080, 80286, 386... and so fourth assembly languages by setting C, C++ and Pascal compilers to generate assembly output starting the the 1980s. Very strong video. Wish you had some resources listed like URL to website but I'll find it through ToC. Also, I wouldn't have thought to run my Intel cross compiled on my M1. Nice simple trick thanks to Rosetta.
@chrishayuk
@chrishayuk Жыл бұрын
thank you. glad you like
@davidgari3240
@davidgari3240 Жыл бұрын
You spelled FORTH wrong. 😢
@kaplansedat
@kaplansedat Жыл бұрын
Best Rust content on internet.
@chrishayuk
@chrishayuk Жыл бұрын
you are definitely too kind but glad you're enjoying. i'm sure it's frustrating that i jump merrily between languages based on my whims
@spaghettiking653
@spaghettiking653 Жыл бұрын
I'm very grateful for this video, since I'm making a compiler for school and need to understand what assembly to generate and how to handle all these language features in assembly :) Thanks hugely for the upload, hope to see more Rust and assembly!
@chrishayuk
@chrishayuk Жыл бұрын
Glad it helped!
@NOPerative
@NOPerative 6 ай бұрын
Title says it all. Rust became more apparent when I started looking at the language through my x86_64 asm glasses; FYI for everyone unfamiliar with assembler is relax - asm is not going to byte you (it will) but don't let it intimidate you. I still think assembler is a must and its disregard is where many run into issue understanding what needs to happen logically in code creating an environment wrought with unnecessary hair pulling.
@YourMom-rg5jk
@YourMom-rg5jk Жыл бұрын
KZbin recommended has been fantastic recently with leading me to these kinds of channels with videos explaining low level stuff. I appreciate these man they're really interesting.
@chrishayuk
@chrishayuk Жыл бұрын
Glad it’s useful
@_realist_6957
@_realist_6957 Жыл бұрын
I wish we would have been friends in real life and done programming together. You are doing really good job
@chrishayuk
@chrishayuk Жыл бұрын
that's so kind, thank you :)
@valentinomelis8331
@valentinomelis8331 Жыл бұрын
really like your style man, keep up the good work
@SandwichMitGurke
@SandwichMitGurke Жыл бұрын
youtube just read my mind... I wanted to continue learning Rust but also do some assembly programming for fun. This is exactly what I needed, thanks :D
@chrishayuk
@chrishayuk Жыл бұрын
glad it helped. i plan to do an assembly tutorial at some point.
@YourMom-rg5jk
@YourMom-rg5jk Жыл бұрын
fr!
@falcon20243
@falcon20243 Жыл бұрын
Loving your content Chris. Keep it up.
@chrishayuk
@chrishayuk Жыл бұрын
thank you
@cd-stephen
@cd-stephen 11 ай бұрын
just awesome - learned more about assembly then anywhere else
@chrishayuk
@chrishayuk 11 ай бұрын
thank you, glad it's useful. i enjoy showing assembly as it really shows what's going on under the hood
@_realist_6957
@_realist_6957 Жыл бұрын
Chris you are a legend man
@chrishayuk
@chrishayuk Жыл бұрын
thank you :) , glad you're enjoying the vids
@ricardorosa5315
@ricardorosa5315 Жыл бұрын
This is amazing!!!! And so well explained! Subscribed instantly 💪
@chrishayuk
@chrishayuk Жыл бұрын
Awesome, thank you!
@DavidEngelen
@DavidEngelen Жыл бұрын
Love the (Rust) vids keep it up!
@chrishayuk
@chrishayuk Жыл бұрын
glad you like :) , more rust vids coming. i promise
@proudmoroccan8164
@proudmoroccan8164 Жыл бұрын
Thank you for sharing. Greetings from Morocco.
@chrishayuk
@chrishayuk Жыл бұрын
you're welcome and hello morocco :)
@krome305
@krome305 Жыл бұрын
Thanks for this content Chris!
@chrishayuk
@chrishayuk Жыл бұрын
you're welcome
@ntippy
@ntippy Жыл бұрын
Well done, more high level programmers need to know how this works. Not that they should write assembly but it turns our that the way you write a function greatly empowers or limits what the compiler can do with it. Favor immutable choices every opportunity you get.
@chrishayuk
@chrishayuk Жыл бұрын
thank you, glad you enjoyed and agreed, it's always good to understand underneath the hood
@stevenreina5774
@stevenreina5774 Жыл бұрын
Great video!!
@chrishayuk
@chrishayuk Жыл бұрын
thanks, glad you enjoyed :)
@romandzhadan5546
@romandzhadan5546 Жыл бұрын
great explanation
@chrishayuk
@chrishayuk Жыл бұрын
Thank you
@sanket1729
@sanket1729 Жыл бұрын
Thanks for the video. I would expect everything to be similar for c++. Did not understand how the rust specific things like borrow checker helped in the compilation.
@chrishayuk
@chrishayuk Жыл бұрын
i will cover ownership and borrrow checking in a future vid
@EudaderurScheiss
@EudaderurScheiss Жыл бұрын
very cool, did some assembly years ago. what maybe is more interesting is how rust does the panicking. does every imul / add have its own panicking jump block defined? i guess the reason is to find the error line later on? it be cool to see the same code compiled with c/c++/rust
@chrishayuk
@chrishayuk Жыл бұрын
awesome glad you like. yeah had a similar thought about comparing with C/C++ will try and do that soon
@CryZe92
@CryZe92 Жыл бұрын
Also keep in mind that this assembly here was "without optimizations" (except a few the compiler snuck in anyway). So a release build would look very different.
@chrishayuk
@chrishayuk Жыл бұрын
@@CryZe92 yes release builds look quite different.. but you can't really teach how rust is working under the hood with a release build as it's heavily optimized.
@dyslexicsteak897
@dyslexicsteak897 Жыл бұрын
yes there are many runtime checks that occur only in debug mode
@SandwichMitGurke
@SandwichMitGurke Жыл бұрын
@@chrishayuk just out of curiosity I checked the assembly code with release target. I did not expect what I saw. The compiler calculated everything on it's own and stored the number 600 directly onto the stack. 600 is result3, which means the compiler itself calculated 10*20*2 + 200. It removed all other variables entirely. Impressive
@schoudhary108
@schoudhary108 Жыл бұрын
lovely 👍
@chrishayuk
@chrishayuk Жыл бұрын
Thank you 😊
@alexon2010
@alexon2010 Жыл бұрын
Very cool your video about Rust, I don't know anything about Rust but I want to learn, I could create a video on how to use Rust with Arduino and ESP32
@chrishayuk
@chrishayuk Жыл бұрын
please do
@uilleachan
@uilleachan Жыл бұрын
"Gubbins", lol. Scottish roots on show there!
@chrishayuk
@chrishayuk Жыл бұрын
hahaha, you caught me, i'm scottish through and through
@EnderMega
@EnderMega Жыл бұрын
Im not a Rust programmer, Im a C/C++ programmer, but this video was really cool. My hate with other languages is that people use the lazy argument _"The compiler does that for me..."_ or _"The compiler is smarter than you!"_ . I dont think any machine is smarten then humans, we made then, we're better than them. Plus, knowing what you program is actually doing is great for debuging and other stuf. That was a greate video my man ;) .
@taragnor
@taragnor Жыл бұрын
The compiler isn't smarter, but it is ultimately way better at not making careless mistakes.
@EnderMega
@EnderMega Жыл бұрын
@@taragnor that still not a excuse to not know what is happening behind the hood
@chrishayuk
@chrishayuk Жыл бұрын
i agree, i like know what's under the hood also. thanks for the kind comments. compilers are just a natural evolution of automation. we see it today with transpilation in high-level languages also
@ahmadumar6210
@ahmadumar6210 Жыл бұрын
@Chris nice video, do you give courses in rust with projects?
@chrishayuk
@chrishayuk Жыл бұрын
ah no, sorry, this is really just about sharing thoughts.
@nark4837
@nark4837 Жыл бұрын
Enjoying your videos! Chris, where is your accent from? I feel like I hear a bit of Scottish, English, American, I'm assuming you have lived in many places in your life? 😃
@chrishayuk
@chrishayuk Жыл бұрын
I am very much Scottish but living in England and I certainly move around the world. Throw in Irish as well as American and you've got my accent nailed. Glad you're enjoying the vids
@nark4837
@nark4837 Жыл бұрын
@@chrishayuk Ah cool, knew it was a mixed accent! By the way, just a few things I noticed when watching the video yesterday, 'al', not 'a1' is actually the lower 8-bits of the ax/eax/rax register. I love the way how Rust handles runtime errors though, only miniscule difference in performance compared to C in exchange for programs that handle things properly! Also, it is quite strange how it optimises 20 * 10 to 200 only once in the generated assembly, when it could have optimised it everywhere imul was used.
@chrishayuk
@chrishayuk Жыл бұрын
@@nark4837 my intel assembly sucks. i will do a tutorial vid on it soon. mainly to educate myself
@leave-a-comment-at-the-door
@leave-a-comment-at-the-door Жыл бұрын
Where did you get your code completion? it looks really useful
@chrishayuk
@chrishayuk Жыл бұрын
GitHub copilot
@leave-a-comment-at-the-door
@leave-a-comment-at-the-door Жыл бұрын
@@chrishayuk thanks!
@nikitablack1568
@nikitablack1568 Жыл бұрын
Thanks for sharing! I have a question - your autocompletion looks like magic when it suggests the entire line based on a comment or something else. Is this a VSCode plugin?
@theninjascientist689
@theninjascientist689 Жыл бұрын
I'm assuming it's GitHub copilot, which is a paid extension based on OpenAI's ChatGPT
@rizkiaprita
@rizkiaprita Жыл бұрын
@@theninjascientist689 github copilot is based on char gpt??? 🤯
@SandwichMitGurke
@SandwichMitGurke Жыл бұрын
21:10 What's the point of storing eax on the stack, then doing nothing with eax and loading the value from the stack into eax again? Seems not efficient at all to me? I mean yes, we wrote let result1 ... which we want to store on the stack, but shouldn't the compiler optimize this? Am I missing something?
@chrishayuk
@chrishayuk Жыл бұрын
it will optimize on release bui;d. will deep dive this more
@amanueltigistu8268
@amanueltigistu8268 Жыл бұрын
Thanks for your Awesome Contents. What do you think about Zig Programming Language? I need to see zig Web Server Performance Tests. I think it's going to be cool 😎.
@chrishayuk
@chrishayuk Жыл бұрын
i have a lot of thoughts on this.. tutorial coming soon. if you look at some of my bun videos in the mean time you'll get an idea of zig web performance. it's fast
@amanueltigistu8268
@amanueltigistu8268 Жыл бұрын
about 2 weeks, I have tried to learn Zig & I found Zig very much fun & easy to work with. Zig explicit memory management is Really Great, you might mis manager memory, but you can test it right away. Also Zig's WebAssembly & WASI Integration is Really Awesome.
@chrishayuk
@chrishayuk Жыл бұрын
@@amanueltigistu8268 actually i was playing with Zig's webassembly the other night. i quite liked it. i didn't check the underlying wat from wasm, to see if i liked what was generated but it looked promising
@amanueltigistu8268
@amanueltigistu8268 Жыл бұрын
@@chrishayuk I can't wait to see the tutorial Video for Zig. I think it's going to be very much cool. Thanks.
@guilherme5094
@guilherme5094 Жыл бұрын
👍
@anfitanin
@anfitanin Жыл бұрын
I'm sorry but I do not get one thing: why there is always diffrence of byte in stack of 4? Shouldn't 4 bites be able to represent up to 15? sorry for so base level question...
@coolkats9331
@coolkats9331 Жыл бұрын
I just installed rust recently but not started practicing. Still Learning Java(just started)
@chrishayuk
@chrishayuk Жыл бұрын
learn multiple languages, it gets easier
@hezuikn
@hezuikn Жыл бұрын
pretty
@leyasep5919
@leyasep5919 Жыл бұрын
0:50 : the mixing of music is *bad*, it shouldn't be so loud 😕
@chrishayuk
@chrishayuk Жыл бұрын
agreed, fixed for new vids
@eliavrad2845
@eliavrad2845 Жыл бұрын
I don't understand the optimization: why does it mov eax to rsp+32, check overflow, and then mov rsp+32 back to eax, which still has the value? why does it do half the calculation to get to 400, but then optimize adding 200: if it is willing to call ahead that result1=200, why isn't it doing 2*200+200, or just straight up optimize everything to 600?
@alphaanar2651
@alphaanar2651 Жыл бұрын
The code was compiled in debug mode, meaning that you will see unoptimized code and some strange things. Any decent compiler for any good language would just replace all that stuff with loading constant 600 if you compile it in release mode and enable optimizations.
@sudeshryan8707
@sudeshryan8707 Жыл бұрын
To 1st part of question : Bcoz of **seto al**. He misunderstood AL register (lowest byte of eax) as a1 register (theres no such in x86). Seto al will set al register with overflow bit, hence eax no longer has original result of calculation. After checking overflow then mov eax, rsp+32 will fetch original result back. 2nd part: I think bcoz calculation results are stored in 3 variables, compiler need to calculate in steps so it can save the results to rsp+32 & rsp+28 etc.. Or may be there is a flag for further optimisations we can set.
@markjans2169
@markjans2169 Жыл бұрын
This compiles via LLVM to assembly I guess. Probably LLVM also does some optimizations, even in debug mode.
@SandwichMitGurke
@SandwichMitGurke Жыл бұрын
@@alphaanar2651 does the C compiler also just replace it with 600? I'm just curious. Recognizing that all those variables can be eliminated is quite impressing imo
@jackgerberuae
@jackgerberuae Жыл бұрын
@@sudeshryan8707 according to comments, once you compile to implementation, the compiler throws out all variables and stores only the final result. It is done this way because of debug mode only
@rizkiaprita
@rizkiaprita Жыл бұрын
i dont write rust or assembly. why am i watching this 😂. very good explanation tho
@chrishayuk
@chrishayuk Жыл бұрын
it's always fun to learn new stuff, will improve how you approach your existing languages. glad you enjoyed it
@victorpaulo4342
@victorpaulo4342 Жыл бұрын
i have the sa issue..
@porterrucki5479
@porterrucki5479 Жыл бұрын
How's it going? Did you learn how to use it?
@chrishayuk
@chrishayuk Жыл бұрын
reverse engineering
@cmilkau
@cmilkau Жыл бұрын
I'm actually surprised it didn't just mov eax, 600.
@DeusGladiorum
@DeusGladiorum Жыл бұрын
It does if you turn on compiler optimization, which is off by default. Add "-C opt-level=1". Works on Godbolt.
@qscuio
@qscuio 10 ай бұрын
The color is really strange.
@chrishayuk
@chrishayuk 10 ай бұрын
I like to experiment, I’m partial to the smurf / avatar vibe
@jammy3662
@jammy3662 Жыл бұрын
that intro is WAY too loud
@chrishayuk
@chrishayuk Жыл бұрын
yeah. sorry. i've ditched the intro for my latest video. will see how that compares and will rethink
@jammy3662
@jammy3662 Жыл бұрын
@@chrishayuk thanks for being open to feedback!
@chrishayuk
@chrishayuk Жыл бұрын
@@jammy3662 no worries.. i don't wanna annoy people.. had that feedback a few times. and i don't think it's a necessary component. would rather people enjoyed the content. will be interesting to see how it effects the first 30 second drop off numbers
@IleniaQuintero
@IleniaQuintero 27 күн бұрын
Hello, I was looking at your video channel. We may be helping a company that uses secure images to increase supply chain security and help cloud native development. Would you be willing to help try their software, make a video, and help show devs how to use their tools? This is not an offer, but just to start a conversation about your willingness to take on sponsorship. Please provide me with your email if you are interested. You'd have a chance to look at their technology and decide if it's the type of software that you'd be interested in covering in your channel.
@chrishayuk
@chrishayuk 27 күн бұрын
hey thanks for the reach out, but sponsorship isn't really a direction i'm going in, but appreciate the thought
Rust Before Main - Ryan Levick - Rust Linz, July 2022
31:34
ИРИНА КАЙРАТОВНА - АЙДАХАР (БЕКА) [MV]
02:51
ГОСТ ENTERTAINMENT
Рет қаралды 1,4 МЛН
🍕Пиццерия FNAF в реальной жизни #shorts
00:41
Balloon Stepping Challenge: Barry Policeman Vs  Herobrine and His Friends
00:28
When Zig Outshines Rust | Prime Reacts
23:31
ThePrimeTime
Рет қаралды 133 М.
C++ vs Rust: which is faster?
21:15
fasterthanlime
Рет қаралды 376 М.
Why does this Rust program leak memory?
35:24
fasterthanlime
Рет қаралды 56 М.
All Rust features explained
21:30
Let's Get Rusty
Рет қаралды 284 М.
Golang vs. Rust: Which is Better?
12:40
Code With Ryan
Рет қаралды 122 М.
SQLx is my favorite PostgreSQL driver to use with Rust.
9:47
Dreams of Code
Рет қаралды 47 М.
The Truth about Rust/WebAssembly Performance
29:47
Greg Johnston
Рет қаралды 171 М.
Rust, Modern Solutions to Modern Problems
9:19
Code Persist
Рет қаралды 53 М.
Rust vs C++
7:18
conaticus
Рет қаралды 56 М.
Rust Demystified 🪄 Simplifying The Toughest Parts
14:05
Code to the Moon
Рет қаралды 170 М.
ВЫ ЧЕ СДЕЛАЛИ С iOS 18?
22:40
Overtake lab
Рет қаралды 120 М.
WWDC 2024 - June 10 | Apple
1:43:37
Apple
Рет қаралды 10 МЛН
keren sih #iphone #apple
0:16
kadangaruan
Рет қаралды 1,7 МЛН
Жёсткий тест чехла Spigen Classic C1
0:56
Romancev768
Рет қаралды 720 М.