The Firsts…

We, the humans, are always prone to stay away from something that we ‘think’ to be not reachable. But have we ever thought of what makes us stand away from it? Most often the answer is a big NO! We are always worried about the consequences. We keep on stuffing our mind with questions like “What if we fail? What will others think about me?”. But have you ever thought of what if you win? Take a minute from your life for this.

Which is the biggest animal on land? Of course, it’s the elephant. It’s stronger enough to crush everything that comes in front of it. But then why is lion the King of the Jungle and not elephant? Ever thought about this? If no, spare another minute from your life for this. The elephant is really strong that it can break any chains. But it’s with the same chain we control it. They ‘think’ that they cannot move. And they have ‘never tried‘. It’s the same with humans too. We will get to know more about our strengths if and only if we ‘try’ doing different things.

When we meet a person for the first time in our life, we rarely talk to him/her until and unless necessity calls. We start liking a person, once we get to know more about him/her. So the basic step for the process of ‘liking’ was just to talk to that person. So the ‘first step’ matters. Being an engineering student let me talk from a student’s perspective. Often we hear students saying, “This subject is really tough” or “I hate this subject”. Imagine your enemy subject to be a person. To get close to him what you have to do? Talk to him! May not be to the book, it may be a little weird :p So, all you have to do is try to understand the subject with all your heart. The more you know, the more you fall in love. Start doing it, rather than waiting for an auspicious ‘next day’ for a start.

In all aspects of life, it’s just the matter of the firsts. Fear is actually a dilemma when we are not clear about what our next step should be. But to take the next step, we must have the first step. Just forget every other thing in your life and step out from the cage. Dare to take risks. Because, it’s from the falls we learn how to walk. Forget what others will think about you and decide your destiny.

Advertisements

Say “Hello, World!” in assembly language.

Programming in assembly language has always been a big deal. So here is a simple guide to assembly programming. To know more about x86 assembly and its environment setup check out my blog post on x86 assembly.

Program Structure

An assembly program basically consists of the following parts, .data, .bss and .text, where the .data deals with the initialized variables, the .bss part deals with the uninitialized part and the .txt deals with the code.

An assembly program marks its start with the ‘_start:‘ like in a c program the main function marks its start.

Apart from the other programming languages we use, we have to code for most of the actions that we perform, which makes assembly programming to a bit confusing, as it deals more with its processor architecture.

Lets code our first assembly program, the Hello, World!

section	.text
   global _start     ;must be declared for linker (ld)

_start:	            ;tells linker entry point
   mov	edx,len     ;message length
   mov	ecx,msg     ;message to write
   mov	ebx,1       ;file descriptor (stdout)
   mov	eax,4       ;system call number (sys_write)
   int	0x80        ;call kernel

   mov	eax,1       ;system call number (sys_exit)
   int	0x80        ;call kernel

section	.data
msg db 'Hello, world!', 0xa  ;string to be printed
len equ $ - msg     ;length of the string

Now we will look into each of the statements and keywords used in the above program.

;‘ is used to comment.

section .text : to denote that to be the starting of the code.

global _start : global directive is NASM specific. It is for exporting symbols in your code to where it points in the object code generated. Here you mark _start symbol global so its name is added in the object code ( a.o ). When you run the executable it starts at where marked as _start in the code.

_start : like main function in a c program it marks the start of the program.

mov edx, len : length of the string to be printed is moved to the edx register.

mov ecx, msg : the string to be printed is moved to the ecx register.

ecx and edx register, as per _fastcall convention, is used to store the first two arguments of the function generally.

mov ebx, 1 : the number specifies the respective file descriptor, where it is 0 for stdin, 1 for stdout and 2 for stderr.

mov eax, 4 : this number is the syscall number for write function.

int 0x80 : it is the interrupt given to invoke the kernel(int = interrupt, 0x80 = interrupt number).

mov eax, 1 : syscall number for exit.

section .data : section where the initialized variables are declared.

msg db ‘Hello, world!’, 0xa : db stands for define byte which allocate 1 byte, where 0xa is the linefeed character here and 0xa is the ascii value for a new line(\n).

  • db : define byte : 1 byte
  • dw : define word : 2 bytes
  • dd : define doubleword : 4 bytes
  • dq : define quadword : 8 bytes
  • dt : define ten bytes : 10 bytes

