Thursday, March 31, 2016

I am obsessed with GOD


I am getting unhealthy obsession with GOD. In the quest to find someone whose existence can't be proved, I fear that I might be alienated from the humans, who do exist.

Its like waiting for one phantom love , which you thought is made for you and ignoring the real persons around you.

But humans and GOD go hand in hand. One can't exist without other.

I recently watched SUPERMAN vs BATMAN. And I loved it, because rather than having high dose of ACTION ( like MARVELL MOVIES) , it deals more with emotions of powerful man.

Lex Luthor said something in that movie which makes your think.  " If GOD is all-powerful, he can't be all-good  and if he is all-good, he can't be all-powerful".

Now how we will measure goodness and power, when we will say that a person is almighty ?

Suppose there is GOD and he is all-good, then he will try to be as fair as possible. But is it possible that all humans will be satisfied ? No , because we have are own emotions and we are selfish.

Now say if 1 in millions don't believe GOD to be all powerful or good, then he can't be all good or powerful.

Its like DEMOCRACY ,  he majority doesn't believe you to be GOOD, then you can't WIN even if you are most unselfish , most emphatic heart out there.


Now do we really want GOD to acknowledge himself ? What will happen if he in reality exist and he proved. 

What is much better -  to believe in someone all mighty , but who is just a belief which can be changed.   OR  having a reality who can do whatever he/she likes.

Maybe we will have chaos, if GOD really exist.  Lets take a scenario.

> GOD exist, he comes and says he is GOD.

> HUMANS : Which religion you belong to ?

> GOD : There is nothing called religion, this is made by you to simply mislead one another. From today there will be no religion, no need to worship me also.

> HUMANS : okay.......this is liberating...we don't have to do things in name of religion. But what if we want you to fulfill our wishes  or if we if feel guilty about something and want forgiveness.

And will you stop something bad from happening ??

> GOD : Its not so easy....there are some wishes which can't be granted...for example if you say GOD made me rich...thats not possible ...I can't make everyone rich ,,,..same way if you have divided yourself on basis of countries and want to win against each other.. How can I grant wish of both parties.

About forgiveness and stopping something bad : First of all we need to define what is bad. If we go by my definition of GOOD/BAD and I stopped everything bad to happen , then FORGIVENESS will not come to picture.  And if it does, that means I allowed something BAD to happen  which will raise questions on my AL-MIGHTINESS.

> HUMANS : Why we want you to exist ?

> GOD : Because you need me ...................................there are some things which you can easily do and don't remember me for those things..........but then there are something which you find hard to do...hard to fathom ...as a  respite...as an excuse  you want me

You humans always want to understand everything ..you want to know about past and also the future.
You can never believe that things happen simply without reason. You are creating paradoxes of your own.


What will happen if all of you becomes totally like each other. No one more beautiful than other, every one having same amount of money ?

-----------------------------------------------------FOOT NOTE------------------------------------------------

As a writer, I don't know the answer of last question ?





Wednesday, March 30, 2016

Sockets : Finally they unraveled themselves : Part 1


Socket programming was something, I was always interested in. But Now when i look back in my college years , I realized that nothing was taught which could have been practical. The teaching situation in india is quite bad.

If internet would have not come, we would still be lagging behind a lot.

Also I am very lazy, until and unless there is no external force, my inertia of rest doesn't allow me to work.


But past is past...behold ..the future is bright.............

Rather than having detailed techincal discussion about them, we will see there overview and then see Android Programming.


1) OSI layer :  If anyone has ever taken any networking course, they know about OSI layer. Below is the diagram



Now , in the above diagram SOCKETS fall between Transport and Session Layer. 
Transport Layer has TCP/UDP.\
 Internet Layer has IP. 

To communicate between any two devices, we need IP address. But what is multiple applications on one device are communicating with other device.  In that case we need PORT, which helps in distinguish traffic flow. 

SOCKET are combination of IP address and PORT, (APPLICATION/Presentation/Session) Layer opens SOCKET with Transport Layer and then all data is read/write from this socket. 


