Contributors

Thursday, September 15, 2011

Use of __attribute__


void exitnow() __attribute__((noreturn));


int main()
{
    int n = 0;
        if ( n > 0 )
    {
                exitnow();
        /* control never reaches this point */
    }
        else
                return 0;
}

Thursday, August 25, 2011

Discussion board: Malloc() and Calloc()!

http://www.coolinterview.com/interview/11749/

Everyone,

Allocation happens rightaway when a malloc or calloc is called. Only difference is that, malloc() leaves the area with garbage while calloc() initializes it with zeros.

What you guys think?

Sunday, August 14, 2011

Linux:Binutils:READELF


readelf - There is a utility in Linux which dismantles any ELF format file in the command like. We have lot of parameters to pass to this utility.
Options are:
-a --all               Equivalent to: -h -l -S -s -r -d -V -A -I
-h --file-header       Display the ELF file header
-l --program-headers   Display the program headers
--segments          An alias for --program-headers
-S --section-headers   Display the sections' header
--sections          An alias for --section-headers
-g --section-groups    Display the section groups
-e --headers           Equivalent to: -h -l -S
-s --syms              Display the symbol table
--symbols          An alias for --syms
-n --notes             Display the core notes (if present)
-r --relocs            Display the relocations (if present)
-u --unwind            Display the unwind info (if present)
-d --dynamic           Display the dynamic section (if present)
-V --version-info      Display the version sections (if present)
-A --arch-specific     Display architecture specific information (if any).
-D --use-dynamic       Use the dynamic section info when displaying symbols
-x --hex-dump= Dump the contents of section
-w[liaprmfFso] or
--debug-dump[=line,=info,=abbrev,=pubnames,=ranges,=macro,=frames,=str,=loc]
Display the contents of DWARF2 debug sections
-I --histogram         Display histogram of bucket list lengths
-W --wide              Allow output width to exceed 80 characters
-H --help              Display this information
-v --version           Display the version number of readelf
Options are:
-a --all               Equivalent to: -h -l -S -s -r -d -V -A -I
-h --file-header       Display the ELF file header
-l --program-headers   Display the program headers
--segments          An alias for --program-headers
-S --section-headers   Display the sections' header
--sections          An alias for --section-headers
-g --section-groups    Display the section groups
-e --headers           Equivalent to: -h -l -S
-s --syms              Display the symbol table
--symbols          An alias for --syms
-n --notes             Display the core notes (if present)
-r --relocs            Display the relocations (if present)
-u --unwind            Display the unwind info (if present)
-d --dynamic           Display the dynamic section (if present)
-V --version-info      Display the version sections (if present)
-A --arch-specific     Display architecture specific information (if any).
-D --use-dynamic       Use the dynamic section info when displaying symbols
-x --hex-dump= Dump the contents of section
-w[liaprmfFso] or
--debug-dump[=line,=info,=abbrev,=pubnames,=ranges,=macro,=frames,=str,=loc]
Display the contents of DWARF2 debug sections
-I --histogram         Display histogram of bucket list lengths
-W --wide              Allow output width to exceed 80 characters
-H --help              Display this information
-v --version           Display the version number of readelf
How to execute:
$ readelf --all
Example:
A C source file:
#include
void func(){
printf("I am in a function\n");
}
int main(int argc)
{
func();
return 0;
}
After compilation, run the readelf utility:
ELF Header:
Magic:   7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00
Class:                             ELF32
Data:                              2's complement, little endian
Version:                           1 (current)
OS/ABI:                            UNIX - System V
ABI Version:                       0
Type:                              EXEC (Executable file)
Machine:                           Intel 80386
Version:                           0x1
Entry point address:               0x80482c0
Start of program headers:          52 (bytes into file)
Start of section headers:          1928 (bytes into file)
Flags:                             0x0
Size of this header:               52 (bytes)
Size of program headers:           32 (bytes)
Number of program headers:         7
Size of section headers:           40 (bytes)
Number of section headers:         28
Section header string table index: 25
Section Headers:
[Nr] Name              Type            Addr     Off    Size   ES Flg Lk Inf Al
[ 0]                   NULL            00000000 000000 000000 00      0   0  0
[ 1] .interp           PROGBITS        08048114 000114 000013 00   A  0   0  1
[ 2] .note.ABI-tag     NOTE            08048128 000128 000020 00   A  0   0  4
[ 3] .hash             HASH            08048148 000148 00002c 04   A  4   0  4
[ 4] .dynsym           DYNSYM          08048174 000174 000060 10   A  5   1  4
[ 5] .dynstr           STRTAB          080481d4 0001d4 000060 00   A  0   0  1
[ 6] .gnu.version      VERSYM          08048234 000234 00000c 02   A  4   0  2
[ 7] .gnu.version_r    VERNEED         08048240 000240 000020 00   A  5   1  4
[ 8] .rel.dyn          REL             08048260 000260 000008 08   A  4   0  4
[ 9] .rel.plt          REL             08048268 000268 000010 08   A  4  11  4
[10] .init             PROGBITS        08048278 000278 000017 00  AX  0   0  4
[11] .plt              PROGBITS        08048290 000290 000030 04  AX  0   0  4
[12] .text             PROGBITS        080482c0 0002c0 0001a4 00  AX  0   0  4
[13] .fini             PROGBITS        08048464 000464 00001a 00  AX  0   0  4
[14] .rodata           PROGBITS        08048480 000480 00001c 00   A  0   0  4
[15] .eh_frame         PROGBITS        0804849c 00049c 000004 00   A  0   0  4
[16] .ctors            PROGBITS        080494a0 0004a0 000008 00  WA  0   0  4
[17] .dtors            PROGBITS        080494a8 0004a8 000008 00  WA  0   0  4
[18] .jcr              PROGBITS        080494b0 0004b0 000004 00  WA  0   0  4
[19] .dynamic          DYNAMIC         080494b4 0004b4 0000c8 08  WA  5   0  4
[20] .got              PROGBITS        0804957c 00057c 000004 04  WA  0   0  4
[21] .got.plt          PROGBITS        08049580 000580 000014 04  WA  0   0  4
[22] .data             PROGBITS        08049594 000594 00000c 00  WA  0   0  4
[23] .bss              NOBITS          080495a0 0005a0 000004 00  WA  0   0  4
[24] .comment          PROGBITS        00000000 0005a0 00010e 00      0   0  1
[25] .shstrtab         STRTAB          00000000 0006ae 0000d7 00      0   0  1
[26] .symtab           SYMTAB          00000000 000be8 000470 10     27  44  4
[27] .strtab           STRTAB          00000000 001058 00023a 00      0   0  1
Key to Flags:
W (write), A (alloc), X (execute), M (merge), S (strings)
I (info), L (link order), G (group), x (unknown)
O (extra OS processing required) o (OS specific), p (processor specific)
Program Headers:
Type           Offset   VirtAddr   PhysAddr   FileSiz MemSiz  Flg Align
PHDR           0x000034 0x08048034 0x08048034 0x000e0 0x000e0 R E 0x4
INTERP         0x000114 0x08048114 0x08048114 0x00013 0x00013 R   0x1
[Requesting program interpreter: /lib/ld-linux.so.2]
LOAD           0x000000 0x08048000 0x08048000 0x004a0 0x004a0 R E 0x1000
LOAD           0x0004a0 0x080494a0 0x080494a0 0x00100 0x00104 RW  0x1000
DYNAMIC        0x0004b4 0x080494b4 0x080494b4 0x000c8 0x000c8 RW  0x4
NOTE           0x000128 0x08048128 0x08048128 0x00020 0x00020 R   0x4
GNU_STACK      0x000000 0x00000000 0x00000000 0x00000 0x00000 RW  0x4
Section to Segment mapping:
Segment Sections...
00
01     .interp
02     .interp .note.ABI-tag .hash .dynsym .dynstr .gnu.version .gnu.version_r .rel.dyn .rel.plt .init .plt .text .fini .rodata .eh_frame
03     .ctors .dtors .jcr .dynamic .got .got.plt .data .bss
04     .dynamic
05     .note.ABI-tag
06
Dynamic section at offset 0x4b4 contains 20 entries:
Tag        Type                         Name/Value
0x00000001 (NEEDED)                     Shared library: [libc.so.6]
0x0000000c (INIT)                       0x8048278
0x0000000d (FINI)                       0x8048464
0x00000004 (HASH)                       0x8048148
0x00000005 (STRTAB)                     0x80481d4
0x00000006 (SYMTAB)                     0x8048174
0x0000000a (STRSZ)                      96 (bytes)
0x0000000b (SYMENT)                     16 (bytes)
0x00000015 (DEBUG)                      0x0
0x00000003 (PLTGOT)                     0x8049580
0x00000002 (PLTRELSZ)                   16 (bytes)
0x00000014 (PLTREL)                     REL
0x00000017 (JMPREL)                     0x8048268
0x00000011 (REL)                        0x8048260
0x00000012 (RELSZ)                      8 (bytes)
0x00000013 (RELENT)                     8 (bytes)
0x6ffffffe (VERNEED)                    0x8048240
0x6fffffff (VERNEEDNUM)                 1
0x6ffffff0 (VERSYM)                     0x8048234
0x00000000 (NULL)                       0x0
Relocation section '.rel.dyn' at offset 0x260 contains 1 entries:
Offset     Info    Type            Sym.Value  Sym. Name
0804957c  00000506 R_386_GLOB_DAT    00000000   __gmon_start__
Relocation section '.rel.plt' at offset 0x268 contains 2 entries:
Offset     Info    Type            Sym.Value  Sym. Name
0804958c  00000107 R_386_JUMP_SLOT   00000000   __libc_start_main
08049590  00000207 R_386_JUMP_SLOT   00000000   printf
There are no unwind sections in this file.
Symbol table '.dynsym' contains 6 entries:
Num:    Value  Size Type    Bind   Vis      Ndx Name
0: 00000000     0 NOTYPE  LOCAL  DEFAULT  UND
1: 00000000   221 FUNC    GLOBAL DEFAULT  UND __libc_start_main@GLIBC_2.0 (2)
2: 00000000    54 FUNC    GLOBAL DEFAULT  UND printf@GLIBC_2.0 (2)
3: 08048484     4 OBJECT  GLOBAL DEFAULT   14 _IO_stdin_used
4: 00000000     0 NOTYPE  WEAK   DEFAULT  UND _Jv_RegisterClasses
5: 00000000     0 NOTYPE  WEAK   DEFAULT  UND __gmon_start__
Symbol table '.symtab' contains 71 entries:
Num:    Value  Size Type    Bind   Vis      Ndx Name
0: 00000000     0 NOTYPE  LOCAL  DEFAULT  UND
1: 08048114     0 SECTION LOCAL  DEFAULT    1
2: 08048128     0 SECTION LOCAL  DEFAULT    2
3: 08048148     0 SECTION LOCAL  DEFAULT    3
4: 08048174     0 SECTION LOCAL  DEFAULT    4
5: 080481d4     0 SECTION LOCAL  DEFAULT    5
6: 08048234     0 SECTION LOCAL  DEFAULT    6
7: 08048240     0 SECTION LOCAL  DEFAULT    7
8: 08048260     0 SECTION LOCAL  DEFAULT    8
9: 08048268     0 SECTION LOCAL  DEFAULT    9
10: 08048278     0 SECTION LOCAL  DEFAULT   10
11: 08048290     0 SECTION LOCAL  DEFAULT   11
12: 080482c0     0 SECTION LOCAL  DEFAULT   12
13: 08048464     0 SECTION LOCAL  DEFAULT   13
14: 08048480     0 SECTION LOCAL  DEFAULT   14
15: 0804849c     0 SECTION LOCAL  DEFAULT   15
16: 080494a0     0 SECTION LOCAL  DEFAULT   16
17: 080494a8     0 SECTION LOCAL  DEFAULT   17
18: 080494b0     0 SECTION LOCAL  DEFAULT   18
19: 080494b4     0 SECTION LOCAL  DEFAULT   19
20: 0804957c     0 SECTION LOCAL  DEFAULT   20
21: 08049580     0 SECTION LOCAL  DEFAULT   21
22: 08049594     0 SECTION LOCAL  DEFAULT   22
23: 080495a0     0 SECTION LOCAL  DEFAULT   23
24: 00000000     0 SECTION LOCAL  DEFAULT   24
25: 00000000     0 SECTION LOCAL  DEFAULT   25
26: 00000000     0 SECTION LOCAL  DEFAULT   26
27: 00000000     0 SECTION LOCAL  DEFAULT   27
28: 080482e4     0 FUNC    LOCAL  DEFAULT   12 call_gmon_start
29: 00000000     0 FILE    LOCAL  DEFAULT  ABS crtstuff.c
30: 080494a0     0 OBJECT  LOCAL  DEFAULT   16 __CTOR_LIST__
31: 080494a8     0 OBJECT  LOCAL  DEFAULT   17 __DTOR_LIST__
32: 080494b0     0 OBJECT  LOCAL  DEFAULT   18 __JCR_LIST__
33: 0804959c     0 OBJECT  LOCAL  DEFAULT   22 p.0
34: 080495a0     1 OBJECT  LOCAL  DEFAULT   23 completed.1
35: 08048308     0 FUNC    LOCAL  DEFAULT   12 __do_global_dtors_aux
36: 0804833c     0 FUNC    LOCAL  DEFAULT   12 frame_dummy
37: 00000000     0 FILE    LOCAL  DEFAULT  ABS crtstuff.c
38: 080494a4     0 OBJECT  LOCAL  DEFAULT   16 __CTOR_END__
39: 080494ac     0 OBJECT  LOCAL  DEFAULT   17 __DTOR_END__
40: 0804849c     0 OBJECT  LOCAL  DEFAULT   15 __FRAME_END__
41: 080494b0     0 OBJECT  LOCAL  DEFAULT   18 __JCR_END__
42: 08048440     0 FUNC    LOCAL  DEFAULT   12 __do_global_ctors_aux
43: 00000000     0 FILE    LOCAL  DEFAULT  ABS new.c
44: 080494b4     0 OBJECT  GLOBAL DEFAULT   19 _DYNAMIC
45: 08048480     4 OBJECT  GLOBAL DEFAULT   14 _fp_hw
46: 080494a0     0 NOTYPE  GLOBAL HIDDEN  ABS __fini_array_end
47: 08049598     0 OBJECT  GLOBAL HIDDEN   22 __dso_handle
48: 080483fc    66 FUNC    GLOBAL DEFAULT   12 __libc_csu_fini
49: 08048278     0 FUNC    GLOBAL DEFAULT   10 _init
50: 080482c0     0 FUNC    GLOBAL DEFAULT   12 _start
51: 080494a0     0 NOTYPE  GLOBAL HIDDEN  ABS __fini_array_start
52: 080483a8    82 FUNC    GLOBAL DEFAULT   12 __libc_csu_init
53: 080495a0     0 NOTYPE  GLOBAL DEFAULT  ABS __bss_start
54: 08048380    40 FUNC    GLOBAL DEFAULT   12 main
55: 00000000   221 FUNC    GLOBAL DEFAULT  UND __libc_start_main@@GLIBC_
56: 080494a0     0 NOTYPE  GLOBAL HIDDEN  ABS __init_array_end
57: 08049594     0 NOTYPE  WEAK   DEFAULT   22 data_start
58: 00000000    54 FUNC    GLOBAL DEFAULT  UND printf@@GLIBC_2.0
59: 08048464     0 FUNC    GLOBAL DEFAULT   13 _fini
60: 080494a0     0 NOTYPE  GLOBAL HIDDEN  ABS __preinit_array_end
61: 08048368    24 FUNC    GLOBAL DEFAULT   12 func
62: 080495a0     0 NOTYPE  GLOBAL DEFAULT  ABS _edata
63: 08049580     0 OBJECT  GLOBAL DEFAULT   21 _GLOBAL_OFFSET_TABLE_
64: 080495a4     0 NOTYPE  GLOBAL DEFAULT  ABS _end
65: 080494a0     0 NOTYPE  GLOBAL HIDDEN  ABS __init_array_start
66: 08048484     4 OBJECT  GLOBAL DEFAULT   14 _IO_stdin_used
67: 08049594     0 NOTYPE  GLOBAL DEFAULT   22 __data_start
68: 00000000     0 NOTYPE  WEAK   DEFAULT  UND _Jv_RegisterClasses
69: 080494a0     0 NOTYPE  GLOBAL HIDDEN  ABS __preinit_array_start
70: 00000000     0 NOTYPE  WEAK   DEFAULT  UND __gmon_start__
Histogram for bucket list length (total of 3 buckets):
Length  Number     % of total  Coverage
0  0          (  0.0%)
1  1          ( 33.3%)     20.0%
2  2          ( 66.7%)    100.0%
Version symbols section '.gnu.version' contains 6 entries:
Addr: 0000000008048234  Offset: 0x000234  Link: 4 (.dynsym)
000:   0 (*local*)       2 (GLIBC_2.0)     2 (GLIBC_2.0)     1 (*global*)
004:   0 (*local*)       0 (*local*)
Version needs section '.gnu.version_r' contains 1 entries:
Addr: 0x0000000008048240  Offset: 0x000240  Link to section: 5 (.dynstr)
000000: Version: 1  File: libc.so.6  Cnt: 1
0x0010:   Name: GLIBC_2.0  Flags: none  Version: 2
Thanks.