len equ $ – msg : ‘$’ means the current address of the assembler. So current address($) minus the address of the string(msg) gives the length of the string.

This is how a simple Hello, World program in assembly language look like. Once you are familiar with the architecture and the instruction set for which you are gonna program, assembly programming is not a big deal. Hope this helped you.

Happy coding 🙂

How to start with GDB..?

GDB(GNU Project Debugger) is a debugger, which is a program that runs other programs to help us know actually what happens while the program is executed. GDB is one of the most commonly used debugger for UNIX systems. All you need to have is a basic idea of x86 architecture and assembly programming. You may head into my page on x86 assembly for this.

Basically, GDB helps us identify the following issues:

a) When the core is dumped, the GDB helps us identify which line caused the crash.

b) If an error occurs while executing a function, which line calls the statement and the parameters can be identified.

c) The values of the variables at a particular point of execution can be identified.

d) The result of a particular expression in the program can be identified.

I am using GDB-peda for this. To install GDB-peda in your Linux system, type the following commands in your terminal.

To install the libraries, follow the command:

sudo apt-get install libncurses5-dev

Now download the repository from github.

git clone https://github.com/longld/peda.git ~/peda
echo “source ~/peda/peda.py” >> ~/.gdbinit 

The second command is to get direct access to GDB-peda while opening the debugger.

Once we have our GDB-peda installed, we can start debugging our programs.

To get the debugging information while compiling, add the GDB flag ( -g) to it.

gcc -g -o filename filename.c

Now to start GDB, simply type:

gdb filename

To get the entire list of functions, type

info functions

Now we will go through some of the basic commands to use GDB-peda

pd <function> : to print the disasembly of the specified function


b *(function/address) : to set a breakpoint at the specified function or address


r : to run the program till the breakpoint or end


ni : single step without descending into any functions i.e., if encounters a function executes the entire function in a single step


si : single step to descend into the functions


help (h) : to get help on gdb commands


c (continue) : continue till the next breakpoint or end


delete : to delete all breakpoints or the specified one


print <$register/address/variable> : to print the value at the specified address or variable


.x/s <$register/address> : to print the string at the given address [s in the above command can be replaced with x (hex), wx (integer) as preferred]

You can also use the GDB commands for the same. Some of the GDB commands are:

disas main – to get the assembly code for the main function

set disassembly-flavor intel – to convert disassembly to more user friendly format

b main – Puts a breakpoint at the beginning of the program

b – Puts a breakpoint at the current line

b N – Puts a breakpoint at line N

b +N – Puts a breakpoint N lines down from the current line

b fn – Puts a breakpoint at the beginning of function “fn”

d N – Deletes breakpoint number N

info break – list breakpoints

r – Runs the program until a breakpoint or error

c – Continues running the program until the next breakpoint or error

f – Runs until the current function is finished

s – Runs the next line of the program

s N – Runs the next N lines of the program

n – Like s, but it does not step into functions

u N – Runs until you get N lines in front of the current line

p var – Prints the current value of the variable “var”

bt – Prints a stack trace

u – Goes up a level in the stack

d – Goes down a level in the stack

q – Quits gdb

Now you can interpret your programs using the GDB and start debugging.

x86 Assembly

Programming allows a person to represent machine language in human-readable format. Then why do we need assembly programming? What is actually assembly programming?

Assembly language is the low level programming language understood by a microprocessor or other programmable devices. Whatever instructions we give in a high level program will not be understood by the computer as such. It should be converted to a language that can be understood by the computer, called the binary. Assembly programming is mainly used for direct hardware manipulation, access to specialized processor instructions, or to address critical performance issues as it is specific for the computer architecture or the processor type. Hence many types. X86, MIPS, ARM etc are some examples.

Assembler is a software that converts the low level language to machine code. For example, NASM(Netwide Assembler), TASM(Turbo Assembler) etc.

Considering the example,

int main() {
   int a, b, result;
   result = a + b;
}