So now we know what is socket and how transfer can be done. Lets see what are API available in Android/Java library to open,close,read,write from a SOCKET. 

Also most of data transfer happening on internet or most of the Android apps we see are based on Server-Client architecture. 

A client will periodic check with Server if some new data is available from him, and will post if any data needs to be posted by Client to Server. 

So if you visualize , Client should know Server IP address, but if Server do not know Client IP address , it will be fine, as onus is on Client and not server. 


So the life - cycle of SOCKET is like below 




1) You create a socket on SERVER using a PORT ID.  ( Note depending on language and platform you are working on , you might also have to BIND the socket to Server IP address)

2) Then SERVER is constantly listening to any NEW CONNECTION coming. 

3) At CLIENT side, we also create socket. NOTE : the use of client side socket is to communicate with SERVER, hence the IP address and PORT no which we provides here is of SERVER.

4) Then CLIENT tries to connect to SERVER. 

5) SEVER once gets CLIENT request, accepts it.

6) Now we have communication link open and data can be transferred between SERVER and CLIENT.

7) Finally we close the connection. 

Now a bit of  Operating System .  If you see SERVER functions design wise, SERVER has to listen to new CLIENT request and also needs to communicate with existing CLIENT, hence we have to need two different THREADS, since both of these functions need to work in parallel. 



Now in Android, we use 

1)  ServerSocket serverSocket  = new ServerSocket(port_no);

    // This is to create Server side socket 

2 and 5) Socket socket_c = serverSocket.accept();

    // This is use to accept client connection, now using socket_c we can communicate with Client, NOTE : we don't use serverSocket to communicate with client, that is only used to listen and accept client connections. Once client connection is accepted, further communication is done using the client socket created at server side for each client.


3 and 4)  socket = new Socket(Server IP address, Server Port);

   // This is used to create socket at client side. This only will also try to connect to server, no other function needs to be called explicitly.



6 ) InputStream inputStream = socket.getInputStream(); 

     // This is used to read data coming to socket, irrespective of socket at server or client side.

    OutputStream outputStream = socket.getOutputStream(); 
    PrintStream printStream = new PrintStream(outputStream);
    printStream.print("data to be send in string format");

    // Below commands are needed to write data into socket.


Viola,  we are almost there. 

So in next post we will see Android App code , as it will also involve thread. 



Saturday, March 26, 2016

Life : Why we fear to take full control of it



Well ..as it happens most of time...after spending 1-2 weeks as normal human being..I get overwhelmed by the emotions which i see around myself...and to get over this hangover , I have to isolate myself and think about the most puzzling thing which have been at the centerstage since adam and eve.


What is life ...Who we are ...What is happiness ..and how to live life..

Everything which we consider right or wrong ..is simply what we were feed from the start. What is all that is lie... Animals kill each other ..they are infidel...they are not virtuous..yet they also live

I have seen humans rule changes as per time and place...lot of things which were considered INCORRECT by the society , has changed. And there is no guarantee that it will not change in future.

So how in this world, should i live his life. Should I do whatever it pleases him, without consideration of anyone else. If i am happy doing something, will it matter what other thinks of me.

All the big industrialist / money-makers have not earn money by 100% morally. Because you can't. When results do not depend entirely on you, to get best results you have to think just about yourself.

Same way I am listening to lot of breakups happening in bollywood now a days, What is this ?
Suddenly after spending 3-4 years , people are realizing that they are not compatible.

Can you really spend your life with only one person ? How can you be sure that he/she loves you as much as we do.  We can simply believe , there is absolutely nothing else on whose basis we can make a conclusion.  If you believe other person to be faithful, it doesn't matter what you see or hear. You can always make  yourself to believe in any lies. Same way if you don't want to believe ..nothing can be done .

So you see, its in our control how we live our life....but even then we tend to give away the control to others ...parents, bosses, loved ones.


I say when we have to live in a world concocted by lies , its better to live in our own lies.
Lets do what we want to do ...if nothing else...mayb atleast we will know in the end if GOD exist or its is biggest myth of all times.


