memory leaks C++ using umdh.exe windows

do you have a app or server process that has to run continuously..and are you running out of memory . then there is memory leak.

track the private bytes of process and see whether the private bytes are increasing through out the time. Private bytes are amount of physical RAM being used by the process. a 32 bit process cant go beyond 2 GB of RAM on windows . it can reach to 3 GB if /3GB flag is specified in C:\boot.ini .

so lets use USER MODE DUMP HEAP (UMDH.exe)  to debug memory leaks .

Steps to use umdh

1)  Download debugging tools for windows from here and install them
     http://www.microsoft.com/whdc/devtools/debugging/installx86.mspx#b

set environment variable _NT_SYMBOL_PATH.
set _NT_SYMBOL_PATH= SRV*c:\localsymbols*http://msdl.microsoft.com/download/symbols;.


for example if my c++ program is there in C:\binutils\ then give 
SRV*f:\localsymbols*http://msdl.microsoft.com/download/symbols;C:\binutils which has the .pdb files for your program. 


2) launch gflags.exe from C:\Program Files\Debugging Tools for Windows (x86)

   in the image tab, give the application name for which you want to collect leak info. we need to collect stacktrace info for this application . press tab and tick the mark for collecting stack traces.

here is the sample screenshot of gflags.exe for program.exe which is c++ app.


click apply and restart  your program. you need to restart  your program to reflect these changes.

in this example we need to restart program.exe for which i need to collect stack traces.

we can also enable user mode stack tracing for process using gflags.exe -i program.exe +ust .

+ust means enabling stack tracing

-ust means disabling stack tracing .

-i is for image name. in this case my C++ app is program.exe

step 3:

in 3rd step you need to collect heap dump using umdh.exe .
umdh.exe -g -pn:program.exe -f :dump1.txt gives the heap dump of process program.exe .

-g is option to find unreferenced memory blocks in process. its like we allocate memory using pointers again and again and forgot to free it. then the memory is not referenced any more .

-pn is option to attach umdh.exe by process name. here my process name would be program.exe

-f is for output file to which we want to write heap dumps.

step 4:
do your operations on program.exe or let your program.exe run for more time and take other heap dump.
umdh.exe -g -pn:program.exe -f :dump2.txt . so we have 2 dumps now. 


step 5:


take the diff of two dumps. this gives the increase in heap figures. umdh can also give diff between 
two dumps. 


umdh.exe -d dump1.txt dump2.txt > summary.txt . 


the above command gives diff between two dumps. the summary.txt will have this info :
memory increase in bytes and corresponding call stack which a programmer needs.


The sample summary.txt will have the following format. I attached the snapshot here


try umdh.exe for finding leaks .

many developers forgot to restart their programs after setting gflags.exe , in such cases we dont get call stacks, this is point to remember.

Introduction to Network Security

why do we need network security ? . becoz we often share confidential information, we often do many money/business transactions etc. we don't want some one to interpret our data that is sent thru internet.

according to statistics the number of hacking incidents reported in 2003,2004 are high . the intruder knowledge has become very skillful. 

Lets discuss about the security attacks: 
Security attacks are of 2 types 1)passive attack 2)active attack.  . 

the security threat could be a hacker or a virus/worm that gets executed automatically

The Passive Attack:
the passive attack is nothing but the hacker just interprets the data sent through the network. but there will be no modification of data. detecting these kinds of attack is tricky. 

if peer A is sending data to peer B, if the hacker just observes the data being passed between these 2 peers, then the attack is said to be passive attack. 

observing traffic pattern,is 2nd type of passive attack. the intruder observes the traffic flow in  network.

Suppose that we had a way of masking the contents of messages or other information traffic so that opponents, even if they captured the message, could not extract  the information from the message. 

The common technique for masking contents is encryption. If we had encryption protection in place, an opponent might still be able to observe the pattern of these messages. The opponent could determine the location and identity of communicating hosts and could observe the frequency and length of messages being exchanged. This information might be useful in guessing the nature of the communication that was taking place.
Passive attacks are very difficult to detect because they do not involve any alteration of the data. Typically, the message traffic is sent and received in an apparently normal fashion and neither the sender nor receiver is aware that a third party has read the messages or observed the traffic pattern. However, it is feasible to prevent the success of these attacks, usually by means of encryption. 

Thus, the emphasis in dealing with passive attacks is on prevention rather than detection.

the 2nd type of security attacks is Active Attack:

the active attack involves modification of data or creation of false data sent thru network by hacker . there are 4 types in this 
a)masquerade 2)replay of messages 3)modification of messages 4) denial of service. 

lets discuss about these attacks.

masquerade: in this, the hacker pretends to be a different entity.one entity tries to behave as different entity. suppose peer A sends confidential data to peer B, then the hacker pretends to be a peer B and gets the confidential data from peer A .


For example, authentication sequences can be captured and replayed after a valid authentication sequence
has taken place, thus enabling an authorized entity with few privileges to obtain extra privileges by impersonating an entity that has those privileges.


replay of messages:  in this attack, the hacker gets the passive information from sender and observes them, later replays the messages to receiver.

modificiation of message:  In this the intruder modifies the message that has been sent thru network from host A to host B. when host A sends message "Give Admin rights to steves" to host B, the intruder can capture this and modifies as "Give Admin rights to parker" and sends to receiver host B.

denial of service:  the denial of service prevents or inhibits the normal use or management of communication facilites. example may include , the inrtuder attacks the network hosts by degrading its performance by sending overwhelming requests.  

TCP protocol

Introduction:

 First, TCP provides connections between clients and servers. A TCP client establishes a connection with a given server, exchanges data with that server across the connection, and then terminates the connection.