Monday, August 8, 2011


Illustration: The following program explains the use of backtrace(): Just compile it and run you will get like:
main() => foo() => showBackTrace() with the virtual addresses.

/* Include execinfo.h header file for backtrace() functions */
#include < stdio.h >
#include < stdlib.h >
#include < execinfo.h >

/* Include prototypes */
void foo();
void showBackTrace();

/* Main function to call foo() function */
int main(void) {
foo();
return 0;
}

/* Call showBackTrace() function here */
void foo(void) {
showBackTrace();
}

/* showBackTrace() function to list the backtrace symbols obtained by backtrace() call */
void showBackTrace() {
const int maxbtsize = 50;
int btsize;
void* bt[maxbtsize];
char** strs = 0;
int i = 0;
/* Get the depth of backtraces available */
btsize = backtrace(bt, maxbtsize);
/* Get the symbols into 'strs' which is a char's double pointer */
strs = backtrace_symbols(bt, btsize);
/* Print the symbols obtained */
for (i = 0; i < btsize; i += 1) {
printf("%d.) %s\n", i, strs[i]);
}
free(strs);
}

Thanks.

Friday, August 5, 2011

Swapper

Many a times I have wondered how the idle time is calculated in a operating system. Though scheduler in every OS does the scheduling of every process that needs a share of processors time to get its butt kicked....... must have say in this. I wanted to know how it varies in every OS and my first step was to look in Linux. There came a component named Swapper, component naaaahhh......... its a process.

