26 Apr 2017

What is a GDB(GNU Debugger)? How it Works ?

A debugger is a program that runs other programs, allowing the user to exercise control over these programs, and to examine variables when problems arise.
GNU Debugger, which is also called gdb, is the most popular debugger for UNIX systems to debug C and C++ programs.
GNU Debugger helps you in getting information about the following:
  • If a core dump happened, then what statement or expression did the program crash on?
  • If an error occurs while executing a function, what line of the program contains the call to that function, and what are the parameters?
  • What are the values of program variables at a particular point during execution of the program?
  • What is the result of a particular expression in a program?

How GDB Debugs?

GDB allows you to run the program up to a certain point, then stop and print out the values of certain variables at that point, or step through the program one line at a time and print out the values of each variable after executing each line.
GDB uses a simple command line interface.

Points to Note

  • Even though GDB can help you in finding out memory leakage related bugs, but it is not a tool to detect memory leakages.
  • GDB cannot be used for programs that compile with errors and it does not help in fixing those errors.
  • Before you go for installation, check if you already have gdb installed on your Unix system by issuing the following command:
    $gdb -help 
    
    If GDB is installed, then it will display all the available options within your GDB. If GDB is not installed, then proceed for a fresh installation.
    You can install GDB on your system by following the simple steps discussed below.
    step 1: Make sure you have the prerequisites for installing gdb:
    • An ANSI-compliant C compiler (gcc is recommended - note that gdb can debug codes generated by other compilers)
    • 115 MB of free disk space is required on the partition on which you're going to build gdb.
    • 20 MB of free disk space is required on the partition on which you're going to install gdb.
    step 2: Use the following command to install gdb on linux machine.
    $ sudo apt-get install libc6-dbg gdb valgrind 
    
    step 3: Now use the following command to find the help information.
    $gdb -help 
    
    You now have gdb installed on your system and it is ready to use.
  • Debugging Symbol Table maps instructions in the compiled binary program to their corresponding variable, function, or line in the source code. This mapping could be something like:
    • Program instruction ⇒ item name, item type, original file, line number defined.
    Symbol tables may be embedded into the program or stored as a separate file. So if you plan to debug your program, then it is required to create a symbol table which will have the required information to debug the program.
    We can infer the following facts about symbol tables:
    • A symbol table works for a particular version of the program – if the program changes, a new table must be created.
    • Debug builds are often larger and slower than retail (non-debug) builds; debug builds contain the symbol table and other ancillary information.
    • If you wish to debug a binary program you did not compile yourself, you must get the symbol tables from the author.
    To let GDB be able to read all that information line by line from the symbol table, we need to compile it a bit differently. Normally we compile our programs as:
    gcc hello.cc -o hello 
    
    Instead of doing this, we need to compile with the -g flag as shown below:
    gcc -g hello.cc -o hello 