TCP also provides reliability. When TCP sends data to the other end, it requires an acknowledgment in return. If an acknowledgment is not received, TCP automatically retransmits the data and waits a longer amount of time. After some number of retransmissions, TCP will give up, with the total amount of time spent trying to send data typically between 4 and 10 minutes (depending on the implementation).

TCP Connection establishment:

TCP has a three way hand shake for connection establishment .

1) a client will send connection request to server. this is called (synchronize) SYN segment
2) server responds to SYN segment with Acknowledgement . this is called SYN + ACK segment.
3) when client receives ACK from server, it establishes connection.

to implement tcp 3 way handshake 

1) a server should bind to the port and should  listen for incoming connections. this is done by using socket,bind,listen calls from socket library
2) client calls connect()n which sends SYN segment to server.which tells the server the client's initial sequence number for the data that the client will send on the connection
3)The server must acknowledge (ACK) the client's SYN and the server must also send its own SYN containing the initial sequence number for the data that the server will send on the connection. The server sends its SYN and the ACK of the client's SYN in a single segment.
4)The client must acknowledge the server's SYN.

Picture of 3 way handshake: click to enlarge.




Note that TCP does not guarantee that the data will be received by the other endpoint, as this is impossible. It delivers data to the other endpoint if possible, and notifies the user (by giving up on retransmissions and breaking the connection) if it is not possible. Therefore, TCP cannot be described as a 100% reliable protocol; it provides reliable delivery of data or reliable notification of failure.
TCP contains algorithms to estimate the round-trip time (RTT) between a client and server dynamically so that it knows how long to wait for an acknowledgment. For example, the RTT on a LAN can be milliseconds while across a WAN, it can be seconds. Furthermore, TCP continuously estimates the RTT of a given connection, because the RTT is affected by variations in the network traffic.
TCP also sequences the data by associating a sequence number with every byte that it sends. For example, assume an application writes 2,048 bytes to a TCP socket, causing TCP to send two segments, the first containing the data with sequence numbers 1–1,024 and the second containing the data with sequence numbers 1,025–2,048. (A segment is the unit of data that TCP passes to IP.) If the segments arrive out of order, the receiving TCP will reorder the two segments based on their sequence numbers before passing the data to the receiving application. If TCP receives duplicate data from its peer (say the peer thought a segment was lost and retransmitted it, when it wasn't really lost, the network was just overloaded), it can detect that the data has been duplicated (from the sequence numbers), and discard the duplicate. 
TCP provides flow control. TCP always tells its peer exactly how many bytes of data it is willing to accept from the peer at any one time. This is called the advertised window. At any time, the window is the amount of room currently available in the receive buffer, guaranteeing that the sender cannot overflow the receive buffer. The window changes dynamically over time: As data is received from the sender, the window size decreases, but as the receiving application reads data from the buffer, the window size increases. It is possible for the window to reach 0: when TCP's receive buffer for a socket is full and it must wait for the application to read data from the buffer before it can take any more data from the peer.

TCP Connection termination:
when it comes for termination. TCP has 4 steps .
step 1) when application calls close(), the tcp peer will send the FIN segment. it means it has finished sending data .this is called active close
step 2) The other end that receives the FIN performs the passive close. The received FIN is acknowledged by TCP. The receipt of the FIN is also passed to the application as an end-of-file (after any data that may have already been queued for the application to receive), since the receipt of the FIN means the application will not receive any additional data on the connection.
step 3)sometime later, the application that received the end-of-file will close its socket. This causes its TCP to send a FIN.
step 4) The TCP on the system that receives this final FIN (the end that did the active close) acknowledges the FIN.


Network Programming

would like to blog network programming topics.

when I say network programming, i would like to blog about TCP & UDP protocols.


Tcp Protocol:

http://techie-builder.blogspot.com/2010/11/tcp-protocol.html


UDP Protocol:

link to be given here

using dup,fork,exec communicate b/w process

what happens when ls -l | head -5 | wc is issued in shell. the shell creates processes and uses pipes between them to pass the output 2 other process. to implement this programmatically  we need to map the pipe to stdin/stdout .

1) create 2 pipes. say p1 and p2 .
2)create child process using fork . dup the write end of p1 with stdout and exec with ls -l
3)create other child process to receive ouput of ls -l here. we can do this by using dup with read end of p1 with stdin. to send output to wc again we need to dup write end of pipe p2 with stdout. exec with head -5 process
4)in parent process, receive the output from head -5 command. do this by using dup() on read end of pipe p2 with stdin and exec. output will be displayed on screen .


Program to implement  ls –l | head -5 | wc

#include
#include
#include
#include
#include

#include

#define MAXLEN 1024
  int main()
        {

        int p1[2],p2[2];
        int outfd,infd;int old_infd,old_outfd ; // save old descp
        int pid,pid2,pid3,flag;char str[MAXLEN];
        pipe(p1);

         if(pipe(p2) < 0)

        perror("cannot create pipe p2");
        outfd=p2[1];
        infd=p2[0];
        old_infd=dup(0); // save old descriptors
        old_outfd=dup(1);


        switch(pid=fork()) {
        case 0:
                close(1);dup(p1[1]);
                close(p1[0]);
                dup(p1[1]);
                execl("/usr/bin/ls","ls","-l",NULL);
                break;

        case -1:
                perror("cannot create process");
                break;
        default:
                sleep(2);
        }
        switch(pid3=fork()){
        case 0:
                close(0);
                dup(p1[0]);
                close(p1[0]); close(p1[1]);
                dup2(old_outfd,1);
                close(1);
                dup(outfd);
                close(infd); // close pipes
                close(outfd);
                execl("/usr/bin/head","head","-5",NULL);
                break;
        default:
                sleep(2);
                dup2(old_infd,0);
                close(0);
                dup(infd);
                close(outfd);close(infd);

                 execl("/usr/bin/wc","wc",NULL);

        }
        return 1;

        }

