Compile (with gcc) and link (with ld) to create your executable (without C library).

int add(int a, int b);

#include "x.h"
extern int extra;
int main()
int a = 9;
int b = 8;
int c;
c = add(9, 8) + extra;

return 0;

#include "x.h"
int extra = 9;
int add(int a, int b)
return a+b;

.globl _start

call main
movl $1, %eax
xorl %ebx, %ebx
int $0x80

Now do
~/# gcc -c -nostdlib a.c
~/# gcc -c -nostdlib b.c
~/# gcc -c -nostdlib start.S
~/# ld -o test a.o b.o start.o

Your executable test is ready!!


Good example showing how to create a Position Independent Executable (PIE).

We can create a Position Independent Executable (PIE) using -fPIE compiler option and -pie linker option of gcc.

A nice example collected from net.

#include <stdio.h>

static void foo() {}
static int bar = 5;

int main(void)
int baz = 5;
printf("function: %p, library function: %p, data: %p, stack: %p\n", foo, &printf, &bar, &baz);
return 0;

Now do

$ gcc -o aslr aslr.c; for i in $(seq 1 10); do ./aslr; done
$ gcc -fPIE -o aslr aslr.c; for i in $(seq 1 10); do ./aslr; done
$ gcc -fPIE -pie -o aslr aslr.c; for i in $(seq 1 10); do ./aslr; done

and see what you get!!


When 'clear' command doesn't clean the whole terminal window.

We can use 'reset' command to clean the whole terminal window.

C statement execution time in microseconds

#include <sys/time.h>

struct timeval tv1, tv2;

gettimeofday(&tv1, NULL);
//put c statements here
gettimeofday(&tv2, NULL);

printf ("Total time = %lld microseconds\n", ((long long)tv2.tv_sec*(long long)1000000+(long long)tv2.tv_usec) - ((long long)tv1.tv_sec*(long long)1000000+(long long)tv1.tv_usec));

Sort directories based on human readable size

# du --max-depth=3 . | sort -n | cut -f 2 | while read file_name; do du -sh $file_name; done;

Better strace command

# strace -fFittTvs300 -eraw=all -o output.txt <command or -p pid>

Run dos2unix on all files of a directory

# find . -type f -exec dos2unix '{}' ';'

Git: to get a particular revision of a file

# git show ecc653:my_program.php > k.php

Better grep command

# grep --color=always -i Quad /proc/cpuinfo

Cross gcc compilation




tar xvzf binutils-2.23.tar.gz

bunzip2 gmp-4.3.2.tar.bz2
tar xvf gmp-4.3.2.tar

bunzip2 mpfr-2.4.2.tar.bz2
tar xvf mpfr-2.4.2.tar

tar zxvf mpc-0.8.1.tar.gz

bunzip2 gcc-core-4.6.2.tar.bz2
tar xvf gcc-core-4.6.2.tar

mkdir src
mv gmp-4.3.2 mpc-0.8.1 mpfr-2.4.2 binutils-2.23 gcc-4.6.2 src

mkdir -p opt/cross

export PREFIX="$HOME/opt/cross"
export TARGET=i586-elf
export PATH="$PREFIX/bin:$PATH"

cd $HOME/src
mkdir build-binutils
cd build-binutils
../binutils-2.23/configure --target=$TARGET --prefix="$PREFIX" --disable-nls
make install

mv gmp-4.3.2 gcc-4.6.2/gmp
mv mpc-0.8.1 gcc-4.6.2/mpc
mv mpfr-2.4.2 gcc-4.6.2/mpfr
mkdir build-gcc
cd build-gcc
../gcc-4.6.2/configure --target=$TARGET --prefix="$PREFIX" --disable-nls --enable-languages=c --without-headers
make all-gcc
make all-target-libgcc
make install-gcc
make install-target-libgcc

$HOME/opt/cross/bin/$TARGET-gcc --version