GDB offers a big list of commands, however the following commands are the ones used most frequently:
  • 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
  • Getting Started: Starting and Stopping

    • gcc -g myprogram.c
      • Compiles myprogram.c with the debugging option (-g). You still get an a.out, but it contains debugging information that lets you use variables and function names inside GDB, rather than raw memory locations (not fun).
    • gdb a.out
      • Opens GDB with file a.out, but does not run the program. You’ll see a prompt (gdb) - all examples are from this prompt.
    • r
    • r arg1 arg2
    • r < file1
      • Three ways to run “a.out”, loaded previously. You can run it directly (r), pass arguments (r arg1 arg2), or feed in a file. You will usually set breakpoints before running.
    • help
    • h breakpoints
      • Lists help topics (help) or gets help on a specific topic (h breakpoints). GDB is well-documented.
    • q - Quit GDB

    Stepping through Code

    Stepping lets you trace the path of your program, and zero in on the code that is crashing or returning invalid input.
    • l
    • l 50
    • l myfunction
      • Lists 10 lines of source code for current line (l), a specific line (l 50), or for a function (l myfunction).
    • next
      • Runs the program until next line, then pauses. If the current line is a function, it executes the entire function, then pauses. next is good for walking through your code quickly.
    • step
      • Runs the next instruction, not line. If the current instruction is setting a variable, it is the same as next. If it’s a function, it will jump into the function, execute the first statement, then pause. step is good for diving into the details of your code.
    • finish
      • Finishes executing the current function, then pause (also called step out). Useful if you accidentally stepped into a function.

    Breakpoints or Watchpoints

    Breakpoints play an important role in debugging. They pause (break) a program when it reaches a certain point. You can examine and change variables and resume execution. This is helpful when some input failure occurs, or inputs are to be tested.
    • break 45
    • break myfunction
      • Sets a breakpoint at line 45, or at myfunction. The program will pause when it reaches the breakpoint.
    • watch x == 3
      • Sets a watchpoint, which pauses the program when a condition changes (when x == 3 changes). Watchpoints are great for certain inputs (myPtr != NULL) without having to break on every function call.
    • continue
      • Resumes execution after being paused by a breakpoint/watchpoint. The program will continue until it hits the next breakpoint/watchpoint.
    • delete N
      • Deletes breakpoint N (breakpoints are numbered when created).

    Setting Variables

    Viewing and changing variables at runtime is a critical part of debugging. Try providing invalid inputs to functions or running other test cases to find the root cause of problems. Typically, you will view/set variables when the program is paused.
    • print x
      • Prints current value of variable x. Being able to use the original variable names is why the (-g) flag is needed; programs compiled regularly have this information removed.
    • set x = 3
    • set x = y
      • Sets x to a set value (3) or to another variable (y)
    • call myfunction()
    • call myotherfunction(x)
    • call strlen(mystring)
      • Calls user-defined or system functions. This is extremely useful, but beware of calling buggy functions.
    • display x
      • Constantly displays the value of variable x, which is shown after every step or pause. Useful if you are constantly checking for a certain value.
    • undisplay x
      • Removes the constant display of a variable displayed by display command.

    Backtrace and Changing Frames

    A stack is a list of the current function calls - it shows you where you are in the program. A frame stores the details of a single function call, such as the arguments.
    • bt
      • Backtraces or prints the current function stack to show where you are in the current program. If main calls function a(), which calls b(), which calls c(), the backtrace is
    • c <= current location 
      b 
      a 
      main 
      
    • up
    • down
      • Move to the next frame up or down in the function stack. If you are in c, you can move to b or a to examine local variables.
    • return
      • Returns from current function.

    Handling Signals

    Signals are messages thrown after certain events, such as a timer or error. GDB may pause when it encounters a signal; you may wish to ignore them insteadhandle [signalname] [action]
    • handle SIGUSR1 nostop
    • handle SIGUSR1 noprint
    • handle SIGUSR1 ignore
      • Instruct GDB to ignore a certain signal (SIGUSR1) when it occurs. There are varying levels of ignoring.
      • Go through the following examples to understand the procedure of debugging a program and core dumped.
        • This example demonstrates how you would capture an error that is happening due to an exception raised while dividing by zero.
        • This example demonstrates a program that can dump a core due to non-initialized memory.
        Both the programs are written in C++ and generate core dump due to different reasons. After going through these two examples, you should be in a position to debug your C or C++ programs generating core dumps.
      • After going through this tutorial, you must have gained a good understanding of debugging a C or C++ program using GNU Debugger. Now it should be very easy for you to learn the functionality of other debuggers because they are very similar to GDB. It is highly recommended that you go through other debuggers as well to become familiar with their features.
        There are quite a few good debuggers available in the market:
        • DBX Debugger - This debugger ships along with Sun Solaris and you can get complete information about this debugger using the man page of dbx, i.e., man dbx.
        • DDD Debugger - This is a graphical version of dbx and freely available on Linux. To have a complete detail, use the man page of ddd, i.e., man ddd.
        You can get a comprehensive detail about GNU Debugger from the following link: Debugging with GDB

ISRO Proud Once Again.........................

Goto the link below.You will see a globe and on that lots of green dots.you can click on any dot and listen to the live Radio of that particular area or region.

simply Amazing..........................try everyone you feel 😅😅😅

http://radio.garden/live

What is a BSP(Board Support Package)?

In embedded systems, a board support package (BSP) is an implementation of specific support code (software) for a given (device motherboard) board that conforms to a given operating system. It is commonly built with a bootloader that contains the minimal device support to load the operating system and device drivers for all the devices on the board.
Some suppliers also provide a root file system, a toolchain for building programs to run on the embedded system (which would be part of the architecture support package), and utilities to configure the device (while running).

Example

The Wind River board support package for the ARM Integrator 920T board contains, among other things, the following elements:
  • A config.h file, which defines constants such as ROM_SIZE and RAM_HIGH_ADRS.
  • A Makefile, which defines binary versions of VxWorks ROM images for programming into flash memory.
  • A bootrom file, which defines the boot line parameters for the board.
  • A target.ref file, which describes board-specific information such as switch and jumper settings, interrupt levels, and offset bias.
  • A VxWorks image.
  • Various C files, including:
flashMem.c — the device driver for the board's flash memory
pciIomapShow.c — mapping file for the PCI bus
primeCellSio.c — TTY driver
sysLib.c — system-dependent routines specific to this board
romInit.s — ROM initialization module for the board; contains entry code for images that start running from ROM

A board support package (BSP) is essential code code for a given computer hardware device that will make that device work with the computer's OS (operating system). The BSP contains a small program called a boot loader or boot manager that places the OS and device drivers into memory. The contents of the BSP depend on the particular hardware and OS.
Specific tasks that the BSP performs include the following, in order:
  • Initialize the processor.
  • Initialize the bus.
  • Initialize the interrupt controller.
  • Initialize the clock.
  • Initialize the RAM (random access memory) settings.
  • Configure the segments (if applicable).
  • Run the boot loader.
In addition to the foregoing, a BSP can contain directives, compilation parameters, and hardware parameters for configuring the OS.


for more information click on below link

https://www.windriver.com/products/bsp_web/what_is_a_bsp.pdf

25 Apr 2017

Books for Different languages download for free enjoy..........................

I have Uploaded a Huge Collection of Books of below Languages.
Ajax
Amazon
Andriod
Angular JS
C to C++ to C#
Asp Dot.Net
HTML to CSS to PHP to MySQL
Internet to Networking
Java to JavaScript to Jason
Apache to Kafka to Connector
Linux to Kali to Shell to Server
Hacking to Web Penetration
Algorithm to Data Structure
Python - 115 Books & Ready Programs
Artificial Intelligence to Data Mining
Bash BeEF CS Cloud Deep Web Drones
In Short, All Most Everything in Technology
Learn, Enjoy, Share Programming & Do Something for the Society.

22 Apr 2017

Embedded programming basics for C – bitwise operations


Bitwise or bitlevel operations form the basis of embedded programming. A knowledge of Hexadecimal and Binary Numbering system is required along with conversion from binary to hex and vice-verse. A tutorial for that is located @ www.ocfreaks.com/hexadecimal-and-binary-number-system-basics-for-embedded-programming/. If you are less familiar with hexadecimal and binary number systems that will help you.
Further , I assume that the reader has a basic understanding of C programming language , Digital Logic , MCU(Registers,etc..).

Bit level Operations in C

Now getting armed with the knowledge of interconversion between Hexadecimal and Binary we can start with Bitwise(or bit level) operations in C. There are bascially 6 types of Bitwise operators. These are :
1. Bitwise OR operator denoted by ‘|
2. Bitwise AND operator denoted by ‘&
3. Bitwise Complement or Negation Operator denoted by ‘~
4. Bitwise Right Shift & Left Shift denoted by ‘>>‘ and ‘<<‘ respectively
5. Bitwise XOR operator denoted by ‘^
Important Note: Bitwise Operations are meant to be done on Integers only! No Float and No Double here plz!
Below is the Truth table for OR , AND , XOR – each of them require 2 operands:
OP1 (Operand 1)OP2 (Operand 2)OP1 | OP2 (OR)OP1 & OP2 (AND)OP1 ^ OP2 (XOR)
00000
10101
01101
11110
Hexadecimal Numbers in C/C++ program have a ‘0x’ prefix. Without these prefix any number will be considered as a Decimal number by the compiler and hence we need to be explicit with numbers.
Implied Declaration and Use of Numbers when working at bit level:
Consider: unsigned int n = 0x7F2; Here its is implied that n will be 0x000007F2 since n is a 32bit number. Here number will be automatically padded with Zeros form right hand side as required.
Consider: unsigned int n = (1<<3); Here the 3rd bit will be 1 and rest all will be made zeros by the compiler.
In short 0s are padded towards the left as required.
Consider there is a 32 bit register which is connected to 32 pins. Changing any bit to 1 will produce a HIGH (LOGIC 1) and making it ‘0’ will produce a LOW i.e LOGIC 0 on the corresponding bit. If we assign bit number 19(from right) a ‘1’ then pin 19 will produce a HIGH.
In C this can be done as :

REG = 0x00100000; //hexadecimal
=or=

REG = (1<<19); // sort of compact binary rep.