binary search tree - eliminate duplicates in array

binary search tree is best algorithm in eleminating duplicates in array.

algorithm:
step 1) construct root node with 1st element in array
step 2) scan next element in array say elem and compare with root node of tree. node=tree
 step 3) if elem < node->data   and there is no left node in tree ,
               then insert elem in left node
              else repeat step3 by node = node -> left ;
step 4)  if elem > node->data  and there is no right node in tree ,
               then insert elem in right node
              else repeat step 4 by node=node->right.
 step 5) if elem == node->data , then there is duplicate in array.

the advantage of this algorithm is no need to traverse through all elements in array, duplicate element can be found once we reach it .

the worst case of this algorithm is when duplicate element is at the end of array.

C program for binary search:


#include "stdafx.h"
#include

typedef struct node{
int data;
node *left;
node *right;
}tree;

tree *t1=NULL,*t2=NULL, *t4=NULL, *root=NULL ;
int i=0;
void construct_tree(int *p,int count);
void insert(tree *t,int data);
//void insert_right(tree *t,int data);

int main(int argc, _TCHAR* argv[])
{
 int a[100]; int count=0;
printf("\n enter how many nodes for numericals");
scanf("%d",&count);
printf("\n enter numericals");
for(int i=0;i < count;i++)
scanf("%d",&a[i]);
construct_tree(a,count);
return 0;
}

void construct_tree(int *p,int count)
{
//printf("%d\t",p[i]);
root=new tree();
root->data=p[0];
root->left=NULL;
root->right=NULL;
for(t4=root,i=1;i
insert(t4,p[i]);
} // end func

void insert(tree *temp,int data){
if(data < temp->data ){
if(temp->left == NULL){
tree *t2=new tree();
t2->data=data;
t2->left=NULL;
t2->right=NULL;
temp->left=t2;
}
else
insert(temp->left,data);
}
else if(data > temp->data){
if(temp->right == NULL){
tree *t2=new tree();
t2->data=data;
t2->left=NULL;
t2->right=NULL;
temp->right=t2;
}
else
insert(temp->right,data);
}
else if(data == temp->data )
printf("\n %d duplicate found",data);
     // end else
}

change permissions for file

chmod is the command for changing permission of files.

4 - read (r)
2- write (w)
1- execute (x)

rwx-rwx-rwx are the permission bits.

first group rwx belongs to owner , 2nd group rwx belongs to users who belong to owners group.
third group of rwx belongs to other users.

chmod  755 file.txt

here 7  =  4+2+1 rwx permission to owner of file
5 = 4+1  r+x permission to user who belongs to group of owner
5= 4+1 read+execute to others

inode in Linux

An inode is a data structure holding information about files in a Linux file system. There is an inode for each file, and a file is uniquely identified by the file system on which it resides and its inode number on that system.

what is a shell in linux

Shell is a user program or it's environment provided for user interaction. Shell is an command language interpreter that executes commands read from the standard input device (keyboard) or from a file.

Shell is not part of system kernel, but uses the system kernel to execute programs, create files etc.
To find all available shells in your system type following command:
$ cat /etc/shells

some basic commands on linux


ls
 - to list files and sub directories in given directory


grep -used to search for a string in given file. grep means global regular expression print

vi - used to edit the files. to know more abt the vi editor click here http://www.cs.rit.edu/~cslab/vi.html

ps - ps is the shortage for Process Status. The command should be used to display the currently running processes on Unix/Linux systems.

top - To find out  programs CPU time and its memory.

shutdown - to shutdown your system.

du- displays the space taken by files

cat - displays the content of files. example: cat file1

find - Finds one or more files assuming that you know their approximate filenames .
example: find /home -type f -print . this will print all the files from /home dir to down all the levels.

jobs - jobs running in back ground

put foreground job into background on Linux

if your job is running in foreground already, suspend the job by pressing Ctrl +z button.
then give
$ bg

put job in background

Ah. some times you want to go back to shell prompt when executing a command which is taking lengthy time. so to get ur shell back just give "&" at end of command to put ur job background.
example:

$ mozilla & # this command runs mozilla in background.

other alternative is bg command.
bg [jobspec]
Resume the suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell's notion of the current job is used.

cron jobs in linux

what is cronjob in linux?
cron is a Linux system process that will execute a program at a preset time. To use cron you must prepare a text file that describes the program that you want executed and the times that cron should execute them. Then you use the crontab program to load the text file that describes the cron jobs into cron.

Here is the format of a cron job file:

[min] [hour] [day of month] [month] [day of week] [program to be run]



how to create a cron job in linux?

You must use crontab to load cron jobs into cron. First create a text file that uses the above rule to describe the cron job that you want to load into cron. But before you load it, type crontab -l to list any jobs that are currently loaded in crontab.

If none are listed, then it is safe to load your job. Example. If you wanted to run /usr/local/bin/foo once a day at 3:10am, then create a text file

10 3 * * * /usr/bin/foo

Save it as foo.cron. Then type crontab foo.cron. Check to see if it was loaded by typing crontab -l. It should display something like this:

# DO NOT EDIT THIS FILE - edit the master and reinstall.
# (ipwatch.cron installed on Thu Nov 18 11:48:02 1999)
# (Cron version -- $Id: crontab.c,v 2.13 1994/01/17 03:20:37 vixie Exp $)
10 3 * * * /usr/bin/foo

If you want to edit the cron job, then edit foo.cron and then remove the existing cron job (crontab -r) and load it again (crontab foo.cron). You can have multiple jobs. Just put each different one on a seperate line in foo.cron.

boot process in linux after selecting OS label

Boot process in linux after you select the OS label

The first thing the kernel does is to execute init program. Init is the root/parent of all processes executing on Linux.
The first processes that init starts is a script /etc/rc.d/rc.sysinit
Based on the appropriate run-level, scripts are executed to start various processes to run the system and make it functional
the process id of init will be 1.

run levels in linux

what are the runlevels in linux?
There are 7 run levels. from 0-6. given below is run level - its script - description about the runlevel.
run-level script description
0 /etc/rc.d/rc0.d/ shutdown/halt system
1 /etc/rc.d/rc1.d/ Single user mode
2 /etc/rc.d/rc2.d/ Multiuser with no network services exported
3 /etc/rc.d/rc3.d/ Default text/console only start. Full multiuser
4 /etc/rc.d/rc4.d/ Reserved for local use. Also X-windows (Slackware/BSD)
5 /etc/rc.d/rc5.d/ XDM X-windows GUI mode (Redhat/System V)
6 /etc/rc.d/rc6.d/ Reboot

if we give "init 0" the system jumps to run level 0 which is shutdown process. so you can shutdown ur system using init 0 command also
to shift to any runlevel just give init [runlevel] where runlevel is 0-6

enable telnet/ftp services on redhat linux

is telnet disabled in ur linux os. here is the way to turn on

As a root user.

1) vi /etc/xinetd.d/telnet .
2) give disable=no
3) bash#/etc/init.d/xinetd restart