Friday, March 25, 2016

ValGrind : It's leaking :)


Those of you who haven't heard about ValGrind : It is Gates of Death or gates of Valhalla in Norse Mythology.

I just love mythology.  I am not sure, how true it is , but for the time humans were born it existed.
It is our fear , our love , our redemption.

Its changes as humans changes, it is ever evolving.

But this post is not about Gates of Valhalla. ( Does Max max : Fury Road) rings a bell

This post is about second ValGrind : Which is debugging tool suite, It has one tool called MEMCHECK, which helps in checking if your C or C++ program is leaking memory.

Now in the older post, we have seen how to debug crash and know why your program crashed. But seriously, we will not always wait for our program to crash. So we use Memcheck to see if our program gotta piss or not.


1) If you want to use something, you need to have it.  So install it first on your linux machine. Pretty easy. Simply run

> sudo apt-get install valgrind. 

2) I will take the example, where my .C file is  crash.c and my program is crash. To run on this you have to give below command.

> valgrind --tool=memcheck --leak-check=full ./crash

Now what happens is that the output of this command will come on your terminal and which is not easy to read.

So better put that into some file  say "val.txt".

> valgrind --tool=memcheeck --leak-check=full -log-file="val.txt" ./crash


now for my below code, the valgrind output was

Crash.c file 

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

void voldemort(int *);

int main()
{
   int *hp;
   hp=(int *)malloc(sizeof(int)*1);
   voldemort(hp);
  // free(hp);
}

void voldemort(int *hp)
{
  int *temp;
  temp = hp;
  *temp=2; 
  hp=NULL;
  *hp=10;

}


Valgrind output

==8949== Memcheck, a memory error detector
==8949== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al.
==8949== Using Valgrind-3.10.0.SVN and LibVEX; rerun with -h for copyright info
==8949== Command: ./crash
==8949== Parent PID: 5602
==8949== 
==8949== Invalid write of size 4
==8949==    at 0x8048463: voldemort (crash.c:20)
==8949==    by 0x8048441: main (crash.c:10)
==8949==  Address 0x0 is not stack'd, malloc'd or (recently) free'd
==8949== 
==8949== 

==8949== Process terminating with default action of signal 11 (SIGSEGV): dumping core

So if you see , it is telling that at line 20 , there is invalid write. which if we see in crash.c file is correct, and we can modify our program to handle it.


So thats it ...

PLUG the LEAK

Tuesday, March 22, 2016

Core Dump : part 2


In last post, we saw about GDB, and BT . In this post we will work 1-2 more functions

So let see for below code. 

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

void voldemort(int *);

int main()
{
   int *hp;
   hp=(int *)malloc(sizeof(int)*1);
   free(hp);
   voldemort(hp);
}

void voldemort(int *hp)
{
  free(hp);
}

On running I got below error

*** Error in `./crash': double free or corruption (fasttop): 0x0a04b008 ***
Aborted (core dumped)

This is my gdb - bt message

#0  0xb76df424 in __kernel_vsyscall ()
#1  0xb7548827 in __GI_raise (sig=sig@entry=6)
    at ../nptl/sysdeps/unix/sysv/linux/raise.c:56
#2  0xb754bc53 in __GI_abort () at abort.c:89
#3  0xb7583993 in __libc_message (do_abort=do_abort@entry=1,
    fmt=fmt@entry=0xb7680a5c "*** Error in `%s': %s: 0x%s ***\n")
    at ../sysdeps/posix/libc_fatal.c:175
#4  0xb758de7a in malloc_printerr (action=<optimized out>,
    str=0xb7680c20 "double free or corruption (fasttop)", ptr=0xa04b008)
    at malloc.c:4996
#5  0xb758eaed in _int_free (av=0xb76c5420 <main_arena>,
    p=<optimized out>, have_lock=0) at malloc.c:3840
#6  0x08048491 in voldemort ()
#7  0x0804847e in main ()

