This question already has an answer here:
-
How to find out who called a method?
9 answers
I want to write a debug function or method that will help print useful information. When it is called, I need:
- the memory address of the calling object (if called by an object)
- the method signature of the caller (or the name of the method), or the name of the function
- the class name that owns that method or function
Is it possible to get this information without passing a whole bunch of parameters?
I want to make something like:
debug();
which then goes into every method and function, and helps printing out useful informations about what's going on.
My first instinct would be to suggest using gdb
and breakpoints, since most of that information is available in a stack trace. However, if you really want to see it printed, there are ways to approximate what you're talking about
The preprocessor recognizes the __PRETTY_FUNCTION__
macro for printing the function/method name, and it works well for Objective-C methods. If you print the method name and the value of self
at each method of interest, you've pretty much generated a poor man's stack trace.
Try including a #define
like this in a header that every file that wants it includes:
#define METHOD() printf("%s\t0x%x\n", __PRETTY_FUNCTION__, (unsigned int)self)
Then just include this line whenever you want to print that information:
METHOD();
The output will look something like this:
-[MyClass initWithFoo:bar:] 0x12345678
As I mentioned, this type of approach is likely to produce huge amounts of output, and gdb is probably a more pragmatic option.
I use Karl Kraft's DebugLog
Sorry I don't have a full answer for you, just some relevant info.
NSThread defines a method that gets you an unsymbolicated backtrace, callStackReturnAddresses
. In 10.6, it also will give you strings satisfying your second and third requests callStackSymbols
.
Getting address of the calling object is interesting, but not totally simple. It's going to involve walking up the stack and picking out where the receiver object is usually stored if there is a usual place it's stored on ARM. For this you (or someone) would need to understand the calling conventions for ARM, which are probably documented in an ARM ABI (application binary interface) somewhere. I don't know ARM. This would be doable on i386, and not really on ppc.
You can use the backtrace(3) API to find out what method or function called you. Getting the calling object, if there was one, is much, much harder, though.