to enable FTP service.
1) bash#/etc/init.d/vsftpd start.

duplicate hardisk on Linux

bash#dd if=/dev/sda of=/dev/sdb .

/dev/sda is input disk and /dev/sdb is output disk

you should do this as a root user. before giving this comamnd make sure you have /dev/sda .

closing port with ease on Linux

use nmap utility to close the port .

run this command

bash#nmap localhost

the output will be like

Interesting ports on localhost (127.0.0.1)
Not shown: 1711 closed ports

PORT STATE SERVICE
25/tcp open smtp
80/tcp open http

Now if you want to close port 80 , simply run this

bash#fuser -k 80/tcp 


you can also use ipaddress instead of localhost while using nmap command 

get callstack programmatically on windows using c++

to get call stack on windows load dbghelp.dll and get functions from it and use StackWalk() function. to get the stack pointer and base pointer I used _asm to access the registers. just call ShowCallStack() in your code and you will see the call_stack_.txt file in your working directory .
/*
write to smart.ram856@gmail.com if you want the code or any doubts on this
*/

#include "stdafx.h"
// use angular brackets later..for blog post iam not able to use angular braces
#include < windows.h >
#include"winbase.h"
#include"Dbghelp.h"
#include"iostream"
#include"vector"

using namespace std;

#define gle (GetLastError())
#define lenof(a) (sizeof(a) / sizeof((a)[0]))
#define MAXNAMELEN 1024 // max name length for found symbols
#define IMGSYMLEN ( sizeof IMAGEHLP_SYMBOL )
#define TTBUFLEN 65536 // for a temp buffer
#define MAX_MODULE_NAME32 255
#define TH32CS_SNAPMODULE 0x00000008
static FILE *fp=NULL;

struct ModuleEntry
{
std::string imageName;
std::string moduleName;
DWORD baseAddress;
DWORD size;
};

typedef struct _MODULEINFO {
LPVOID lpBaseOfDll;
DWORD SizeOfImage;
LPVOID EntryPoint;
} MODULEINFO, *LPMODULEINFO;

static HANDLE hIOMutex= CreateMutex (NULL, FALSE, NULL);

#pragma pack( push, 8 )
typedef struct tagMODULEENTRY32
{
DWORD dwSize;
DWORD th32ModuleID; // This module
DWORD th32ProcessID; // owning process
DWORD GlblcntUsage; // Global usage count on the module
DWORD ProccntUsage; // Module usage count in th32ProcessID's context
BYTE * modBaseAddr; // Base address of module in th32ProcessID's context
DWORD modBaseSize; // Size in bytes of module starting at modBaseAddr
HMODULE hModule; // The hModule of this module in th32ProcessID's context
char szModule[MAX_MODULE_NAME32 + 1];
char szExePath[MAX_PATH];
}MODULEENTRY32;
typedef MODULEENTRY32 * PMODULEENTRY32;
typedef MODULEENTRY32 * LPMODULEENTRY32;
#pragma pack( pop )

// CreateToolhelp32Snapshot()
typedef HANDLE (__stdcall *tCT32S)( DWORD dwFlags, DWORD th32ProcessID );
// Module32First()
typedef BOOL (__stdcall *tM32F)( HANDLE hSnapshot, LPMODULEENTRY32 lpme );
// Module32Next()
typedef BOOL (__stdcall *tM32N)( HANDLE hSnapshot, LPMODULEENTRY32 lpme );

typedef vector<> ModuleList ;
typedef ModuleList::iterator ModuleListIter ;

//these are for stacktrace functions

// SymCleanup()
typedef BOOL (__stdcall *tSC)( HANDLE hProcess );
tSC pSC = NULL;

// SymFunctionTableAccess()
typedef PVOID (__stdcall *tSFTA)( HANDLE hProcess, DWORD AddrBase );
tSFTA pSFTA = NULL;