The computer cannot understand the instructions given above as such. It will understand if and only if converted to binary. After all, for a computer everything is binary. Everything, from letters to windows. Everything that we see or processed are binary. So there is a need to convert the above code to binary. Binary is really difficult for a human beings to handle. So we make use of an intermediate level, which is the assembly language, where we write code on behalf of the computer architecture. That is, we code on behalf of what really happens when we give the command to add two numbers. Hence we get a clear idea about how the above code is actually processed in low level.

For this I am making use of the assembler NASM. To install NASM open your terminal and type:

sudo apt-get install nasm

Since assembly is more related to the processor, we have to have some idea on the common terms related to processor. Here we will be dealing with Intel syntax of assembly(32 bit).

Registers    

They are temporary data storage areas in a processor where single value can be stored. Data processing in a register is faster and efficient as it is of small size. They are mainly of two types: General Purpose Registers(GPRs) and Special Purpose Registers(SPRs).

There are 8 General Purpose Registers in X86 architecture.

eax

Mainly two purposes: to store the return value of a function and for certain calculations as special registers. Technically volatile. Most important register after esp.

Returning in c language:

return 3;

The same code becomes more into form of registers when written in assembly.

mov eax, 3;   //Set eax to 3(returning value)
ret;         //Return

ebx

Doesn’t have any special use but the value will be set often to any of the commonly used values(such as 0) to speed up calculations. It is non volatile.

ecx

It is used as a function parameter or a loop counter. As per the “_fastcall” convention, the first two arguments of the function are to be passed to the ecx and edx. Also whenever a member function of a class is called, a pointer to the class is passed to ecx.Another function is while using a loop. The accumulator variable is often set to ecx which then decrements to 0. It is volatile.

edx

Besides _fastcall, edx is used for storing short term variables in a function. It is volatile.

esi

It is often used as a pointer especially for rep-class instructions where a source and destination is required, esi points to the source. It is non volatile hence often stores a data which is required throughout the function.

edi

Similar to esi, but used as destination register.

ebp

For a non optimized compilation, ebp acts as a frame pointer i.e., it keeps tracks where the stack is at the beginning of the function(start/base of the stack). So that the values stored in the stack can be easily referenced even if the stack changes throughout the function. It is non volatile.

esp

Points to the top(current position) of the stack as the stack grows downwards from high memory to low memory. When a word value is pushed onto the stack, the assembler decreases the esp by 2. It is non volatile.

Common Special Purpose Registers are the PC(Program Counter, points to the next instruction to be fetched), IR(Instruction Register, points to the currently active instruction) and SR(Status Register, stores basic state of the processor).

eip, is an example for PC

The volatile and non volatile registers are also known as caller-saved and callee-saved registers respectively.

There are three parts for an assembly program: text section, data section and bss section.

Text section stores the instruction or code. Data section stores initialized variables while bss section stores uninitialized variables.

Stack

Stack is a linear data structure that follows the principle of LIFO(Last In First Out) i.e., the element inserted last will be the element removed first. A stack grows downwards from higher address to lower address.

Stack Frame

A stack frame will be created every time a function is called. All the data for the function will be saved within the stack along with the return address.Return address or the saved EIP is the address executed right after the end of the function. This frame is called a stack frame.

section .text                 ;stores instructions
 global main
      main:
      
      push ebp                 ;function prologue            
      mov ebp, esp            

      mov eax, 0xa             ;moves 10 into eax register
      mov ebx, 0x100           ; moves 256 into ebx register

      add eax, ebx             ;adds up the value present in both theregisters and stores the result in eax

     
      mov esp, ebp              ;function epilogues
      pop ebp                 
      ret                  

“;” is used to comment

Function prologue: It does everything for the function to begin. It creates the stack frame of the callee function by saving the base pointer of the previous function(saved EBP) and then setting up the new base pointer at the current location of the stack.

push ebp                  ;saves the value of ebp of callee function
mov ebp, esp              ;sets the ebp of caller funciton

Function epilogue: Cleans up the stack frame just before the function is done and returns to the caller function by popping ebp.

mov esp, ebp               ;destroys the stack frame as esp again points to ebp
pop ebp                    ;restores the stack frame of caller function
ret                        ;sets saved eip as the next instruction to be executed

Commands to assemble the code:

nasm -f elf32 filename.asm (converts into an object file named filename.o)

ld -o filename filename.o (link the object file NASM produced into an executable file)

