Wednesday, December 2, 2015

Print Call stack where Exception Occure

Code: http://peerreview.in/code/s565f4c408bae0c31afe09543

#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#ifndef __USE_GNU
#define __USE_GNU
#endif
#include <iostream>
#include <execinfo.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ucontext.h>
#include <unistd.h>

/* This structure mirrors the one found in /usr/include/asm/ucontext.h */

typedef struct _sig_ucontext {
 unsigned long     uc_flags;
 struct ucontext   *uc_link;
 stack_t           uc_stack;
 struct sigcontext uc_mcontext;
 sigset_t          uc_sigmask;
} sig_ucontext_t;

void crit_err_hdlr(int sig_num, siginfo_t * info, void * ucontext)
{
 void *             array[50];
 void *             caller_address;
 char **            messages;
 int                size, i;
 sig_ucontext_t *   uc;

 uc = (sig_ucontext_t *)ucontext;

 /* Get the address at the time the signal was raised */
#if defined(__i386__) // gcc specific
 caller_address = (void *) uc->uc_mcontext.eip; // EIP: x86 specific
#elif defined(__x86_64__) // gcc specific
 caller_address = (void *) uc->uc_mcontext.rip; // RIP: x86_64 specific
#else
#error Unsupported architecture. // TODO: Add support for other arch.
#endif

 fprintf(stderr, "signal %d (%s), address is %p from %p\n",
  sig_num, strsignal(sig_num), info->si_addr,
  (void *)caller_address);

 size = backtrace(array, 50);

 /* overwrite sigaction with caller's address */
 array[1] = caller_address;

 messages = backtrace_symbols(array, size);

 /* skip first stack frame (points here) */
 for (i = 1; i < size && messages != NULL; ++i)
 {
  fprintf(stderr, "[bt]: (%d) %s\n", i, messages[i]);
 }

 free(messages);

 exit(EXIT_FAILURE);
}

int crash()
{
 char * p = NULL;
 *p = 0;
 return 0;
}

int foo4()
{
 crash();
 return 0;
}

int foo3()
{
 foo4();
 return 0;
}

int foo2()
{
 foo3();
 return 0;
}

int foo1 () noexcept
{
 foo2();
 return 0;
}

/* How to run:
g++ -rdynamic -std=c++11  NECB.cpp
./a.out
*/
int main(int argc, char ** argv)
{
 struct sigaction sigact;

 sigact.sa_sigaction = crit_err_hdlr;
 sigact.sa_flags = SA_RESTART | SA_SIGINFO;

 if (sigaction(SIGSEGV, &sigact, (struct sigaction *)NULL) != 0)
 {
    fprintf(stderr, "error setting signal handler for %d (%s)\n",
    SIGSEGV, strsignal(SIGSEGV));

     exit(EXIT_FAILURE);
 }
 foo1();
 exit(EXIT_SUCCESS);
}

Exception propagation and noexcept C++11

exception propagation and noexcept C++11
=======================================

Q1. what is exception propagation?
-------------------------------------------
An exception propagates from method to method, up the call stack, until it's caught. So if a() calls b(), which calls c(), which calls d(), and if d() throws an exception, the exception will propagate from d to c to b to a, unless one of these methods catches the exception.
#include<iostream>
using namespace std;

void d() {
    cout<<"d start\n";
    throw 42;
    cout<<"d ends\n";
}
void c() {
    cout<<"c start\n";
    d();
    cout<<"c ends\n";
}
void b() {
    cout<<"b start\n";
    c();
    cout<<"b ends\n";
}
void a() {
    cout<<"a start\n";
    b();
    cout<<"a ends\n";
}

int main()
{
    try{
        a();
    }
    catch(...){
        cout<<"catched";
    }
}

Run Code online: http://peerreview.in/code/s565f3cbe8bae0c31afe09541

What is Stack Unwinding in C++?
-------------------------------
The process of removing function entries from function call stack at run time is called Stack Unwinding. Stack Unwinding is generally related to Exception Handling. In C++, when an exception occurs, the function call stack is linearly searched for the exception handler, and all the entries before the function with exception handler are removed from the function call stack. So exception handling involves Stack Unwinding if exception is not handled in same function (where it is thrown).