// SymGetLineFromAddr()
typedef BOOL (__stdcall *tSGLFA)( HANDLE hProcess, DWORD dwAddr,
PDWORD pdwDisplacement, PIMAGEHLP_LINE Line );
tSGLFA pSGLFA = NULL;

// SymGetModuleBase()
typedef DWORD (__stdcall *tSGMB)( HANDLE hProcess, DWORD dwAddr );
tSGMB pSGMB = NULL;

// SymGetModuleInfo()
typedef BOOL (__stdcall *tSGMI)( HANDLE hProcess, DWORD dwAddr, PIMAGEHLP_MODULE ModuleInfo );
tSGMI pSGMI = NULL;

// SymGetOptions()
typedef DWORD (__stdcall *tSGO)( VOID );
tSGO pSGO = NULL;

// SymGetSymFromAddr()
typedef BOOL (__stdcall *tSGSFA)( HANDLE hProcess, DWORD dwAddr,
PDWORD pdwDisplacement, PIMAGEHLP_SYMBOL Symbol );
tSGSFA pSGSFA = NULL;

// SymInitialize()
typedef BOOL (__stdcall *tSI)( HANDLE hProcess, PSTR UserSearchPath, BOOL fInvadeProcess );
tSI pSI = NULL;

// SymLoadModule()
typedef DWORD (__stdcall *tSLM)( HANDLE hProcess, HANDLE hFile,
PSTR ImageName, PSTR ModuleName, DWORD BaseOfDll, DWORD SizeOfDll );
tSLM pSLM = NULL;

// SymSetOptions()
typedef DWORD (__stdcall *tSSO)( DWORD SymOptions );
tSSO pSSO = NULL;

// StackWalk()
typedef BOOL (__stdcall *tSW)( DWORD MachineType, HANDLE hProcess,
HANDLE hThread, LPSTACKFRAME StackFrame, PVOID ContextRecord,
PREAD_PROCESS_MEMORY_ROUTINE ReadMemoryRoutine,
PFUNCTION_TABLE_ACCESS_ROUTINE FunctionTableAccessRoutine,
PGET_MODULE_BASE_ROUTINE GetModuleBaseRoutine,
PTRANSLATE_ADDRESS_ROUTINE TranslateAddress );
tSW pSW = NULL;

// UnDecorateSymbolName()
typedef DWORD (__stdcall WINAPI *tUDSN)( PCSTR DecoratedName, PSTR UnDecoratedName,
DWORD UndecoratedLength, DWORD Flags );
tUDSN pUDSN = NULL;

int threadAbortFlag = 0;
HANDLE hTapTapTap = NULL;


int init();


void ShowStack(HANDLE hThread, CONTEXT& c ); // dump a stack trace
void ShowCallStack(); //which calls the ShowCallStack()
DWORD Filter( EXCEPTION_POINTERS *ep );
void enumAndLoadModuleSymbols( HANDLE hProcess, DWORD pid );
bool fillModuleList( ModuleList& modules, DWORD pid, HANDLE hProcess );
bool fillModuleListTH32( ModuleList& modules, DWORD pid );
bool fillModuleListPSAPI( ModuleList& modules, DWORD pid, HANDLE hProcess );




static int init()
{
// load the imagehlp.dll and its functions to get stacktraces.
hImagehlpDll = LoadLibrary(L"dbghelp.dll" );
if ( hImagehlpDll == NULL )
{
printf( "LoadLibrary( imagehlp.dll ) failed" );
return 1;
}
pSC = (tSC) GetProcAddress( hImagehlpDll, "SymCleanup" );
pSFTA = (tSFTA) GetProcAddress( hImagehlpDll, "SymFunctionTableAccess" );
pSGLFA = (tSGLFA) GetProcAddress( hImagehlpDll, "SymGetLineFromAddr" );
pSGMB = (tSGMB) GetProcAddress( hImagehlpDll, "SymGetModuleBase" );
pSGMI = (tSGMI) GetProcAddress( hImagehlpDll, "SymGetModuleInfo" );
pSGO = (tSGO) GetProcAddress( hImagehlpDll, "SymGetOptions" );
pSGSFA = (tSGSFA) GetProcAddress( hImagehlpDll, "SymGetSymFromAddr" );
pSI = (tSI) GetProcAddress( hImagehlpDll, "SymInitialize" );
pSSO = (tSSO) GetProcAddress( hImagehlpDll, "SymSetOptions" );
pSW = (tSW) GetProcAddress( hImagehlpDll, "StackWalk" );
pUDSN = (tUDSN) GetProcAddress( hImagehlpDll, "UnDecorateSymbolName" );
pSLM = (tSLM) GetProcAddress( hImagehlpDll, "SymLoadModule" );

if ( pSC == NULL || pSFTA == NULL || pSGMB == NULL || pSGMI == NULL ||
pSGO == NULL || pSGSFA == NULL || pSI == NULL || pSSO == NULL ||
pSW == NULL || pUDSN == NULL || pSLM == NULL )
{
puts( "GetProcAddress(): some required function not found." );
FreeLibrary( hImagehlpDll );
return 1;
}

}