As we can see at step 4, double corruption has taken place. 
And in step 5 , we have called  system function and Step 4 is Voldemort . 

So we got function in which error has occurred.


One more example:

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

void voldemort(int *);

int main()
{
   int *hp;
   hp=(int *)malloc(sizeof(int)*1);
   voldemort(hp);
  // free(hp);
}

void voldemort(int *hp)
{
  int *temp;
  temp = hp;
  *temp=2; 
  hp=NULL;
  *hp=10; 
 
}

On running this I got 
 Segmentation fault (core dumped)

gdb-bt  output is 

Program terminated with signal SIGSEGV, Segmentation fault.
#0  0x08048463 in voldemort ()
(gdb) bt
#0  0x08048463 in voldemort ()
#1  0x08048442 in main ()


So as you can see with different type of signal , information can change a bit.

now we know Voldemort is bad guy and causing crash. So we need to check voldemort in detail.


Now if you have noted , then we can see that in front of every fucntion there is one number. To go inside a function we need that number with frame cmd. Example to go inside voldemort, we have to on gdb type below 

(gdb) frame 0                              // this will select this function, then we can use further gdb cmds                                                          list,   info locals

but when I typed, I ran into an error 'SYMBOL table info not available'. This is because at the time of building I have not enabled debugger option.

So I need to use that , like below .   crash.c  is my .c file name, crash will be name of my executable.

> gcc -g -o crash crash.c

Now when I run ./crash , in crashed as expected.  now after running gdb on it .

It automatically gave me line number where crash is happening. AWESOME

#0  0x08048463 in voldemort (hp=0x0) at crash.c:20
#1  0x08048442 in main () at crash.c:10

But to continue our tute, lets select this function

(gdb) frame 0
(gdb) list                    // list the function code
(gdb) info locals          // gives details about local variables.

For my function, below is details


(gdb) frame 0
#0  0x08048463 in voldemort (hp=0x0) at crash.c:20
20  *hp=10;
(gdb) list
15 {
16  int *temp;
17  temp = hp;
18  *temp=2;
19  hp=NULL;
20  *hp=10;
21
22
23 }
(gdb) info locals
temp = 0xa04b008
(gdb)

Now , we have seen that how can be debug crash dump using gdb.  
To quit gdb, simply paste q

But still lot needs to be debugged, like  what are memory address and what are values stored in them.
useful when crash is not happening, but answer is not as expected. 

that we will see in further tutes.

Core Dump : part 1


Well ...if u spend significant time on learning one language and slowly slowly or quickly depending on how much you are interested in that language ..you will try to see its different facets of that language.

So since I mostly work on C, I use to see lot of segmentation fault happening when writing program related to pointers or stackoverflow.  In all these cases COREDUMPS are generated, which tells memory wise what went wrong.

Now , mostly I don't use to see this, but go back to program and try to figure out what went wrong.

This works if your program is 1-2 files only and simple. Else its very hard to know why crash happened.

So i started to read about how to check core-dump in gcc.

Below is what i learned.

1) Is core dump getting generated ? 

Even though your gcc will say core dump is generated, but you will see it is not present. It happens because your SHELL doesn't have permission to generated coredump by default.

hence you have to run below command.

> ulimit -c unlimited.

NOTE : ulimit is shell property, so when you start running your program you have to run above cmd first. So any program then run on that will generate core dump.

2) Checking Core Dump#

1) Run below cmd :  
gdb <executable> <core-file> or gdb <executable> -c <core-file>

Example I have c file name crash.c and core dump generated name is core, so i will run

> gdb ./crash core

This will give some information on my screen.

My .c program was

#include<stdio.h> #include<stdlib.h> int main() { int p[0]; int b=10; p[0];//=(int*) malloc(sizeof(int)*1); printf("b %d\n",b); printf("%p %p %p",&b,&p[0],&p[1]); p[1]=20; printf("b %d\n",b); free(p); // This is point where crash should occur //p=&b; }


Output of running cmd which mentioned below is