When scheduler got nothing to do I mean napping it still runs a process named as swapper or the idle process where is merrily takes a nap and keeps scheduling swapper till a sleepy hollow comes to break the nap, I mean a process.

I hope the sleepy story was good.

;?)

Startup scripts and customization of linux environment

As explained by my friend Karthi in an earlier post, /etc/init.d/ is a good place to start with start scripts.

I would like add my few cents here.
  • /etc/inittab is better place to start on basic linux needy components
  • can have startup scripts in /etc/rc.d/init.d
  • For intializing/customizing the system update rc.sysinit
;?)

Thursday, August 4, 2011

Dynamically loaded libraries


There are two types of libraries used: 1) static library (one with .a extn) and 2) shared libary (one with .so extn). The shared library can be included with the target executable in two ways, of which one way is to use libdl library functions. This is explained with an example below:

#include< stdio.h >
#include < stdlib.h >
#include < unistd.h >
#include < dlfcn.h >

/* The program uses shared library functions */
int main(int argc, char *argv[]) {
    void *dlh;
    int rc = 0;
/* Function pointer to hold the library functions */
    void (*fnstub)();
/* dlopen: opens the shared library,
RTLD_NOW: Flag instructs dlopen to resolve any symbols of the library before proceeding
RTLD_LAZY: Leaves undefined symbols if any
RTLD_GLOBAL: Informs all undefined symbols be resolved in subsequent dlopen */
    dlh = dlopen("./libmylib.so.1.0", RTLD_NOW);
    if (dlh == NULL) {
        printf("\nNot found");
    }
/* Fn ptr: 'fnstub' variable points to 'printfn' function */
    fnstub = dlsym(dlh, "printfn");
    if (!fnstub) {
        printf("\nFunc not fund: %s", dlerror());
    }
/* Call printfn function here */
    fnstub();
/* Close the object handle and terminate */
    dlclose(dlh);
    return(0);
}

