09 August, 2013

Finding which function in an application is using maximum stack

Hi friends,
Recently I got a question in one of my interview which I was not able to answer, So I though why not to post the question here and get the answer.
So the question is "How can we find which function in an application is using maximum stack size?"
We can not use GDB.

05 August, 2013

BESCOM monitor

Hi all,

As you all know I have been at home a lot the past few months and I have been spending quite a few sleepless, mosquito infested nights due to power cuts. So I was thinking about how frequent power cuts happen and a way to monitor it. If we can have enough data we can predict based on past experience if at any given point of time how likely it is that we may have a power failure. There is no point of reading newspapers for the power cut schedule cause they don't follow it anyway! I guess its BESCOM version of Calvin & Hobbes :)

At first I was wondering how to sense if the power is on/off if I had to collect data first. We could build a small circuit to sense it and write a driver blah, blah, blah... 
But since I was on my laptop I could monitor if it is charging or not. Seems simple and does not require any special hardware. In future maybe if I setup a dedicated system to monitor it then we shall see how it goes.

So based on that I thought of doing the following:

1. Use the acpi interface to check the status of the laptop adapter among other useful information.

2. Monitor it periodically and log it in to a file for which I run a script every 5 minutes.

3. Read the file, use some probability mumbo jumbo to predict if there is a chance of a power cut.

Of course this is not the ideal way to do it as it would not be realistic for someone to keep their laptops connected to the power outlet always. But just as a small project I just wanted to try it anyway just for fun. 

So I'll post my progress so far if any of you guys are interested help me out cause I am having trouble with math and coding (Never understood the former, forgot the later).

Shell script for the monitoring:


#!/bin/bash

file="/tmp/power.csv"
touch $file

acpi -a | grep off > /dev/null
if [ $? -eq 0 ] 
then
    echo `date +"%a; %d/%m/%y; %R;"` "0">> $file
else
    echo `date +"%a; %d/%m/%y; %R;"` "1">> $file
fi

###### EOF ######


Sample power.csv file:


Mon; 05/08/13; 16:50; 1
Mon; 05/08/13; 16:55; 1
Mon; 05/08/13; 17:00; 1
Mon; 05/08/13; 17:05; 0
Mon; 05/08/13; 17:10; 1
Mon; 05/08/13; 19:10; 0
Mon; 05/08/13; 19:15; 0
Mon; 05/08/13; 19:20; 1
Mon; 05/08/13; 19:25; 0
Mon; 05/08/13; 19:30; 0
Mon; 05/08/13; 19:35; 0



For running the script you will need to check if your laptop has already been install with the acpi package and check its output. On mine I get the following output. Not sure if everyone gets the same data and format.


[Anush@Lenny]$ acpi -V
Battery 0: Discharging, 76%, 03:27:29 remaining
Battery 0: design capacity 4752 mAh, last full capacity 4511 mAh = 94%
Adapter 0: off-line
Thermal 0: ok, 44.0 degrees C
Thermal 0: trip point 0 switches to mode critical at temperature 98.0 degrees C
Cooling 0: LCD 7 of 15
Cooling 1: Processor 0 of 10
Cooling 2: Processor 0 of 10
Cooling 3: Processor 0 of 10
Cooling 4: Processor 0 of 10
[Anush@Lenny]$ 


So far I can monitor the data and even plot a simple graph in excel once I import the *.csv file. So much for the easy part. Now comes the hard part of reading the file and predicting the future... :D

Oh I almost forgot... Need to set up crontab with the following data to automatically run the script every 5 minutes.

[Anush@Lenny]$ crontab -e

Add the following line...

*/5 * * * * /home/Anush/Desktop/power.sh

...and verify using the following command.

[Anush@Lenny]$ crontab -l
*/5 * * * * /home/Anush/Desktop/power.sh



Check if crond is running:


[Anush@Lenny powmon]$ service crond status
Redirecting to /bin/systemctl status  crond.service
crond.service - Command Scheduler
 Loaded: loaded (/usr/lib/systemd/system/crond.service; enabled)
 Active: active (running) since Mon, 05 Aug 2013 12:18:43 +0530; 7h ago
Main PID: 28143 (crond)
 CGroup: name=systemd:/system/crond.service
 └ 28143 /usr/sbin/crond -n


If crond is not running try the following

[Anush@Lenny]$ chkconfig crond 
[Anush@Lenny]$ sudo chkconfig crond on


So as I said before still need to figure out how to read the file and calculate the probability stuff.
Thinking if I should use a C program or try a bit more of scripting. There maybe better ways of doing what I have done so far so let me know what you guys think, all your suggestions are welcome...!!!

Also I would like to know if we need to setup an online repository on github or google code if we need to share code and ideas in the future. Cause I am not sure how easy it is for you guys to read or post code here but if you guys are ok with it we shall continue as it is. Not that I expect a lot of traffic on this site. I was surprised that SSH even remembered to post here... ;)
It was good to see his post after such a long idle time.  

Damn it just as I am about to finish this post there is no power. I am not kidding. I intend to get to the bottom of this. If and when this is code gets completed I hope you guys can help me out by sharing data from your areas and figure out if its just my bad luck that they cut the power here so frequently or its the same all over Bangalore. 



04 August, 2013

An untold story of intelligent programmer

Hello All,

Today I am going to share with you an interesting story of an intelligent programmer who almost lost the hope on C programming and basically on everything.