void ShowCallStack() {
init();
WaitForSingleObject( hIOMutex, INFINITE );
CONTEXT c;
static int file_open =0;
if(file_open == 0) {
char *s=(char *)malloc(30);;
sprintf(s,"call_stack_%d.txt",GetCurrentProcessId());
fp=fopen(s,"a+");
if(fp == NULL) fprintf(stdout,"cannot create file ");
file_open ++;
}

memset( &c, '\0', sizeof c );
c.ContextFlags = CONTEXT_FULL;
HANDLE hThread=GetCurrentThread();
if ( ! GetThreadContext( hThread, &c ) )
{
printf( "GetThreadContext(): gle = %lu\n", gle );
}
ShowStack(hThread, c );
ReleaseMutex( hIOMutex);
}
void ShowStack(HANDLE hThread, CONTEXT& c )
{

// normally, call ImageNtHeader() and use machine info from PE header
DWORD imageType = IMAGE_FILE_MACHINE_I386;
HANDLE hProcess = GetCurrentProcess(); // hProcess normally comes from outside
int frameNum; // counts walked frames
DWORD offsetFromSymbol; // tells us how far from the symbol we were
DWORD symOptions; // symbol handler settings
IMAGEHLP_SYMBOL *pSym = (IMAGEHLP_SYMBOL *) malloc( IMGSYMLEN + MAXNAMELEN );
char undName[MAXNAMELEN]; // undecorated name
char undFullName[MAXNAMELEN]; // undecorated name with all shenanigans
IMAGEHLP_MODULE Module;
IMAGEHLP_LINE Line;
string symSearchPath;
char *tt = 0;
DWORD regEip;
DWORD regEsp;
DWORD regEbp;

STACKFRAME s; // in/out stackframe
memset( &s, '\0', sizeof s );

// NOTE: normally, the exe directory and the current directory should be taken
// from the target process. The current dir would be gotten through injection
// of a remote thread; the exe fir through either ToolHelp32 or PSAPI.

tt = new char[TTBUFLEN]; // this is a _sample_. you can do the error checking yourself.

// build symbol search path from:
symSearchPath = "";

// environment variable _NT_SYMBOL_PATH
if ( GetEnvironmentVariable( L"_NT_SYMBOL_PATH", (LPWSTR)tt, TTBUFLEN ) )
strcat(tt,";");
//strcat(symSearchPath,tt);
symSearchPath += tt ;
// environment variable _NT_ALTERNATE_SYMBOL_PATH
if ( symSearchPath.size() > 0 ) // if we added anything, we have a trailing semicolon
symSearchPath = symSearchPath.substr( 0, symSearchPath.size() - 1 );
strncpy( tt, symSearchPath.c_str(), TTBUFLEN );
tt[TTBUFLEN - 1] = '\0'; // if strncpy() overruns, it doesn't add the null terminator

// init symbol handler stuff (SymInitialize())
if ( ! pSI( hProcess, tt, false ) )
{
printf( "SymInitialize(): gle = %lu\n", gle );
}

// SymGetOptions()
symOptions = pSGO();
symOptions |= SYMOPT_LOAD_LINES;
symOptions &= ~SYMOPT_UNDNAME;
pSSO( symOptions ); // SymSetOptions()

// Enumerate modules and tell imagehlp.dll about them.
// On NT, this is not necessary, but it won't hurt.
enumAndLoadModuleSymbols( hProcess, GetCurrentProcessId() );

// init STACKFRAME for first call
// Notes: AddrModeFlat is just an assumption. I hate VDM debugging.
// Notes: will have to be #ifdef-ed for Alphas; MIPSes are dead anyway,
// and good riddance.
// getting instruction, stack, base pointer from CONTEXT could result in weird result. its very hard to get CONTEXT of running thread. so using _asm.
_asm
{
label:
lea eax, label
mov regEip, eax
mov regEbp, ebp
mov regEsp, esp
}

s.AddrPC.Offset = regEip;
s.AddrPC.Mode = AddrModeFlat;
s.AddrFrame.Offset = regEbp;
s.AddrFrame.Mode = AddrModeFlat;
s.AddrStack.Offset = regEsp;
s.AddrStack.Mode = AddrModeFlat;


memset( pSym, '\0', IMGSYMLEN + MAXNAMELEN );
pSym->SizeOfStruct = IMGSYMLEN;
pSym->MaxNameLength = MAXNAMELEN;

memset( &Line, '\0', sizeof Line );
Line.SizeOfStruct = sizeof Line;

memset( &Module, '\0', sizeof Module );
Module.SizeOfStruct = sizeof Module;

offsetFromSymbol = 0;

fprintf(fp, "\n--# FV EIP----- RetAddr- FramePtr StackPtr Symbol\n" );

for ( frameNum = 0; ; ++ frameNum )
{
// get next stack frame (StackWalk(), SymFunctionTableAccess(), SymGetModuleBase())
// if this returns ERROR_INVALID_ADDRESS (487) or ERROR_NOACCESS (998), you can
// assume that either you are done, or that the stack is so hosed that the next
// deeper frame could not be found.
if ( ! pSW( imageType, hProcess, hThread, &s, &c, NULL,
pSFTA, pSGMB, NULL ) )
break;

// display its contents
fprintf(fp, "\n%3d %c%c %08lx %08lx %08lx %08lx ",
frameNum, s.Far? 'F': '.', s.Virtual? 'V': '.',
s.AddrPC.Offset, s.AddrReturn.Offset,
s.AddrFrame.Offset, s.AddrStack.Offset );

if ( s.AddrPC.Offset == 0 )
{
printf( "(-nosymbols- PC == 0)\n" );
}
else
{ // we seem to have a valid PC
// show procedure info (SymGetSymFromAddr())
if ( ! pSGSFA( hProcess, s.AddrPC.Offset, &offsetFromSymbol, pSym ) )
{
if ( gle != 487 )
printf( "SymGetSymFromAddr(): gle = %lu\n", gle );
}
else
{
// UnDecorateSymbolName()
pUDSN( pSym->Name, undName, MAXNAMELEN, UNDNAME_NAME_ONLY );
pUDSN( pSym->Name, undFullName, MAXNAMELEN, UNDNAME_COMPLETE );
fprintf(fp, "%s", undName );
if ( offsetFromSymbol != 0 )
fprintf(fp, " %+ld bytes", (long) offsetFromSymbol );
// putchar( '\n' );
fprintf(fp,"\n");
fprintf(fp, " Sig: %s\n", pSym->Name );
//printf( " Decl: %s\n", undFullName );
}

// show line number info, NT5.0-method (SymGetLineFromAddr())
if ( pSGLFA != NULL )
{ // yes, we have SymGetLineFromAddr()
if ( ! pSGLFA( hProcess, s.AddrPC.Offset, &offsetFromSymbol, &Line ) )
{
if ( gle != 487 )
printf( "SymGetLineFromAddr(): gle = %lu\n", gle );
}
else
{
fprintf(fp, " Line: %s(%lu) %+ld bytes\n",
Line.FileName, Line.LineNumber, offsetFromSymbol );
}
} // yes, we have SymGetLineFromAddr()

// show module info (SymGetModuleInfo())
if ( ! pSGMI( hProcess, s.AddrPC.Offset, &Module ) )
{
printf( "SymGetModuleInfo): gle = %lu\n", gle );
}
else
{ // got module info OK
char ty[80];
switch ( Module.SymType )
{
case SymNone:
strcpy( ty, "-nosymbols-" );
break;
case SymCoff:
strcpy( ty, "COFF" );
break;
case SymCv:
strcpy( ty, "CV" );
break;
case SymPdb:
strcpy( ty, "PDB" );
break;
case SymExport:
strcpy( ty, "-exported-" );
break;
case SymDeferred:
strcpy( ty, "-deferred-" );
break;
case SymSym:
strcpy( ty, "SYM" );
break;
default:
_snprintf( ty, sizeof ty, "symtype=%ld", (long) Module.SymType );
break;
}

fprintf(fp, " Mod: %s[%s], base: %08lxh\n",
Module.ModuleName, Module.ImageName, Module.BaseOfImage );
//fprintf(fp, " Sym: type: %s, file: %s\n",ty, Module.LoadedImageName );
} // got module info OK
} // we seem to have a valid PC
if ( s.AddrReturn.Offset == 0 )
{
// avoid misunderstandings in the printf() following the loop
SetLastError( 0 );
break;
}

} // for ( frameNum )
} // end CallStack