Core was generated by `./crash'. Program terminated with signal SIGABRT, Aborted. #0 0xb76df424 in __kernel_vsyscall ()


So as you can see with above message, you cannot do any shit with your program. Hence you have to use gdb next command -- bt . It stands for backtrace and prints the stack of program.

when i run bt below thing I got

(gdb) bt

#0  0xb76df424 in __kernel_vsyscall ()
#1  0xb7548827 in __GI_raise (sig=sig@entry=6)
    at ../nptl/sysdeps/unix/sysv/linux/raise.c:56
#2  0xb754bc53 in __GI_abort () at abort.c:89
#3  0xb7583993 in __libc_message (do_abort=do_abort@entry=1, 
    fmt=fmt@entry=0xb7680a5c "*** Error in `%s': %s: 0x%s ***\n")
    at ../sysdeps/posix/libc_fatal.c:175
#4  0xb758de7a in malloc_printerr (action=<optimized out>, 
    str=0xb767c56d "free(): invalid pointer", ptr=0xbf7fc108)
    at malloc.c:4996
#5  0xb758eaed in _int_free (av=0xb76c5420 <main_arena>, 
    p=<optimized out>, have_lock=0) at malloc.c:3840
#6  0x080484c1 in main ()

As you can see, something makes a bit sense now.
Since stack is LIFO, the first line ( from last) tells as what was function entered in which we had crash, it was MAIN().

now, when we called free, it defination would hav been in malloc.c , since it is pointed next.

Line 4 is telling as 'free() : invalid pointer' so we can see our pointer there and can see that it is not correct.

Voila our program is debugged. In next tute , we will see more better code.

Sunday, March 20, 2016

UART : Arduino : Serial Port


I got a new Arduino Uno .........:):):)

So first thing I started is to get the BLINK program which comes as part of examples to run.

Now as thing stand, whenever u tend to do things by urself u will run into lot of questions.

So I am not sure how I came to read about UART, but I did and below are things as per my understanding.




UART is software component which tells how to transmit data.

Ex : Mostly UART uses 10 bit frame structure, which can send 8 bit of data.
       or 11 bit , where 1 bit is parity bit.

2 extra bit are STARTING BIT , which is marked by LOW VOLTAGE and
                       STOP BIT , marked by HIGH VOLTAGE.

We will have BAUD RATE, which tells no of bits can be send per second. Most common is 9600.

So we can send 960 frames ( 10-bit frame) each second. or 960 octects of data in 1 second using UART with baud rate of 9600.

BAUD RATE is property of BAUD GENERATOR, which is an oscillator, with a particular frequency.

Formula  of baud rate :

Frequency / (16*(spbrg+1))   // spbrg here is register value of baud rate generator register. 

Basically depending on the BAUD RATE we need, we set spbrg for a particular frequency. 

there is one function I get from net, which will be in the library of microcontroller u are buying. 

OpenUSART(para1,para2,para3,para4,para5,para6)

here para6 is value of spbrg.  and para4 tell 8 bit data transmission.  REST can be get from internet

We also have to assign MICROCONTROLLER one port as INPUT and one as OUTPUT.

So now we know FRAME structure and how to set spbrg programmatically. Doing this we can tell microcontroller to send / receive data using UART.

Good Link : https://www.youtube.com/watch?v=py3HpisbJEY



Now coming to 2nd part . This will be brief

UART was the software part. The hardware/PHY part which converts signals and send them across can be RS-232 or TTL.

Most microcontrollers with UART uses TTL (Transistor-transistor Logic) level UART.
he TTL level UART is commonly used in the communications between microcontrollers and ICs. Only 2 wires are required for the full duplex communications.It is the simplest form of UART. Both logic 1 and 0 are represented by 5V and 0V respectively.



RS-232 (Recommended Standard 232) is a standard for serial binary data signals connecting between a Data Terminal Equipment (DTE) and a Data Communication Equipment (DCE).


GOOD LINK:
 http://tutorial.cytron.com.my/2012/02/16/uart-universal-asynchronous-receiver-and-transmitter/