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.

Advertisements

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 fro 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 file.asm (converts into an object file named file.o)

gcc file.o -o file -m32. (converts file.o into an executable)

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 Superman or Ironman. 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 atleast? 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 excercise, practise 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.

 

 

To all those who don’t have a plan

48257-confusion-clarity-spiritual-path

Well this is my third semester at Amrita Vishwa Vidyapeetham, Amritapuri. When I look back I have a past where I dreamt about my future in an entirely different way from what I am now and I will be. Now I am a CSE student which I never thought I would be! Its when I was in my high school where I started thinking about how my future should be. What all should I be doing, where all I should go and so on. Usual thoughts of a teenager.It was in my tenth grade when I started loving Biology, or to be more precise human physiology. But during that time I didn’t find so special about being a doctor apart from the higher number of digits I will be earning. Since I was a bit afraid of mathematics I always tried to stay away from that even though I always had a secret , unspoken love for maths. After my tenth everybody started asking whom I wanted to be. And wherever I go there will be someone who is a successful doctor or an MBBS student. I always have noticed the sparkle in everyone’s eyes when they meet a doctor or a future doctor. So every next time when I think about my career I will see the sparkle instead of subjects I love. For a teenager who always dealt with people with this sparkling eyes, this was the way. I started to think, “biology is not a big deal… so I could easily get a medical seat if I work hard… “. And this statement will return a true value definitely. At the same time my family was busy searching schools for me where I could get the most efficient training so that directly after my twelfth I could get that sparkling medical seat.

And there started the two years of tight scheduled training. I was so much of energy on my first days where I easily scored.But as time passed my preconceptions started to shatter. Biology was not a big deal. But biology was not alone to be dealt with easily. For one who feared maths just because that long curvy symbol of integration is now dealing with physics. That was truly a big deal! But there I found students who dealt physics so easily as they were taking a coffee. Slowly I felt the drop in the sparkle in the seat that I earlier founded to be shining like a diamond. And finally the day reached. I was bit too nervous. And rest was all obscure.

There my father had second thoughts. Being a Sr.Project Manager at IBM, he couldn’t wish anything better than his daughter coming after him. That’s how I ended up as a CSE student. Some may think, “What! A former biology student now in CSE?” . Its fine, even I too had the same feeling. It’s okay not to have a plan but unable to enjoy what we are doing at the present is not difficult, its dangerous!

Now I know, its not what you studied, its whether you could manage and enjoy what you are studying that matters.

So to all the young people out there, as great people say, nothing is an accident everything happens for a reason. So take the good in everything and just move on!

Basic communication protocols one should know

white switch hub turned on

Protocols are rules.So communication protocols are the rules for communication.They have a clear cut approach that either to follow the rules or not to communicate.They usually include UART,USART,SPI,I2C.

UART:Universal Asynchronous Receiver Transmitter
USART:Universal Synchronous Asynchronous (no clock data is transmitted) Receiver Transmitter
SPI:Serial Peripheral Interface
I2C:Inter Integrated Circuit

UART

UART is the hardware that deals with serial communication through serial ports.It is a standalone IC also found along with micro-controllers.Since it is a serial communication hardware,it transfers one bit at a time sequentially through the channel.Shift Registers are one unavoidable part of these devices as they are the one responsible for the conversion of serial data to parallel data.UART as the name suggests deals with asynchronous data hence is provided internally with a clock.So they works in the Baud rate,where baud rate is the no. of symbols per second.

USART

USART also deals with the serial communication of the data.Since dealing with synchronous data,it does not need to know the baud rate prior.It is provided clock externally.For both UART and USART,the communication happens through two lines:TX(Transmission) and RX(Reception). It can be,

Simplex:one way transmission,transmitter to receiver.
Half duplex:takes turns in reception and transmission.
Full duplex:both transmission and reception at the same time.

After the data is the PARITY BIT.Parity bit is added in order to check accuracy of data.Parity can be odd or even.If the no. of 1s in the data is odd, its off odd parity.If even,its of even parity.The receiver which is in sync with the transmitter expects a parity for the coming data.If met with an error will ask the transmitter to resend it.After the parity bit lies the stop bits which is either one or two.

SPI

Deals with two way communication.One master and multiple slaves concept.At a time can take input from more than one input devices.A standard SPI has 4 signals:MISO(Master Input Slave Output),MOSI(Master Output Slave Input),SCK(clock),SS(Slave Select).Since it includes clock signal,no need to know baud rate prior.

I2C

Serial communication protocol.In this protocol multiple masters are included.So multiple slaves can communicate with multiple masters or multiple slaves with single master.Has only two wires,SDA:Serial Data and SCL:Serial Clock.