void enumAndLoadModuleSymbols( HANDLE hProcess, DWORD pid )
{
ModuleList modules;
ModuleListIter it;
char *img, *mod;

// fill in module list
fillModuleList( modules, pid, hProcess );

for ( it = modules.begin(); it != modules.end(); ++ it )
{
// unfortunately, SymLoadModule() wants writeable strings
img = new char[(*it).imageName.size() + 1];
strcpy( img, (*it).imageName.c_str() );
mod = new char[(*it).moduleName.size() + 1];
strcpy( mod, (*it).moduleName.c_str() );

if ( pSLM( hProcess, 0, img, mod, (*it).baseAddress, (*it).size ) == 0 )
printf( "Error %lu loading symbols for \"%s\"\n",gle, (*it).moduleName.c_str() );
else
printf( "Symbols loaded: \"%s\"\n", (*it).moduleName.c_str() );

delete [] img;
delete [] mod;
}
}


bool fillModuleList( ModuleList& modules, DWORD pid, HANDLE hProcess )
{
// try toolhelp32 first
if ( fillModuleListTH32( modules, pid ) )
return true;
// nope? try psapi, then
return fillModuleListPSAPI( modules, pid, hProcess );
}


bool fillModuleListTH32( ModuleList& modules, DWORD pid )
{
// I think the DLL is called tlhelp32.dll on Win9X, so we try both
//const char *dllname = { L"tlhelp32.dll" };
HINSTANCE hToolhelp;
HINSTANCE kernldll;
tCT32S pCT32S;
tM32F pM32F;
tM32N pM32N;

HANDLE hSnap;
MODULEENTRY32 me = { sizeof me };
bool keepGoing;
ModuleEntry e;
hToolhelp = LoadLibrary(L"tlhelp32.dll");
if ( hToolhelp != NULL)
{
pCT32S = (tCT32S) GetProcAddress( hToolhelp, "CreateToolhelp32Snapshot" );
pM32F = (tM32F) GetProcAddress( hToolhelp, "Module32First" );
pM32N = (tM32N) GetProcAddress( hToolhelp, "Module32Next" );
}
else {
kernldll= LoadLibrary(L"kernel32.dll");
pCT32S = (tCT32S) GetProcAddress(kernldll , "CreateToolhelp32Snapshot" );
pM32F = (tM32F) GetProcAddress( kernldll, "Module32First" );
pM32N = (tM32N) GetProcAddress( kernldll, "Module32Next" );
}
if(pCT32S == NULL && pM32F== NULL && pM32N ==NULL )
return false;
hSnap = pCT32S( TH32CS_SNAPMODULE, pid );
if ( hSnap == (HANDLE) -1 )
return false;

keepGoing = !!pM32F( hSnap, &me );
while ( keepGoing )
{
// here, we have a filled-in MODULEENTRY32
fprintf(fp, "%08lXh %6lu %-15.15s %s\n", me.modBaseAddr, me.modBaseSize, me.szModule, me.szExePath );
e.imageName = me.szExePath;
e.moduleName = me.szModule;
e.baseAddress = (DWORD) me.modBaseAddr;
e.size = me.modBaseSize;
modules.push_back( e );
keepGoing = !!pM32N( hSnap, &me );
}

CloseHandle( hSnap );

FreeLibrary( hToolhelp );

return modules.size() != 0;
}


