Friday, December 08, 2006

Backtracing from code in ARM

Recently I found a way to do backtrace from code in ARM processor. On a normal processor glibc itself provides a function called ‘backtrace’ using which we can do backtracing, resolving symbol names and etc. But my glibc (ver 2.95.3) doesn’t support this, so I thought of writing my own backtrace function and the result is this.

The following two pictures shows the structure of activation record in ARM and how it is maintained



So from the above pictures you could have found that the activation records are maintained like a linked list. All we need to find is the start of linked list and travel till there is no more record.

Glibc provides a built in macro ‘__builtin_frame_address’ using which we can find the current frame(activation record) address at any time. So the steps for backtracing are

  • Find current frame address (i.e. __builtin_frame_address)
  • The first four bytes(i.e. *fp) of frame points to program counter (PC), so skip it
  • The next four bytes(i.e. *(fp – 1)) since stack grow downwards) is link register or return address of current function
    • Using this we can find the parent/caller
  • The fourth four bytes(i.e. *(fp – 3)) points to the previous/caller activation record
    • This forms a linked list of activation records and end when *(fp – 3) is ‘0’
Code:

#include <stdio.h>
void backtrace(void* fp)
{
if (fp == 0)
return;

fprintf (stderr, "%p\n", *((int*)fp - 1));
backtrace ((void*)(*((int*)fp - 3)));
}

int bar()
{
printf ("bar\n");
printf ("*** backtrack ***\n");
backtrace (__builtin_frame_address (0));
printf ("\n");

return 0;
}

int foo()
{
printf ("foo\n");
printf ("*** backtrack ***\n");
backtrace (__builtin_frame_address (0));
printf ("\n");

return bar();
}

int main()
{
printf ("main at %p\n", main);
printf ("foo at %p\n", foo);
printf ("bar at %p\n\n", foo);

printf ("main\n");
printf ("*** backtrack ***\n");
backtrace (__builtin_frame_address (0));
printf ("\n");

return foo();
}

Output:
main at 0x919a1160
foo at 0x919a1114
bar at 0x919a1114

main
*** backtrack ***
0x919a13e0
0x919a1418
0x919a1064

foo
*** backtrack ***
0x919a11b8
0x919a13e0
0x919a1418
0x919a1064

bar
*** backtrack ***
0x919a1144
0x919a11b8
0x919a13e0
0x919a1418
0x919a1064

Wrapping malloc/free

Recently I have come across a situation in which I was supposed to detect memory leak in our application. Since we have written our own memory for our application memory requirements, it become easy for me to tell there is no memory leak inside our code. Since memory consumption was continuously increasing we had confirmed there was a memory leak but not in our code. So the only remaining place where the leak could happen is library. Since we don’t have the source of the library we couldn’t confirm the leak. I started googling for memory leak related stuff and finally end up with a solution.

The first solution is hooking malloc/free. This can be done by assigning callback functions to these variables __malloc_hook/__free_hook. But this feature is not available in older glibc (like mine 2.95.3). So I skipped to the second solution, that is wrapping the malloc/free functions with the help of linker, so that every call to malloc/free will notify us and we can do stuffs like profiling, auditing and etc. Seems simple? Yeah, it is simple if know how glibc memory allocator works.

First add the wrapper functions in your source code like below

void* __wrap_malloc(size_t size)
{

// You can call the real malloc by __real_malloc
// You can do also profiling, like how many allocations,
// size of allocations and etc.
}

void* __wrap_realloc(void* oldptr, size_t size)
{

}

void __wrap_free(void* ptr)
{

}


Then use the following LDFLAGS for compiling your program
-Wl,--wrap,malloc,--wrap,free,--wrap,realloc


NOTE: Some linkers (like mine) are very sensitive to the way the parameters are passed, so check

Now any call to malloc/free will come to __wrap_malloc/__wrap_free functions

Tuesday, September 05, 2006

Programming Quotes

Some of the programming quoates i really enjoyed

Good code is its own best documentation. As you're about to add
a comment, ask yourself, 'How can I improve the code so that this
comment isn't needed?' Improve the code and then document it to
make it even clearer.
- Steve McConnell [Code Complete]

Measuring programming progress by lines of code is like measuring
aircraft building progress by weight.
- Bill Gates

I did say something along the lines of "C makes it easy to shoot
yourself in the foot; C++ makes it harder, but when you do,
it blows your whole leg off."
- Bjarne Stroustrup

Two things are infinite: the universe and human stupidity;
and I'm not sure about the universe.
- Albert Einstein

You're bound to be unhappy if you optimize everything
- Donald Knuth

Theory is when you know something, but it doesn't work.
Practice is when something works, but you don't know why.
Programmers combine theory and practice: Nothing works and
they don't know why.

Do not worry about your difficulties in mathematics,
I assure you that mine are greater.
- Einstein

One of the main causes of the fall of the Roman Empire
was that, lacking zero, they had no way to indicate successful
termination of their C programs

I've finally learned what "upward compatible" means.
It means we get to keep all our old mistakes.
- Dennie van Tassel

Most software today is very much like an Egyptian pyramid
with millions of bricks piled on top of each other,
with no structural integrity, but just done by brute force
and thousands of slaves.
- Alan Kay

A non-virtual function says, you have to do this and
you must do it this way. A virtual function says you
have to do this, but you don't have to do it this way.
That's their fundamental difference.
- Scott Meyers

Copy and paste is a design error
- David Parnas