How to compile:
gcc prog.c –ldl –ooutput_file
/* Include 'libdl' to compile this program */

Friday, July 29, 2011

Adding a startup script/service in Linux!

Startup root directory: /etc/init.d
Directory '/etc/rcX.d' holds list of services to be brought up during startup of runlevel 'X' and to be brought down during termination of runlevel 'X'.
Command: 'update-rc.d' is to modify this list or add our own custom executable shell script to be run during startup. Let us see how!
update-rc.d defaults: Registers our startup script.

update-rc.d -f apache remove: This forces the apache service to be removed from being invoked during startup.
update-rc.d apache defaults: This makes apache service to start with default priority.
update-rc.d apache defaults 90: This makes apache service to start at custom priority '90'.
update-rc.d apache 20 60: This starts apache at '20' priority and ends with '60' priority.
update-rc.d apache start 30 2 3 stop 40 4 5: This specifies different priority for different runlevels. Starts at '30' for runlevels 2 and 3, and stops at '40' for runlevels 4 & 5.
Thanks.

Monday, July 25, 2011

A code piece becomes a daemon!


Daemonize a process
A daemon is started either by the system itself or a user in a terminal or script. When it does start, the process is just like any other executable on the system. To make it truly autonomous, a child processmust be created where the actual code is executed. This is known as forking, and it uses the fork() function:
/* Include header */
#include < stdio.h >
#include < stdlib.h >