In this code (Run Code online: http://peerreview.in/code/s565f3cbe8bae0c31afe09541) The ouput is have only start no end.
a start
b start
c start
d start
catched

Is detractor called when Stack Unwinding ?
---------------------------------------------
On a side note, if there were some local class objects inside f1() and f2(), destructor for those local objects would have been called in Stack Unwinding process. But pointers are not released.

http://peerreview.in/code/s565f3da38bae0c31afe09542

What is noexcept operator (since C++11)?
------------------------------------------- 
The noexcept operator performs a compile-time check that returns true if an expression is declared to not throw any exceptions. It can be used within a function template's noexcept specifier to declare that the function will throw exceptions for some types but not others.

Example:
// whether foo is declared noexcept depends on if the expression T() will throw any exceptions
template <class T>
void foo() noexcept(noexcept(T())) {}
void bar() noexcept(true) {}
void baz() noexcept { throw 42; }  // noexcept is the same as noexcept(true)
int main()
{
    foo<int>();  // noexcept(noexcept(int())) => noexcept(true), so this is fine
    bar();  // fine
    baz();  // compiles, but at runtime this calls std::terminate
}
Crash as:
Program received signal SIGABRT, Aborted.
0x00007ffff7747cc9 in __GI_raise (sig=sig@entry=6) at ../nptl/sysdeps/unix/sysv/linux/raise.c:56
#0  0x00007ffff7747cc9 in __GI_raise (sig=sig@entry=6) at ../nptl/sysdeps/unix/sysv/linux/raise.c:56
#1  0x00007ffff774b0d8 in __GI_abort () at abort.c:89
...

Code: http://peerreview.in/code/s565f38328bae0c31afe09540

Q1. When should we use this?
----------------------------------
If a function cannot throw an exception or if the program isn't written to handle exceptions thrown by a function, that function can be declared noexcept. For example:
Example 1: When we use ?
    extern "C" double sqrt(double) noexcept; // will never throw
Example 2: When we not use?
 vector<double> my_computation(const vector<double>& v) noexcept // I'm not prepared to handle memory exhaustion , This is an error
 {
  vector<double> res(v.size()); // might throw
  for(int i; i<v.size(); ++i) res[i] = sqrt(v[i]);
  return res;
 }

Q2. What happens if we declare noexcept but it throws?
---------------------------------------------------------
If a function declared noexcept throws (so that the exception tries to propagate from the noexcept function) the program is terminated (by a call to terminate()). The call of terminate() cannot rely on objects being in well-defined states (i.e. there is no guarantees that destructor have been invoked, no guaranteed stack unwinding, and no possibility for resuming the program as if no problem had been encountered). This is deliberate and makes noexcept a simple, crude, and very efficient mechanism (much more efficient than the old dynamic throw() mechanism).


Q3. How to  make a function conditionally noexcept?
-------------------------------------------------------

It is possibly to make a function conditionally noexcept. For example, an algorithm can be specified to be noexcept if (and only if) the operations it uses on a template argument are noexcept:

template<class T>
void do_f(vector<T>& v) noexcept(noexcept(f(v.at(0)))) // can throw if f(v.at(0)) can
 {
  for(int i; i<v.size(); ++i)
   v.at(i) = f(v.at(i));
 }
Here, I first use noexcept as an operator: noexcept(f(v.at(0))) is true if f(v.at(0)) can't throw, that is if the f() and at()used are noexcept.

Another Example:
int pop(int idx) noexcept(noexcept(idx > 0))
{
  if (idx <= 0)
    throw std::out_of_range("My array doesnt go that high");
  return idx;
}
Actually the noexept specification expects a constant expression, not a runtime expression. noexcept(idx >0) returns true as comparing two integers does not throw, The declaration <int pop(int idx) noexcept(noexcept(idx > 0))
: says this function does not throw as long as idx > 0 does not throw, which is always the case for an int.

Q4. What is noexcept operator?
------------------------------------
The noexcept() operator is a constant expression and does not evaluate its operand. The general form of anoexcept declaration is noexcept(expression) and ``plain noexcept'' is simply a shorthand for noexcept(true). All declarations of a function must have compatible noexcept specifications. A destructor shouldn't throw; a generated destructor is implicitly noexcept (independently of what code is in its body) if all of the members of its class have noexcept destructors. It is typically a bad idea to have a move operation throw, so declare those noexcept whereever possible. A generated copy or move operation is implicitly noexcept if all of the copy or move operations it uses on members of its class have noexcept destructors. noexcept is widely and systematically used in the standard library to improve performance and clarify requirements.

Wednesday, September 18, 2013

Installing Latex in Windows 7:

Step 1: Download  MiKTEX Download http://mirrors.ctan.org/systems/win32/miktex/setup/basic-miktex-2.8.3761.exe and Install it (PS : USE  Basic MiKTeX 2.8.3761 Installer)

Step 2: Install Taxmaker : Download  http://www.xm1math.net/texmaker/texmakerwin32_install.exe and Install .

Step 3: Run And excute.

NJoy :)