To run,

./filename

Command to install 32 bit libraries:

sudo apt-get install lib32z1

What everyone actually needs

Life is like a see-saw. It has ups and downs. If you are able to remain happy even after a big knock down, then you are awesome! Seriously. We humans actually don’t know how powerful we are. We just go after things that are out of our reach. I am not saying,  always get satisfied with what we have. But decide a limit for everything and happiness will follow you like your best friend. Wherever you go he will be with you.

Have you ever felt like falling, in your dream? Have you ever thought about what it is actually? Take a second to think about that. It happens when there occurs an interruption for the message transmission via cerebral hemispheres. Wow! Have you ever thought like that? Now take another question. How do these interruptions occur? This question can be answered through a small thought process. What are these messages actually? They are impulses. What are these impulses? They are electric signals! Can you even imagine electric impulses passing through our body?  Everyone is a fan of a super hero. But nobody really knows he himself is a Superman.

There are several claimed techniques of physic powers. Haven,t you seen people moving things with their looks, at least in movies. This, which is known as psychokinesis, is a proven thing. If they can do all these so-called super stuff, can’t we be happy at least? I don’t think it’s a big deal. Better way for that is to find good in everything. That may not be as easy as I said. But still can’t we ignore our nature of finding negatives in everything? It really works. Whatever happens to you, let it be big or small, crying for it doesn’t really help you. Just like an exercise, practice it in your life and you will really feel that freshness.

The final result that every human being wishes to have, be it rich or poor,  ordinary or the extra, is happiness. No matter what they are doing. Some find happiness in smuggling though. Their ultimate aim is to find happiness. If we can find happiness in small things, what should we wait for. Just take a deep breath and move on.

Arduino and Raspberry Pi : a comparison

arduino-pi

It hasn’t been too long since the Internet of things bloomed to the world of technology. Since then the impact that Internet of Things, in short IoT, has created is immense. From the health updates of the cattle to the single tap to switch on the lights.

The term Internet of Things may seem to be very complicated and may appear like a 200 pounds Great Dane scowling at you. But it is as sweet as a Beagle, once you get to know more about it.

arduino rasp

IoT is now one of the prominent fields that school students prefer for exhibitions and projects. Are you wondering, “What kids?!”

Haven’t you heard them saying , “Mommy, I made a supersystem that automatically waters the plants!”. How did they manage to do all these so-called super things at this age? But didn’t see anything that large, like a computer. Did they use some super stuff for that?

Yeah, they do! A credit card sized mini computer. “Wait, what? A credit card sized!!? ”

Exactly! This is where the Arduino and Raspberry Pi becomes important.

Both are different. Arduino is a microcontroller board while Raspberry Pi is a mini-computer that has SoC (System of Chips) embedded in it.

Let’s look upon them in detail.

THE ARDUINO

arduino_blink-slow
Image showing Arduino UNO

Arduino is an open source electronic platform that has a microcontroller which is a part of a computer. With an Arduino board, we can even write a Twitter message. Once we check the ‘Products’ page on the Arduino website we can see the different models of Arduino available. Arduino boards are relatively cheap. Here we will be focusing on Arduino UNO which is based on ATmega328. Inside the board, there is 2K of RAM, 32K of flash memory, some timers and hardware that deals with serial communication protocols, I2C  and SPI. To know more about the communication protocols click here. Apart from all these, the board also includes voltage regulators, passive components and I/O connectors.

The board has 14 digital input/output pins among which 6 can be used as PWM( Pulse Width Modulation, is a technique for getting analog results with digital means) outputs. At the bottom right corner, we can find the 6 analog inputs. The board also has a 16 MHz ceramic resonator, a USB connection, a power jack, an ICSP header and a reset button.

fcgoseritaoi7of-large
Parts of Arduino UNO

a_16mhz_ceramic_resonatorThe ceramic resonator is used to generate the clock signal used to control timing.

arduinounor3ispconnectorICSP or In – Circuit Serial Programming, is a protocol used to program microcontrollers.

Arduino only runs one program again and again that we write on the IDE and the recommended languages are Arduino, C/C++. There is no interpreter, no operating system, and no firmware. The code that we write is converted to machine language and runs in Arduino itself. Also, Arduino can provide onboard storage and can be powered using a battery pack.

