Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the address of an instruction in C/C++

Tags:

c

base-address

Any ways to get the address of an instruction? I have tried to used to labeled the instruction and get the address of the label but seems that it only works in GCC compiler with the && operator. (Refer to: this article) What if other compilers?

Any thoughts of this question?

like image 447
nigong Avatar asked Jul 17 '12 20:07

nigong


2 Answers

I'm not sure that the C or the C++ language standards speak of instruction; you could conceivably run a C program compiled to be executed by a large group of human slaves (but that would be unethical, even if standard conforming). You can run by yourself a simplistic tiny program with a pencil and paper, you could use a C interpreter, etc... etc...

An optimizing C or C++ compiler would also translate some C statements into several machine instructions located at various places (in particular, compilers do inline or clone functions or even basic blocks, even without any inline keyword in the source code).

On most system, you might hand code (e.g. in assembly) a routine which returns as a pointer value its return address (i.e. the address of the caller).

With GCC (and compatible compilers, perhaps Clang/LLVM), you might use __builtin_return_address and related builtins.

Gnu Libc on Linux offers you backtrace (but I have been diappointed by it, when I tried).

Notice that these tricks might not work when compiling with -fno-frame-pointer

You might also consider customizing GCC e.g. with plugins or MELT extensions (MELT is a domain specific language, implemented as a GPLv3 plugin to GCC, to extend GCC more easily than with plugins coded in C). Your customized GCC might insert calls to instrumentation functions at appropriate places.

like image 156
Basile Starynkevitch Avatar answered Oct 20 '22 19:10

Basile Starynkevitch


Caution: Way out of the box here..

Can you have the linker generate a map file that contains the addresses ( relative or otherwise ) of the applications objects ( functions and data )? Your application could then simply parse the linker map file...

like image 2
Chimera Avatar answered Oct 20 '22 20:10

Chimera