Thursday, January 26, 2012

Assembly the code explanation

For my next post in my saga about assembly I'm gonna explain my source code in my first post.

As you may be aware from my last post that CPU's only execute basic instructions like move x variable to y.
Now we can group them into a segment. As we are dealing with 32bit protected mode CPU's not 16bit we can assume not all of 1 will be in memory however we divide them up into pages which have a max size of 4kb.

There is 3 types you should really care about, .text, .data and .bss.
Each segment has a unique purpose.
The .text contains the functions.
The .data contains the initialized variables.
The .bss contains the uninitiated variables.
This is merely classical naming but its allways good to stick to widely accepted standards.

For functions on windows and you wish to interface with c/c++ then you must prepend all global variables and functions with a _ on Linux you need not do it.

The global label in start.asm turns the start function from a local function (only functions from that file can access it) aka private for those who know an OOP language, to an external function aka a public function for those who know an OOP language.

The _start: (for Windows) in start.asm declares a function.
We use the start function as the entry function which was set in build.sh.

The first 3 lines of shell code in build.sh contains command to clean up our directories.
Basically deletes all the compiled objects from last compilation.

Next in source directory we compile the start.asm to a library file of with extension of .o but not linked as an executable.
For those that have read a bit and realised but heyy -f elf turns it into a linux library! but I'm on windows, it could never work..
Well your wrong, remember Cygwin? well guess what, it contains a library that that it was compiled against thanks to nasm from Cygwin.
So it is a valid windows library file and this will still work fine on linux as type elf is for linux.

We move the library created by nasm to the object dir which we first cleaned up.
We link the library (start.o) as a new executable called blog_first.
Now you may notice that blog_first has no extension and you can't double click it to run it in Windows Explorer.
That is okay, we don't need to!
In Linux binary files like this don't have an extension. So thanks to this being a bash command line interface we can just run it with ./blog_first.
This is done all in build.sh so you don't have to handle it yourself.

Thanks for reading, hope this helps get somebody off the rocky ground you may be in for assembly!

No comments:

Post a Comment