Friday, September 13, 2013

Git CookBook.

Dipankar's Git CookBook
--------
Q1. How to setting up GIT server ?

IN SERVER MACHINE DO THE FOLLOWING AND CREATE REPO (ONE TIME)

$ sudo adduser git
$ su git
$ cd
$ mkdir .ssh
cd ~/.ssh
ls
# Lists the files in your .ssh directory
git@dipankar-OptiPlex-390:~/.ssh$ ssh-keygen -t rsa -C "dutta.dipankar08@gmail.com"
Generating public/private rsa key pair.
Enter file in which to save the key (/home/git/.ssh/id_rsa): <Enter>
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/git/.ssh/id_rsa.
Your public key has been saved in /home/git/.ssh/id_rsa.pub.
The key fingerprint is:
68:b7:df:bc:78:15:84:e9:87:b2:da:75:26:b3:38:08 dutta.dipankar08@gmail.com
The key's randomart image is:
+--[ RSA 2048]----+
|             o   |
|            o .  |
|           . o   |
|       .  . o o  |
|      o S  o . . |
|     .E. .. + +  |
|       ..+ o B   |
|        o.++o    |
|          oo+.   |
+-----------------+
git@dipankar-OptiPlex-390:~/.ssh$ 
git@dipankar-OptiPlex-390:~/.ssh$ cat dipankar.pub 
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDq1iZ9XsfJdwECXSP6i4v5gRJIvtQh8M+udJAgcPiq+Hw7Kbz2cz14rkIG6lD0yOCJpKop8FeS9Z1CDNpZDafTgPYZmi6erIygh8Mwe/BHkp8hHzrg7u1nuEqq2UX6+MLMJB7gyhdqd9/mydDRPVtgAlmyejOOlgNRUpSuSBIa4AURslmeFbFfdLbDB0iLJhFU/rtJGYCBQckLdnQG+MsCv0pK3367eLkeCQR5sGoXvbUtgxpDiCJ4hNSipNeLssUoHWz1wbMnCqLERXaIHngMKEr3xruZ0D/MKkD1atw+3ijFWC1ErBpZbwfocJhCwAYZhA6KBButdLulzaZ58IJB dutta.dipankar08@gmail.com
git@dipankar-OptiPlex-390:~/.ssh
dipankar@dipankar-OptiPlex-390:/opt$ sudo chmod -r  777 git
chmod: cannot access `777': No such file or directory
dipankar@dipankar-OptiPlex-390:/opt$ sudo chmod 777 git
dipankar@dipankar-OptiPlex-390:/opt$ sudo chown git:git  git
dipankar@dipankar-OptiPlex-390:/opt$ ll
total 12
drwxr-xr-x  3 root root 4096 Sep 13 12:23 ./
drwxr-xr-x 28 root root 4096 Sep 13 12:33 ../
drwxrwxrwx  2 git  git  4096 Sep 13 12:52 git/
dipankar@dipankar-OptiPlex-390:/opt$ su git
root@dipankar-OptiPlex-390:/home/git/.ssh# mkdir /opt/git
root@dipankar-OptiPlex-390:/home/git/.ssh# cd /opt/git/
root@dipankar-OptiPlex-390:/opt/git# mkdir project.git
root@dipankar-OptiPlex-390:/opt/git# cd project.git/
root@dipankar-OptiPlex-390:/opt/git/project.git# git --bare init
Initialized empty Git repository in /opt/git/project.git/

IN REMOTE MACHINE DO THE FOLLOWING AND ADD YOUR EXISTING CODE (ONE TIME)

root@dipankar-OptiPlex-390:/opt/git/project.git# mkdir /dipankar
root@dipankar-OptiPlex-390:/opt/git/project.git# cd /dipankar/
root@dipankar-OptiPlex-390:/dipankar# ls
root@dipankar-OptiPlex-390:/dipankar# git clone git@10.12.4.125:/opt/git/project.git
Cloning into 'project'...
The authenticity of host '10.12.4.125 (10.12.4.125)' can't be established.
ECDSA key fingerprint is 93:ea:51:ca:6c:2e:0f:0b:55:63:a1:da:4f:c3:c6:e1.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '10.12.4.125' (ECDSA) to the list of known hosts.
git@10.12.4.125's password: 
warning: You appear to have cloned an empty repository.
root@dipankar-OptiPlex-390:/dipankar# 
root@dipankar-OptiPlex-390:/dipankar# ls 
project

root@dipankar-OptiPlex-390:/dipankar# cd project/

root@dipankar-OptiPlex-390:/dipankar/project# vim hello.txt
root@dipankar-OptiPlex-390:/dipankar/project# git status
# On branch master
#
# Initial commit
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
# hello.txt
nothing added to commit but untracked files present (use "git add" to track)
root@dipankar-OptiPlex-390:/dipankar/project# git add hello.txt 
root@dipankar-OptiPlex-390:/dipankar/project# git status
# On branch master
#
# Initial commit
#
# Changes to be committed:
#   (use "git rm --cached <file>..." to unstage)
#
# new file:   hello.txt
#
root@dipankar-OptiPlex-390:/dipankar/project# git diff

root@dipankar-OptiPlex-390:/dipankar/project# git commit -m " First Commit " 
[master (root-commit) d8bc11a]  First Commit
 1 file changed, 1 insertion(+)
 create mode 100644 hello.txt
[root@ravi project]# git remote rm origin
[root@ravi project]# git remote add origin git@10.12.4.125:/opt/git/project.git
[root@ravi project]# git push origin master
git@10.12.4.125's password: 
Counting objects: 3, done.
Writing objects: 100% (3/3), 196 bytes, done.
Total 3 (delta 0), reused 0 (delta 0)
To git@10.12.4.125:/opt/git/project.git
 * [new branch]      master -> master
[root@ravi project]# git status
# On branch master
nothing to commit (working directory clean)
[root@ravi project]#

Wednesday, August 14, 2013

How to build a modified kernel on Fedora?


When you compile your Linux kernel in your Fedora, most dependencies should not trouble you. So, what you need to do is just the follow steps:
  • Download kernel source from either kernel.org or github; usually a tar.gz file.
    • wget https://www.kernel.org/pub/linux/kernel/v3.x/linux-3.4.44.tar.gz
  • Extract the kernel file to some directory (e.g. your home directory).
    • tar -xvf linux-3.4.44.tar.gz
  • Configure the kernel. This is the most important step I suppose. You can use your old .config file which is in /usr/src/linux using the make oldconfig command, or you can configure it all by yourself using the make menuconfig command. If you need some GUI tools, you need to install some extra packages, Both Qt based and GTK based GUI are available. In fact, the most important and often dangerous step is, how to get the right drivers and how to make sure you really need a kernel function or not.
    •  make menuconfig
  • if gcc is not installed: install gcc using command :->yum install gcc .
    if ncurses-devel not installed: install it using :-> yum install ncurses-devel  .
  •  compile 
    • make
    • make modules
    • make install. For most new kernel, we needn't run make modules_install any more.
  • Put the kernel image into the boot directory and edit the grub menulist.
  • Reboot your system, your kernel will work!
    • reboot
References:
 [1] Linux Kernel in a Nutshell by Greg Kroah-Hartman (O'Reilly) http://mastermac.free.fr/vrac/lkn.pdf

Wednesday, January 30, 2013

Make you Java Life Easy with JDB

Finding Issue or a root cause of a bug  by adding system.out.println() is very boring task: as you need to add debug line, compile, run, test and at end delete bedug  line, when u added. Even more if you run ur Java program via some Environment ( Like Amazon ) , it;s simple waste your time., as it need significant activation time.

Java provide a easier way to debug your java program on fly.
The Java Debugger, jdb, is a simple command-line debugger for Java classes. It is a demonstration of the Java Platform Debugger Architecture that provides inspection and debugging of a local or remote Java Virtual Machine.

Most Useful command is as below :

Table 1. Step Commands
Jdb  ItemEmacs Commandjdb CommandDescription
Step Overjde-bug-step-overnextAdvance to the next line in the current method, stepping over any lines that invoke other methods.
Step Intojde-debug-step-intostepAdvance to the next line in the program.
Step Outjde-debug-step-outstep upAdvance to the next line in the method that invoked the current method.
Continuejde-debug-contcontAdvance to the next breakpoint or to the end of the program, whichever comes first.


Example :


stop at com.dipankar.kharbandhi.midnapur.services.codebase.impl.HelloWorld:72
After that Hit homepage or any other page
1) See the current Locals value - "dump this"
2) Set to new value - "print setWeblabOverride("Pass Value")"
3) See the new value - "dump this"
4) Continue - "cont"

========================================================================

Full list of commend as below: 

dipankar@superstar] ./jdb -attach edipankar.com:8000            
/jdk1.6.0/bin
Set uncaught java.lang.Throwable
Set deferred uncaught java.lang.Throwable
Initializing jdb ...
> help
** command list **
connectors                -- list available connectors and transports in this VM

run [class [args]]        -- start execution of application's main class

threads [threadgroup]     -- list threads
thread <thread id>        -- set default thread
suspend [thread id(s)]    -- suspend threads (default: all)
resume [thread id(s)]     -- resume threads (default: all)
where [<thread id> | all] -- dump a thread's stack
wherei [<thread id> | all]-- dump a thread's stack, with pc info
up [n frames]             -- move up a thread's stack
down [n frames]           -- move down a thread's stack
kill <thread id> <expr>   -- kill a thread with the given exception object
interrupt <thread id>     -- interrupt a thread

print <expr>              -- print value of expression
dump <expr>               -- print all object information
eval <expr>               -- evaluate expression (same as print)
set <lvalue> = <expr>     -- assign new value to field/variable/array element
locals                    -- print all local variables in current stack frame

classes                   -- list currently known classes
class <class id>          -- show details of named class
methods <class id>        -- list a class's methods
fields <class id>         -- list a class's fields

threadgroups              -- list threadgroups
threadgroup <name>        -- set current threadgroup

stop in <class id>.<method>[(argument_type,...)]
                          -- set a breakpoint in a method
stop at <class id>:<line> -- set a breakpoint at a line
clear <class id>.<method>[(argument_type,...)]
                          -- clear a breakpoint in a method
clear <class id>:<line>   -- clear a breakpoint at a line
clear                     -- list breakpoints
catch [uncaught|caught|all] <class id>|<class pattern>
                          -- break when specified exception occurs
ignore [uncaught|caught|all] <class id>|<class pattern>
                          -- cancel 'catch' for the specified exception
watch [access|all] <class id>.<field name>
                          -- watch access/modifications to a field
unwatch [access|all] <class id>.<field name>
                          -- discontinue watching access/modifications to a field
trace [go] methods [thread]
                          -- trace method entries and exits.
                          -- All threads are suspended unless 'go' is specified
trace [go] method exit | exits [thread]
                          -- trace the current method's exit, or all methods' exits
                          -- All threads are suspended unless 'go' is specified
untrace [methods]         -- stop tracing method entrys and/or exits
step                      -- execute current line
step up                   -- execute until the current method returns to its caller
stepi                     -- execute current instruction
next                      -- step one line (step OVER calls)
cont                      -- continue execution from breakpoint

list [line number|method] -- print source code
use (or sourcepath) [source file path]
                          -- display or change the source path
exclude [<class pattern>, ... | "none"]
                          -- do not report step or method events for specified classes
classpath                 -- print classpath info from target VM

monitor <command>         -- execute command each time the program stops
monitor                   -- list monitors
unmonitor <monitor#>      -- delete a monitor
read <filename>           -- read and execute a command file

lock <expr>               -- print lock info for an object
threadlocks [thread id]   -- print lock info for a thread

pop                       -- pop the stack through and including the current frame
reenter                   -- same as pop, but current frame is reentered
redefine <class id> <class file name>
                          -- redefine the code for a class

disablegc <expr>          -- prevent garbage collection of an object
enablegc <expr>           -- permit garbage collection of an object

!!                        -- repeat last command
<n> <command>             -- repeat command n times
# <command>               -- discard (no-op)
help (or ?)               -- list commands
version                   -- print version information
exit (or quit)            -- exit debugger

<class id>: a full class name with package qualifiers
<class pattern>: a class name with a leading or trailing wildcard ('*')
<thread id>: thread number as reported in the 'threads' command
<expr>: a Java(tm) Programming Language expression.
Most common syntax is supported.

Startup commands can be placed in either "jdb.ini" or ".jdbrc"
in user.home or user.dir

Njoy -- *DD*

Monday, April 30, 2012

How to Block FB / FaceBook from your Laptop


1. put the following line in host file.
Path : C:\WINDOWS\system32\drivers\etc

2. Edit this line and add the following line at end..
---------------------------------------------
74.125.79.94 www.facebook.com
74.125.79.94 facebook.com
74.125.79.94 static.ak.fbcdn.net
74.125.79.94 www.static.ak.fbcdn.net
74.125.79.94 login.facebook.com
74.125.79.94 www.login.facebook.com
74.125.79.94 fbcdn.net
74.125.79.94 www.fbcdn.net
74.125.79.94 fbcdn.com
74.125.79.94 www.fbcdn.com
74.125.79.94 static.ak.connect.facebook.com
74.125.79.94 www.static.ak.connect.facebook.com

------------------------------------------------------

Cheers
Dipankar