This is a simple plug n play device, which when powered runs and simply stops when powered off.

The disadvantages are the Arduino requires external hardware to connect to the internet and also it has only one USB port.

THE RASPBERRY PI

raspberry-pi-3-1
Image showing Raspberry Pi 3

The Raspberry Pi is a Single Board Computer or SCB. It is neither a microcontroller nor a microprocessor rather it has a SoC which has a multi-core processor, GPU, ROM and I/O peripherals inside it. The board also has ports for video, audio, USB, Ethernet, SD card and an HDMI port. The board also has GPIO(General Purpose Input Output) headers that look like Arduino pins.

index-htm_html_m6fa8c3e8
Parts of Raspberry Pi

The GPIO pins are one of the powerful features of the Pi board. 40 GPIO pins can be found on all present boards (unpopulated on Pi Zero and Pi Zero W). Something which can be noted from the figure below is that the pins are not numbered in order. The physical pins 27 and 28 are actually 0 and 1 which are marked for advanced purposes.

There are two 5V pins and two 3V3 (3.3 V) pins and several ground pins (0V). The ground pins are unconfigurable. The remaining are all general purpose 3V3 pins.

The input and output pins can take two values, high(3V3) and low(0V).

Apart from all these, GPIO can be used for several other purposes. Some are general while some are pin specific.

gpio-numbers-pi2
Image showing the GPIO pins

In Raspberry Pi, apart from Arduino, we are writing programs that run in an operating system and Raspberry Pi supports the OS Raspbian which is typically the Linux Operating System.

A general comparison between Arduino and Raspberry Pi is given in the box below:

 

mtizmdq5njy1mdq5njkxnjyw

It’s our choice to decide which board to choose for the project. The better way to do that is, analyze your project well and understand what your project actually needs. Raspberry Pi is more powerful than Arduino without any doubt as it has a faster clock. Also the same can be used for tasks which are repeating. Also Pi is good for multi-tasking.

In simple words, Arduino can be used for beginner projects and Raspberry Pi for complicated ones.

 

Traversals via a binary tree

Binary tree as the name suggests is a tree, upside down. Where the root(node) is on top. Root branches into left and right child nodes. And each child again re-branches to left and right child branches to form a binary tree. bt20linked20list20representation

Binary tree is mostly implemented using doubly linked lists which are linked lists with two links. Links store address of the nearby nodes. One, to the next node and the other to the previous node. A node which does not points to another will have a link, assigned as null.

Traversal via tree can be of in-order, pre-order  and postorder.

In-order traversal can be described as a tree traversed in such a way that the control goes first through out the left branch to root node and then to the right node i.e., first the left subtree is visited then the root node followed by right subtree.

bst_inorder

Here in the above figure we can see that from the root node 40, it is traversed through the left subtree alone to reach the left end. From there it goes to the recent node followed by the right branch. On completion of the left subtree, the control goes to the root node and then to the right branch.

Algorithm :

  1. Recursively travel left subtree
  2. Reach root node
  3. Recursively travel right subtree

until traversed via all nodes.

While in Pre-order traversal, the root node is visited first. Then control goes to the left subtree and then to the right subtree once traversal via left subtree is completed.

bst_preorder

In the above figure, it shows the control flow as it first visits the root node 40. From there left subtree is traversed to visit 25 followed by 10 and 32. After completely traversing via the left subtree, the right subtree is focused and hence it visits 78.

Algorithm :

  1. Visit root node.
  2. Recursively traverse left subtree.
  3. Recursively traverse right subtree.

until traversed via all nodes.

Post-order traversal as the name suggests, visits the root node at the end. First traverses all along the left subtree then the right subtree. Finally reaches the root node.

bst_postorder

From the above figure the control flow is visible as it first goes to the left subtree alone recursively to visit 10 and 32 first. Then it visits the parent node from where the control then goes to the right subtree and finally to the root node 40.

Algorithm :

  1. Recursively traverse left subtree.
  2. Recursively traverse right subtree.
  3. Visit root node.

until traversed via all nodes.

Tree  takes a time complexity  higher than a sorted array and lower than a linked list. Hence it is one of the reasons why it is preferred more.