/* Include daemon properties with the running code */
static void daemonize(void)
{
    pid_t pid, sid;

    if ( getppid() == 1 ) return;

    pid = fork();
    if (pid < 0) {
        exit(1);
    }
    if (pid > 0) {
        exit(0);
    }
/* The fork() function returns either the process id (PID) of the child process (not equal to zero), or -1 on failure. If the process cannot fork a child, then the daemon should terminate right here.
If the PID returned from fork() did succeed, the parent process must exit gracefully. This may seem strange to anyone who hasn't seen it, but by forking, the child process continues the execution from here on out in the code. */
    umask(0);
/* In order to write to any files (including logs) created by the daemon, the file mode mask (umask) must be changed to ensure that they can be written to or read from properly */
    sid = setsid();
    if (sid < 0) {
        exit(1);
    }
/* The child process must get a unique SID from the kernel in order to operate. Otherwise, the child process becomes an orphan in the system. The pid_t type, declared in the previous section, is also used to create a new SID for the child process */
    if ((chdir("/")) < 0) {
        exit(0);
    }
 /* The current working directory should be changed to some place that is guaranteed to always be there. Since many Linux distributions do not completely follow the Linux Filesystem Hierarchy standard, the only directory that is guaranteed to be there is the root (/). We can do this using the chdir() function */
    freopen("/dev/null", "r", stdin);
    freopen("/dev/null", "w", stdout);
    freopen("/dev/null", "w", stderr);
/* Close the file descriptors as the daemon need not use the terminal */
}

/* Our running code */ 
int main( int argc, char *argv[]) {
/* Call the daemonize function to make this running code as daemon */
                daemonize();
                while (1) {
/* Endless looping to do our stuff autonomously */
                                sleep(10);
                }
    return 0;
}

Compile:  cc –o