The programmer had to implement a delay function using 32 bit Timer peripheral of Cortex M3 microcontroller. First it looked so simple. He was ignorant of what coming next to his way.
The tool/editor provided everything, from compiler to drivers of each and every peripheral of micro controller. It required just a foolish programmer to add A and B to get things done.

The tool also provided JTAG access to microcontroller to run the programs in Debug mode where user can add break points or user can program the inbuilt flash of microcontroller with final code, which is called Release mode. The microcontroller has an inbuilt SRAM where all the code runs. On power up, code from flash is shadowed to SRAM by the microcontroller. Don't ask me how.

Moving on to timer story. Initialize it with periodic or one shot mode. Load the count, enable the interrupt and enable the timer. It will begin to count down to zero and interrupts controller. If it is in periodic mode, it will reload itself and starts counting down to provide periodic interrupts.

Below is the implementation of delay function and how it was tested.

/****************************************************************************/
#define TIMER_DELAY_STOPPED (0U)
#define TIMER_DELAY_STARTED (1U)
#define TIMER_DELAY_ACHIEVED (2U)

UINT32 gu32TimerDelay = TIMER_DELAY_STARTED;

void timer1Init (void)
{
    /*--------------------------------------------------------------------------
     * Ensure the CMSIS-PAL provided g_FrequencyPCLK0 global variable contains
     * the correct frequency of the APB bus connecting the MSS timer to the
     * rest of the system.
     */
    SystemCoreClockUpdate();

    MSS_TIM1_init( MSS_TIMER_ONE_SHOT_MODE );
}

/* Delay function implemented by programmer */
void sDelay(UINT32 u32Sec)
{
UINT32 u32TimerLoadVal;
UINT32 u32TimerResolution;

        /* For a 100Mhz system, this global variable will hold 100M as count which is equal to one second */
u32TimerResolution = (g_FrequencyPCLK0);
u32TimerLoadVal = (u32TimerResolution * u32Sec);

        MSS_TIM1_load_immediate( u32TimerLoadVal );

       gu32TimerDelay = TIMER_DELAY_STARTED;
   
      MSS_TIM1_start();
      MSS_TIM1_enable_irq();

     while (gu32TimerDelay != TIMER_DELAY_ACHIEVED)
{
            /* In tight loop till timer interrupts and sets the flag */
                ;
}

       gu32TimerDelay = TIMER_DELAY_STOPPED;
MSS_TIM1_stop();
}

/* Linkage for Timer ISR function provided by compiler. User can add his logic inside this ISR.
__attribute__((__interrupt__)) void Timer1_IRQHandler( void )
{
gu32TimerDelay = TIMER_DELAY_ACHIEVED;
        MSS_TIM1_clear_irq();
}


void main (void)
{
      UINT32 count = 0;
      while (1)
      {
              sDelay(2);
              count = count + 2;
              printf("\nTime elapsed in sec: %d", count);
       }
}


Output:
Time elapsed in sec: 2
Time elapsed in sec: 4
Time elapsed in sec: 6
Time elapsed in sec: 8
                .
                .
                .
/*****************************************************************************/

So the programmer wrote the above functions and tested it in Debug mode and it worked in one shot. He patted his own back and started using delay function everywhere in his final code and flashed it to microcontroller in Release mode.. Voila!!!! There lies the mystery. Not even one single print on the console after the first delay function was called.

To make sure the interrupt is working, programmer added print in ISR. Yes!! The print showed up on console. But no other prints after that. He added prints everywhere. Only prints till the timer interrupt ended, where showing up on the console. None after. Then commenced the long hours of debugging the issue and listening to various so called other intelligent programmers' suggestions.

One of the gossip was how the tool, in debug mode, adds delay to the execution of the code and in release mode, where there is no JTAG interaction with the microcontroller, causing the delay function to fail. Few morons agreed to this. Few experienced fellows said it was not the issue.

So our hero tried many foolish stuffs to debug the issue. Did he succeed? Was there a foolish mistake? Or was there a secret villain who added the mystery spice into the code?

To be  continued.... (Only if any positive response to the story is observed.)

15 July, 2011

Case study: Lvalue error

Try the below programs and analyse the output.

A)
int main()
{
int n = 5;
int j;

j = ++n++;

printf("j = %d\n", j);
return 0;
}
o/p = ?

B)
int main()
{
int n = 5;
int *p = &n;
int j;

j = ++*p++;

printf("j = %d\n", j);
return 0;
}
o/p = ?

C)
int main()
{
int n = 5;
int *p = &n;
int j;

j = ++(*p)++;

printf("j = %d\n", j);
return 0;
}
o/p = ?

PS: First of all, U need to know operator precedence and associativity to understand the program.

14 July, 2011

String Palindrome - Recursive function

Hi all,

Write a program to find whether the given string is palindrome or not with the help of recursive functions.

NOTE: There are many ppl who are not active in this forum, i request them to wake up and reply to the questions posted or atleast to post some questions. Else those ppl will be removed from this forum.

07 July, 2011

Ternary Operator

main()
{
int a = 10, b = 7;
a >= 5 ? b = 100 : b = 200;
printf("B = %d\n",b);
}
When we compile this prg, I am getting an error like this:
3: error: lvalue required as left operand of assignment

What does this mean and how to resolve it?

13 June, 2011

Simple but not Simple!!!!!!

#include
main(){
int x=20;
printf("\n%d\t%d\t%d\n",x,x++,++x);
}

What is the o/p of the above prg and plz explain the logic???