Friday, November 25, 2016

Introduction to assembly x86 for Linux - Hello world

Introduction to Assembly

Assembly language is considered the closest language to the hardware nowadays, You can write any software using assembly. Also, You can almost write the same software without a single line of assembly.

Then why people stay learn assembly !

There is some tasks that assembly cane done them better than any other language like Bootloaders and low-level kernel functions . It also used within high level language code to optimize its performance.

Assembly is not used in programming only, nowadays it mostly used in debugging.

How it works?

Assembly language is based on instructions those are provided by the CPU, not statements like the rest of languages

Each processors family has their own instructions set, so you cant execute ARM assembly code on Intel processor or 64-bit assembly code on 16-bit processor.

To know if your PC will match the code i will write, type this command in the terminal

uname -i

If your output is x86_64 then you are ready to follow me.


Requirements : 

nasm - type sudo apt-get install nasm to install it.
ld linker - Its already installed by default.
Any text editor

Hello World

I will assume you are know what is a register and know a little bit about assembly.
I will talk about this basics later on my youtube channel, its easier to talk rather than typing :D

The code is below, discussed and explained in the comments.

Wait, i assumed you know about registers and basics of assembly so its silly to write a simple code to print Hello world and exit, i will make it advanced a little bit and i will write a sub routine to print out the message.


;Data section.
;All our variables should be declared here.

section .data
    msg: db "Hello, World!",10,0

;Text section.
;Deal it as if its name is code section. i think its clear now
;our code goes here

section .text
    global _start ;This is so important to the linker to tell it where is out main entry

_start:

;Skip this for now, scroll down and read the sub routine code and ;then back here
    mov rax, str  ;store our string offset in rax
    call echo     ;call our function

    
    mov rax, 60
    mov rdi, 0
    syscall     ;rax=60, rdi=0 will perform a clean close


;input = string offset in rax.
;output = printed string.
echo: ;if you are familar with any high level language so deal this ;label as a function name
    push rax    ;push the value stored in RAX into the stack cuz we     ;need it
    ;the value that will be pushed is the string offset, we need it     ;so we will save it to the stack 
    mov rbx, 0  ;We need to count the letters in our word
    ;so we will set rbx to zero and we will compare each byte (char)     ;in our string 
    ;with 0 and if its not 0 then increase rbx by one
    
print:
    inc rax   ;increase rax by 1 to get the first character ot our       ;string
    inc rbx   ; increase rbx, the counter
    mov cl, [rax] ;save a byte from rax to cl, thats why we are         ;increasing rax, 
    ;to get diffrent char everytime we loop
    cmp cl, 0   ;is this byte = 0?
    jne print   ;if its not zero that means we still have chars to       ;count, loop again
    ;if its zero then the following block will be executed
    
mov rax, 1    
mov rdi, 1
pop rsi        ;the offset of our string is saved in the stack, we                  ;will pop it to rsi
mov rdx, rbx  ;rbx should contain the lenght of our string which is               ;the value in rbx
syscall       ;call the kernel

ret           ;return to where we called the routine

Thursday, September 22, 2016

Dynamic memory allocating errors handling

Sometimes you are not aware in advance how much memory you will need store some information, like a string entered by a user. You can declare a variable that is large enough to store any expected data but its a waste of memory, the alternative way to do this is to allocate the memory at runtime and use the Dynamic memory allocation concept.
Unlike the memory the created at compile time, The memory declared at runtime allocated in the heap which is unused memory that allows the applications to allocate memory at runtime

As you know, the computer resources are limited and dynamic memory allocation may fail if there is no enough free memory in the heap to allocate the memory you want.
C++ provides you with 2 ways to check if the allocation succeeded or not.

The first one is by handling exceptions. When memory allocation fails, bad_alloc exception is thrown and handling this exception with the proper handler will prevent your application from termination.

The second one is to use nothrow object while creating the pointer. Using this way, there is no exceptions will be thrown and you the pointer will be returned with the value of nullptr and by checking the value of the pointer you know if the allocation process succeeded or not.

Example :

int *x = (nothrow) new x[5];

if (x==nullptr)
{
//do something
}

Tuesday, August 23, 2016

How to call a function before the main function and after 'return 0' line

Some applications needs to call a function before the main function takes the control for loading a specific value form somewhere or after the program dies for saving settings or something like that but, how?

Its very simple.

__attribute__

This peace of code has two options or two parameters to pass.
If constructor is passed, the function will be executed before the main function.
Unlike, if destructor is passed, the function will be executed after int main returns 0

Examples :


1- Executing before main function


#include iostream
using namespace std;

void beforemain(void)__attribute__((constructor));

void beforemain(void)
  {
     cout<<"hi befor main\n";
  }
           
int main()
  {
      cout<<"main\n";
      return 0;
  }


2- Executing after closing the program


#include iostream
using namespace std;

void aftermain(void)__attribute__((destructor));

void aftermain(void)
   {
        cout<<"bye after main\n";
   }
          
int main()
   {
        cout<<"main\n";
        return 0;
    }

Pretty easy and straightforward, right !

Friday, August 12, 2016

Introduction to computer programming

Before getting to computer programming, lets first understand computer programs and what they do.

A computer program is a sequence of instructions written using a programming language and converted to the machine language to do a specific task.

You can consider that a programming language converts your logic into the computer logic
If somebody asks you how to login to facebook your answer will be like : 

 Open facebook, create account then login

Now, try to arrange your answer in sequence and you will get :

 1 - Open facebook
 2 - Create account  
 3 - Login

Actually, you can consider this sequence as a computer program written in your original language.

Now, lets talk about programming again. A computer program is a sequence of instruction tells the computer what to do.
For example, This C code tells the computer to prints "Hello World!" on the screen.

printf("Hello Wordl!");

Introduction to computer programming.

If you understood what a computer program is then you will answer yourself "Writing a computer program is computer programming"
You are right, but how. As we mentioned, the computer can't understand what you say and you have to convert your instructions that You need him to do into machine language.
For this purpose, the computer programming languages are invented.
There are many programming languages such as
  • Assembly
  • C
  • C++
  • Java
  • Python
  • C#
  • Perl
  • VB.NET
And many more.

This is just an introduction to the world of programming, other guides on how to be a programmer will be posted soon.