As you can see using binary number directly is a headache - specially when there are like 32 bits to handle. Using Hexadecimal instead makes it a bit easier and using Left shift operator makes it super simple. Here '<<' is called the Left Shift Operator. Similar to this is ">>" viz. Right Shift operator.
"(1<<19)" Simply means 'Shift 1 towards the LEFT by 19 Places'. Other bits will be Zero by default.
We generally use Hexadecimal when we need to change bits in bluk and Left shift operator when only few bits need to be changed or extracted.

ORing in C

This is the same exact thing as in Digital Logic i.e 1 ORed with 'x' is always 1 and 0 ORed with 'x' is always 'x' , where x is a bit. Lets take two 4-bit numbers and OR them. Consider two 4-bit numbers n1=0100 & n2=1001. Here the 1st bit of n1 will be ORed with 1st bit of n2 , 2nd bit of n1 will be ORed with 2nd bit of n2 and soo on. In this case n1 is decimal 4 and n2 is decimal 9.
n1 (4) =>0100
n2 (9) =>1001
ORed Result (13) =>1101
Hence we get 4 | 9 = 13.
It can be seen that bitwise ORing is similar to addition but this is not always the case since bitwise OR doesnt deal with carry generated after adding(i.e ORing) two 1s. For e.g. 12 | 9 is also = 13.
Now , If we want to make bit 19 and 12 as '1' we can use the binary OR operator which is represented by a pipe i.e '|'.

REG = (1<<19) | (1<<12); // 19th and 12th bits are set to '1' , rest are Zeros.
Now consider we want to making the first 21 bits (from right) to '1'. This is can be done using hexadecimal notation instead of using shift operator since we will need to write 21 left shift operations for each of the 21 bits. In this case just consider we have a 32 bit number which has all first 19 bits '1'. Then convert this number to hexadecimal and use it!

REG = 0x003FFFFF;
Hence using Hexadecimal or Binary operator depends on the situation.

Bitwise 1's Complement / Negation in C :

Now lets say.. we need to convert all 0s to 1s and vice-verse. This can be done using the Bitwise negation operator denoted by '~'. The result of this operation is called 1's Complement. Its also called a 'NOT' operation. '~' is a unary operator since it requires only 1 operator while rest all are binary operators.
1st lets take a 4bit example to keep it simple.
Consider a binary number 1101. Its Negation will be ~(1101) => 0010.
Now lets get back to 32 bit numbers.. In C it can be done as follows:

unsigned int x = 0x0FFF000F;
REG = ~(x); // REG is assigned 0xF000FFF0;
=or=

REG = ~(0x0FFF000F); // REG is assigned 0xF000FFF0;

ANDing in C

Binary AND operator in C is denoted by '&'. When 2 numbers are ANDed each pair of 'corresponding' bits in both numbers are ANDed. Consider two 4-bit binary numbers ANDed : 1010 & 1101 , here nth bit of both numbers are ANDed to get the result. Here the same truth table(already shown above) is followed as in Therotical Digital Logic i.e 1 ANDed with x is always 'x' (x is a binary number.. a bit) and 0 ANDed with 'x' is always 0.

unsigned char n1,n2,n3; //we can declare an 8-bit number as a char;
n1 = 0xF4; // binary n1 = 0b11110100;
n2 = 0x3A; // binary n2 = 0b00111010;
n3 = n1 & n2; // binary n3 = 0b00110000; i.e 0x30;

XORing in C

XOR is short for eXclusive-OR. By definition of XOR , the result will be a '1' if both the input bits are different and result will be '0' if both are same (as seen in the table few paragraphs above). XOR can be used to check the bit difference between 2 numbers or Registers.

unsigned int n1,n2,n3;
n1 = 0x13; //binay n1 = 0b10011
n2 = 0x1A; //binay n2 = 0b11010;
n3 = n1^n2; // n2 = 0x09 which is binary 0b01001;

Working with Read/Write Registers in C

Generally its a bad Idea to assign a value directly to Registers since doing so may change the value of other bits which might be used to contol some other hardware.
Consider an 8 bit Register say REGT_8b is used to Start/Stop 8 different Timers. Bit 0 (from left) controls Timer 0 , Bit 1 Controls Timer 1 and so on... Writing a '1' to a bit will Start the timer and a '0' will Stop the Timer.
Now lets say Timers 7,6,5 are started and others are stopped. So the current value of REGT_8b will be '11100000'. Now assume that we want to Start Timer 2. We can do this in a manner which doesn't affect the other bits as follows :