bool fillModuleListPSAPI( ModuleList& modules, DWORD pid, HANDLE hProcess )
{
// EnumProcessModules()
typedef BOOL (__stdcall *tEPM)( HANDLE hProcess, HMODULE *lphModule, DWORD cb, LPDWORD lpcbNeeded );
// GetModuleFileNameEx()
typedef DWORD (__stdcall *tGMFNE)( HANDLE hProcess, HMODULE hModule, LPSTR lpFilename, DWORD nSize );
// GetModuleBaseName() -- redundant, as GMFNE() has the same prototype, but who cares?
typedef DWORD (__stdcall *tGMBN)( HANDLE hProcess, HMODULE hModule, LPSTR lpFilename, DWORD nSize );
// GetModuleInformation()
typedef BOOL (__stdcall *tGMI)( HANDLE hProcess, HMODULE hModule, LPMODULEINFO pmi, DWORD nSize );

HINSTANCE hPsapi;
tEPM pEPM;
tGMFNE pGMFNE;
tGMBN pGMBN;
tGMI pGMI;

int i;
ModuleEntry e;
DWORD cbNeeded;
MODULEINFO mi;
HMODULE *hMods = 0;
char *tt = 0;

hPsapi = LoadLibrary( L"psapi.dll" );
if ( hPsapi == 0 )
return false;

modules.clear();

pEPM = (tEPM) GetProcAddress( hPsapi, "EnumProcessModules" );
pGMFNE = (tGMFNE) GetProcAddress( hPsapi, "GetModuleFileNameExA" );
pGMBN = (tGMFNE) GetProcAddress( hPsapi, "GetModuleBaseNameA" );
pGMI = (tGMI) GetProcAddress( hPsapi, "GetModuleInformation" );
if ( pEPM == 0 || pGMFNE == 0 || pGMBN == 0 || pGMI == 0 )
{
// yuck. Some API is missing.
FreeLibrary( hPsapi );
return false;
}

hMods = new HMODULE[TTBUFLEN / sizeof HMODULE];
tt = new char[TTBUFLEN];
// not that this is a sample. Which means I can get away with
// not checking for errors, but you cannot. :)

if ( ! pEPM( hProcess, hMods, TTBUFLEN, &cbNeeded ) )
{
printf( "EPM failed, gle = %lu\n", gle );
goto cleanup;
}

if ( cbNeeded > TTBUFLEN )
{
printf( "More than %lu module handles. Huh?\n", lenof( hMods ) );
goto cleanup;
}

for ( i = 0; i <>
{
// for each module, get:
// base address, size
pGMI( hProcess, hMods[i], &mi, sizeof mi );
e.baseAddress = (DWORD) mi.lpBaseOfDll;
e.size = mi.SizeOfImage;
// image file name
tt[0] = '\0';
pGMFNE( hProcess, hMods[i], tt, TTBUFLEN );
e.imageName = tt;
// module name
tt[0] = '\0';
pGMBN( hProcess, hMods[i], tt, TTBUFLEN );
e.moduleName = tt;
fprintf(fp, "%08lXh %6lu %-15.15s %s\n", e.baseAddress,
e.size, e.moduleName.c_str(), e.imageName.c_str() );

modules.push_back( e );
}

cleanup:
if ( hPsapi )
FreeLibrary( hPsapi );
delete [] tt;
delete [] hMods;

return modules.size() != 0;
}

broadcast a message on all terminals

want to broadcast message to everyone who is logged on all terminals.

wall is the command


bash#wall Lets stop the work and go for coffee .


translate characters to upper/Lower case

while writing shell scripts sometimes in if loop we need to match the strings .we need to check
for both upper/lower cases .

converting a lower case chars to upper case:

echo "Something" | tr [:lower:] [:upper:]

converting a upper case chars to lower chars:

echo "Something" | tr [:upper:][:lower:]


Limit the CPU usage of process

you can limit cpulimit for an application using pid or process name .

for example:

to restrict cpu limit for VLC media player to go beyond 20% of CPU , type

bash# cpulimit -e vlc 1-20

use Vim editor as MySQL pager

when using MySQL you can any pager you wish using pager command

mysql>pager vim

you can see Query results displayed in vim .

change system configuration on next reboot

you can change the following configurations on next reboot .

1) passwd 2) netconfig 3) timeconfig 4) kdbconfig 5) authconfig 6) netsysv

bash# sys-unconfig

and reboot system to reset the details

display system SMBIOS hardware components

To know entire details of each piece of hardware on your computer?

here is the command. you have to run with root permissions.

bash#dmidecode -t x

replace x by

0 for BIOS
1 for system
2 for base board
3 for chassis
4 for processor
5 for memory controller
6 for memory module
7 for cache
8 for port connector
9 for system slots
10 for on board devices
11 for OEM strings
12 for system administration options

for more refer the manual page

"where is" and "what is" in Linux

"whereis " the command used to find the path of executable .

bash#whereis firefox
/usr/bin/firefox

"whatis" you can find the description of the apps using this comamnd.

bash#whatis iptables
iptables(8) - administration tool for IPv4 packet filtering and NAT

Get the PID of running process

you can check the process id of running process by using pidof command

bash# pidof sshd
1876


manual page for commands in Linux

Simple Vim trick:

do you want to open manual page for a command in vi editor? then place

your cursor on keyword and hit Ctrl + k button. this takes to manual page of command.

one you are done reading , hit q followed by Enter key to get back to vim editor again.