#to add cross compiler location to system path
#export PATH="$HOME/opt/cross/bin:$PATH"
#if you like, you can copy the whole "cross" directory from your $HOME/opt to system /opt directory.
#and you add that path to your system path. You can place the export command in .bashrc in $HOME.

Search column name in a mysql db



WHERE table_schema = 'mydb'
AND column_name LIKE '%pattern%' ;

Using script to do something for all files of a folder

# here we try to separate files
#1. that are included in other files
# 2. that are not


echo > a.txt
find $folder | while read filepath
file=`basename "$filepath"`
usedin=`grep -r "$file" $folder`
if [ "$usedin" = "" ]
echo "$filepath" >> a.txt
echo "$filepath"
echo ======
echo $usedin

Sed: to add one space after comma

1. use sed to add a space after comma
2. use sed to replace multiple space(or tab) after comma with one space
3. use sed to perform 1. and 2. using -e option

# cat debug.txt
a, {, 9,L,%

# sed -i.bak -e 's/,/, /g' -e "s/,[ \t]*/, /g" debug.txt

# cat debug.txt
a, {, 9, L, %

Linux commands for set operations

Full explanation at:

Meld: three way merge (manually)

# meld --output o.txt l.txt b.txt r.txt

In general meld displays
l.txt (or local version in case of git, to which version merge is done) in left tab,
b.txt (or base version in case of git, common ancestor to both) in middle tab,
r.txt (or remote version in case of git, from where merge is done) in right tab.

Now make changes to b.txt and save.

Meld saves the changes to o.txt (or working copy in case of git, which is going to be commited).

Files l.txt, b.txt, r.txt all remains unchanged.

How to substitute an old pattern with a new pattern in matched lines of all files inside a directory

Say old pattern is "/old.php",
and new pattern is "/new.php"

# find . -type f -print0 | xargs -0 sed -i 's|/old.php|/new.php|g'
(sed -i for inplace editing of the file)

How to use vim to indent all files in a directory

run vim script indentme.scr to indent all files using vim

# find . -type f -name '*.c' -exec vim -s indentme.scr "{}" \;

[indentme.scr file shall contain vim commands like:

(gg means go to first line
= means auto indent
G means till the last line)

Delete lines containing a pattern from all files inside a directory

# find . -type f -print0 | xargs -0 sed -i '/my_pattern/d'
(sed -i is for inplace editing of the file)

Mysql: forcibly drop a table having foreign constraints

# /opt/lampp/bin/mysql -u root -p -D mydb -e "SET FOREIGN_KEY_CHECKS=0; drop table my_table; SET FOREIGN_KEY_CHECKS=1;"

How to add vim plugin manually

To manually add a plugin for php language to vim

0. vim plugins are of different types, (i) syntax (ii) indent etc.
1. create a folder like ~/.vim/indent or ~/.vim/syntax
2. collect the plugin for php.
Plugins generally have a name like php.vim.
Two different php.vim shall be available, one for syntax and one for indent.
3. put respective php.vim in respective folder.
4. when vim package is installed, it has its plugins in /usr/share/vim/ folder.
5. more info here (

Command find with exec

The below command would find any files with the extension '.doc' and copy them to your /tmp directory

# find / -name '*.doc' -exec cp '{}' /tmp/ ';'

The curly brackets are used in find to represent the current file which has been found. ie. If it found the file shopping.doc then {} would be substituted with shopping.doc. It would then continue to substitute {} for each file it finds. The brackets are normally protected by backslashes (\) or single-quotation marks ('), to stop bash expanding them (trying to interpret them as a special command eg. a wildcard). This ';' is the symbol used by find to signal the end of the commands. It's usually protected by a backslash (\) or quotes to stop bash from trying to expand it.

This finds all c-files and python files in the euler directory.
# find euler/ -iname "*.c*" -exec echo {} \; -or -iname "*.py" -exec echo {} \;

Delete empty lines from a file using vi editor

Use either of the following commands to delete all empty lines:


If you want to delete all lines that are empty or that contain only white space characters (spaces, tabs), use either of:


In the second command, v operates on lines that do not match, and \S matches anything that is not a white space, and d deletes the flagged lines (all lines that have no characters, or that have only white space characters).

Hexdump with output format

# hexdump -n 10 -s 512 -v -e '"x" 1/1 "%02X" " "' untitled.txt

-n for number of bytes.
-s for offset
-v for not showing a * mark for repetition
-e for output format

Qemu: redirect serial port data to stdio or a file, read it in text editor

redirect serial port data to stdio
# qemu-system-i386 -m 64 -serial stdio -hda ./harddisk.img

redirect serial port data to a file
# qemu-system-i386 -m 64 -serial file:a.txt -hda ./harddisk.img

redirect serial port data to a file (another way)
# qemu-system-i386 -m 64 -serial stdio -hda ./harddisk.img | tee a.txt

Now, a.txt can't be opened in a text editor.
Because it contains 0x00 (NULL character) in place of '\n' (new line character).

So use the following command:
# cat a.txt | xargs -0 echo > b.txt

Now b.txt is an ascii file, and can be read by text editors.

Some essential linux commands

to unrar into current folder
# unrar x a.rar

to unrar into a different folder
# mkdir a; unrar x a.rar ./a/

to zip a folder
#zip -r abc abc/

Remote debugging with gdb: debugging a kernel with qemu

1. in one terminal, run
#qemu -no-kqemu -m 64 -fda ./floppy.img -s -S
[floppy.img contains kernel.bin which is loaded by GRUB]

2. in other terminal, run
#gdb ./kernel.bin
[kernel.bin is an ELF executable]

(gdb) target remote localhost:1234
Remote debugging using localhost:1234
0x0000fff0 in ?? ()

(gdb) break _start
Note: breakpoint -1 also set at pc 0x1208a0.
Breakpoint 1 at 0x1208a0

(gdb) c
Stopped due to shared library event


3. Enjoy from here!

Check what is being installed: installwatch command on make install

# installwatch -o /tmp/pkginstall.list make install

Similarities and differences between spinlock, mutex and semaphore.

1. better to use when contention is heavy
2. when one task works in critical section, other tasks don't go to sleep
3. critical section can be used by at most one task
4. useful in multi-processor system but not in single processor system
5. useful when critical section is very small
6. if not acquired, spinlock doesn't make the task sleep, so it doesn't force a context switch

mutex ( ~ binary semaphore)
1. better to use when contention is not heavy
2. when one task works in critical section, other tasks go to sleep
3. critical section can be used by at most one task
4. useful in both multi-processor system and in single processor system
5. useful when critical section is not small
6. if not acquired, mutex makes the task sleep, so it forces a context switch

semaphore ( = counting semaphore)
1. better to use when contention is not heavy
2. when one task works in critical section, other tasks go to sleep
3. critical section can be used by at most N tasks
4. useful in both multi-processor system and in single processor system
5. useful when critical section is not small
6. if not acquired, semaphore makes the task sleep, so it forces a context switch

How to compact virtualbox vdi file.

# /opt/VirtualBox/VBoxManage modifyhd my_vbox.vdi --compact

Linux commands to assemble and link a.asm file written in nasm syntax.

# nasm -f elf32 -g a.asm
# gcc -g a.o -o a.out

How to set up and compile a SDL application.

Steps (Linux commands):

# tar vfxz SDL-1.2.15.tar.gz
# cd SDL-1.2.15
# ./configure
# make
# make install
# cd -
# /usr/local/bin/sdl-config --cflags --libs
# g++ a.cpp `/usr/local/bin/sdl-config --cflags --libs`
# ./a.out

Good link on c++ vtable vptr structure

Steps to program 8051 (P89V51RD2) microcontroller by ISP method using RS232

After long discussions and try, I was able to successfully able to program P89V51RD2 by In Situ Programming (ISP) method using RS232. In a hope that it shall be useful to others, I would like to post my experience with simple steps. For my success, I shall thank all our friends, who have helped me clearing my doubts and have provided their help and suggestions.

Here are the steps to program P89V51RD2 by ISP method using RS232.

My Need:
1. I had to find a microcontroller, which is self programmable, do not need a separate programmer.
2. Circuit should be simple, even a novice can make it and learn.
3. Other tools should be simple and freely available.

So, I choose:
1. P89V51RD2 microcontroller from Philips. Specifically P89V51RD2FN.
2. Circuit diagram from
3. SDCC for compiling C programs and FlashMagic for programming the microcontroller.

I made the circuit on a veroboard.
Connected the circuit to PC using serial cable(RS232).

vbox (winxp guest, linux host) setting:
check "enable serial port"
port number: com1
port mode: host device
port path: /dev/ttyS0

Test code:
void DeadDelay(unsigned int delay)
unsigned int indexI,indexJ;

for(indexI=0; indexI<delay; indexI++)
for(indexJ=0; indexJ<1275; indexJ++);
void main(void)
while (1)
/* Blink LED on Port 0 */


SDCC commands:
C:\>sdcc -I"c:\Program Files\SDCC\include\mcs51" test.c

C:\>packihx test.ihx > test.hex
packihx: read 25 lines, wrote 17: OK.

Flash Magic setting:
com port: com1
baud rate: 9600
device: 89v51rd2
interface: none(isp)
hex file: C:test.hex
check "Verify..."

DO NOT check the box near to "Erase all Flash".
DO NOT check the box near to "Erase Flash used by Hexfile".
It may damage the bootloader!
I didn't check these two boxes and programmed my P89V51RD2 twice, hence confirming that my bootloader was in safe condition.

Now click on "Start".
When it asks to reset the device, press reset button on circuit board and get p89v51rd2 programmed!


Securing puppy linux: Set password for root

After you boot up do the following:

1. open console type 'passwd root'. enter your new password twice.

2. run 'lock' on desktop and enter password from step 1

You may want to select 'blank' from the config to save on processor usage

3. edit /etc/inittab to look like this:

tty1::respawn:/sbin/getty 38400 tty1
tty2::respawn:/sbin/getty 38400 tty2

This keeps someone from killing lock with ctrl+alt+backspace and
logging back in automatically and also gives the option on bootup to
enter 'root' and 'password'.

4. run the firewall wizard at Menu->Setup->Linux-Firewall Wizard.
automagic works fine if you don't have to set up any local services.

5. shutdown and select 'heavy encryption' for save file.


Popular science books list

Mathematical recreations,-1,0,B/exact&FF=dmathematical+recreations&1,-1,/indexsort=r

Popular Science Collection

Symbol visibility in ELF shared library

Details on symbol visibility

Why symbol visibility is good

Position Independent Executable

Very good presentation on this from OpenBSD

Stripping shared libraries

Very good link on this

Good links on ELF (Executable and Linkable Format)

Ian Lance Taylor on Linkers

ELF format details

Very good details on ELF linker loader

Load and run DJGPP COFF, Win32 PE COFF, or ELF .o file

Steps to load ELF

ELF loader code

Code to dynamically link ELF files

Good code for dynamically linking/loading ELF shared library

The ELF Object File Format by Dissection

Very detailed description on ELF linking

How to write dynamically loadable libraries

Process address space, compiler stages etc. 

Linux linker code flow on last slide

Relocation types for i386

On Shared library

Some links collecting other links:

When ldd doesn't tell the details...

Sometimes, ldd does not show all the libraries that a program might use. The system call dlopen() can load a dynamic library on demand, and these libraries do not show up in the ldd output.

Then we can use strace command.
More here:

Some good links on Implementing Regular Expression Engine

Implementing Regular Expressions by Russ Cox

A Regular Expression Matcher, Code by Rob Pike, Exegesis by Brian Kernighan

Knuth-Morris-Pratt string matching algorithm