Any code of your own that you haven't looked at for
six or more months might as well have been written
by someone else.
- Eagleson's law

If you can't be a good example, then you'll just
have to be a horrible warning.
- Catherine Aird

You can know the name of a bird in all the languages
of the world, but when you're finished, you'll know
absolutely nothing whatever about the bird... So let's
look at the bird and see what it's doing -- that's what
counts. I learned very early the difference between
knowing the name of something and knowing something.
- Richard Feynman

The primary duty of an exception handler is to get
the error out of the lap of the programmer and into
the surprised face of the user. Provided you keep
this cardinal rule in mind, you can't go far wrong.
- Verity Stob

Organizations which design systems are constrained
to produce designs which are copies of the communication
structures of these organizations.
- Conway’s Law (For example, if you have four groups
working on a compiler,
you’ll get a 4-pass compiler)

To understand recursion, you must first understand recursion.

When your hammer is C++, everything begins to look like a thumb.

First they ignore you. Then they laught about you.
Then they fight you. And then you win.
- Mahatma Gandhi

The only thing that interferes with my learning is my education.
- Albert Einstein

Even a stopped clock gives the right time twice a day.

Source: http://www.eskimo.com/~hottub/software/programming_quotes.html

Friday, July 21, 2006

C Pun Contest

Some of C puns i really enjoyed.

Q: What do you get when you assign (char) 0 to Arnold Schwarzenegger?
A: A Null Terminator.


#ifdef Get_A_Hearing_Aid


Did you hear about the C+ + programmer whose girlfriend broke up with him because he treated her like an object?


Source: C/C++ User Journal May 1992

Thursday, July 20, 2006

Heap checking class

I found the idea of heap checking class in C User Journal of April 1991. The class is really useful and the following is my own implementation of heap checking class.

class HeapCheck
{
char* begin;
char* end;

public:
HeapCheck()
{
begin = new char;
delete begin;
}

bool IsOk()
{
bool ok;

end = new char;
ok = (end == begin);
delete end;

return ok;
}
}
;

Possible implementation of va_list


I found this in C/C++ Users Journal Jan 1990

typedef int * va_list;

#define va_start (arg_ptr, first_param) (arg_ptr= (va_list) (&first_param+1))
#define va_arg(arg_ptr,type) (* (((type*) (arg_ptr= (va_list) ((type*) arg_ptr) +1))-1))
#define va_end(arg_ptr) \
(arg_ptr=NULL)

Wednesday, July 19, 2006

The History Behind the Keyword 'typename'

Today when i am reading the Game Institute CPP Programming Module 2 i come across this keyword 'typename'. I never heard this C++ keyword before so i googled and fount this fact from http://blogs.msdn.com/slippman/archive/2004/08/11/212768.aspx

Why C++ Supports both Class and Typename for Type Parameters

Recently, someone asked me why we support both class and typename within C++ to indicate a type parameter since the keywords do not hold any platform significance – for example, class is not meant to suggest a native type nor is typename meant to suggest a CLI type. Rather, both equivalently indicate that the name following represents a parameterized type placeholder that will be replaced by a user-specfied actual type.

The reason for the two keywords is historical. In the original template specification, Stroustrup reused the existing class keyword to specify a type parameter rather than introduce a new keyword that might of course break existing programs. It wasn't that a new keyword wasn't considered -- just that it wasn't considered necessary given its potential disruption. And up until the ISO-C++ standard, this was the only way to declare a type parameter.

Reuses of existing keywords seems to always sow confusion. What we found is that beginners were whether the use of the class constrained or limited the type arguments a user could specify to be class types rather than, say, a built-in or pointer type. So, there was some feeling that not having introduced a new keyword was a mistake.

During standardization, certain constructs were discovered within a template definition that resolved to expressions although they were meant to indicate declarations. For example,

template

class Demonstration {

public:

void method() {

T::A *aObj; // oops …

// …

};

While the statement containing aObj is intended by the programmer to be interpreted as the declaration of a pointer to a nested type A within the type parameter T, the language grammar interprets it as an arithmetic expression multiplying the static member A of type T with aObj and throwing away the result. Isn't that annoying! (This sort of dilemna is not possible within generics – there is no way to safely verify that any T contains an A so that the runtime can safely construct an instance of the generic type.)

The committee decided that a new keyword was just the ticket to get the compiler off its unfortunate obsession with expressions. The new keyword was the self-describing typename. When applied to a statement, such as,

typename T::A* a6; // declare pointer to T’s A

it instructs the compiler to treat the subsequent statement as a declaration. Since the keyword was on the payroll, heck, why not fix the confusion caused by the original decision to reuse the class keyword. Of course, given the extensive body of existing code and books and articles and talks and postings using the class keyword, they chose to also retain support for that use of the keyword as well. So that's why you have both.

Published Wednesday, August 11, 2004 9:32 AM by slippman

Also check this comment

Michael Kleber said:
I just had to use typename for the "unfortunate obsession with expressions" sense and I still don't understand why. Consider the following moronic way to find the length of a vector:

using namespace std;
template
int vcount(vector v) {
int i;
typename vector
::iterator vi;
for(i=0,vi=v.begin(); vi!=v.end(); i++,vi++)
;
return(i);
}

Much to my surprise, g++ 3.4.0 didn't like vector
::iterator until I put a typename before it. (Looks like older g++'s think it's just fine.)

I remain baffled, but at least typename was there for me!

I checked the above code with gcc and its true