REGT_8b = REGT_8b | (1<<2); // which is 11100000 | 00000100 = 11100100
=or simply=

REGT_8b |= (1<<2); // same as above
Now lets say we want to Stop Timer 6. This can be achieved as follows :

REGT_8b = REGT_8b & (~(1<<6));
=or simply=

REGT_8b &= ~(1<<6);
Here (1<<6) will be 01000000 (considering it 8bit.. for 32 bit 0s will be padding on left). Then ~(1<<6) will be ~(01000000) = 10111111 and finally when its ANDed with current value of REGT_8b 6th bit of REGT_8b will be set to '0' and others will remain as they were since ANDing any bit with 1 doesn't change its value.

More Examples

For below examples assume current value of REGT_8b as '11100011' which is 8 bit.
1) Stop Timers 0 and 5 :

REGT_8b &= ~( (1<<0) | (1<<5) );
=> ((1<<0) | (1<<5)) is = ((00000001) | (00100000)) = 00100001
=> ~(00100001) is = 11011110
=> Finally REGT_8b & 11011110 is = (11100011) & (11011110) = 11000010 => Timers 0 and 5 Stopped!

2) Start Timers 3 and 4:

REGT_8b |= ( (1<<3) | (1<<4) );
=> ((1<<3) | (1<<4)) is = ((00001000) | (00010000)) = 00011000;
=> Now REGT_8b | (00001000) is = (11100011) | (00011000) = 11111011 => Timers 3 and 4 Started!

3) Stop Timer 7 and Start timer 3:

REGT_8b = (REGT_8b | (1<<3)) & (~(1<<7));
Above complex expression can be avioded by doing it in 2 steps as:

REGT_8b &= ~(1<<7); // Stop Timer 7
REGT_8b |= (1<<3); // Start Timer 3

Monitoring Specific bit change in Registers

Many times we need to read certain Flags in a register that denotes change in Hardware state. Consider a 32 bit Register REGX in which the 12th bit denotes the arrival of data from UART Receive pin into buffer. This data may be a command for the MCU to start or stop or do something. So we need to read the command then interpret it and call appropriate function. In simplest approach we can continuously scan for change in 12th bit of REGX as follows :

while( REGX & (1<<12) ) //wait indefinitely until 12th bit changes from 0 to 1
{
//do something
//exit loop
}

/*=OR=*/

while(REGX & (1<<12)); //wait indefinitely until 12th bit changes from 0 to 1
//do something

Unless the 12th bit of REGX is '1' the result of (REGX & (1<<12)) will always be zero. When 12th bit is 1 then (REGX & (1<<12)) will be = (1<<12) which is obviously greater than 0 and hence is evaluated as TRUE condition and the code inside the while loop gets executed.
To monitor for the change in 12th bit from 1 to 0 we just Negate the condition inside while to :

while ( !(REGX & (1<<12)) ) //wait indefinitely until 12th bit changes from 1 to 0
{
//do something
//exit loop
}

/*=OR=*/
while ( !(REGX & (1<<12)) ); //wait indefinitely until 12th bit changes from 1 to 0
//do something

A real life example would as follows:

#define RDR (1<<0) // Receiver Data Ready
char U0Read(void)
{
     while( !(U0LSR & RDR) ); // wait till any data arrives into Rx FIFO
     return U0RBR; 
}
Note that you are forcing the CPU into an indefinite wait state. This can only useful in a few cases like, for e.g., you have made a command parser for a CNC machine which waits for a command and then processes it accordingly(or takes appropriate action) then again waits for new command.

Extracting/Testing Bit(s) from a Register:

To extract a bit from a register we can use a variable in which all other bit locations , except the one we are intereseted in , are forced to 0. This can be done using masks.
Lets assume we want to extract bit number 13. For this we first define a mask in which bit location 13 is 1 and rest are all zeros. Then we AND this mask with the register and save the result in a variable.

unsigned int mask ,extract_n;
mask = (1<<13);
extract_n = REGX & mask; // bit 13 goes to extract_n 
If the 13th bit of REGX was 1 then the 13th bit of extract_n will also be one. Similarly for 0. This can be easily extended to extract multiple bits.
To test whether bit 13 of REGX is 0 or 1 we can accomplish it as follows :

if(REGX & (1<<13))
{
...
...
}
This is similar to what we did using mask and monitoring except that the result here is used as condition for 'if' construct. Here too '(REGX & (1<<13))' will evaluate to true if bit 13 is 1 and false if bit 13 is 0.