Get instruction address in C / C ++

Any ways to get the address of the instruction? I tried to use a label to indicate instructions and get the address of the label, but it seems that it only works in the GCC compiler using the && operator. (Refer to: in this article ) What if other compilers?

Any thoughts on this issue?

+6
source share
3 answers

I'm not sure if the C or C ++ language standards talk about learning; you could possibly run a C program compiled for execution by a large group of human slaves (but that would be unethical, even if the standard correspondence). You can run a simple tiny program with pencil and paper, you can use the C interpreter, etc. Etc....

The optimizing C or C ++ compiler also translates some C statements into several machine instructions located in different places (in particular, compilers perform built-in or clone functions or even basic blocks, even without the inline in the source code),

On most systems, you can pass a code (for example, to an assembly) a subroutine that returns its return address (i.e., the address of the caller) as a pointer value.

With GCC (and compatible compilers, perhaps Clang / LLVM), you can use __ builtin_return_address and its associated built-in functions.

Gnu Libc on Linux offers you backtrace (but I was dissolved by it when I tried).

Please note that these tricks may not work when compiling with -fno-frame-pointer

You may also consider configuring GCC, for example. with plugins or MELT extensions (MELT is a domain-specific language implemented as a GPLv3 plugin for GCC, for a GCC extension it is easier than using plugins encoded in C). Your custom GCC can insert toolkit function calls in appropriate places.

+4
source

Caution: getting out of the box here.

Is it possible to create a map file layout that contains the addresses (relative or other) of application objects (functions and data)? Then your application can simply analyze the linker map file ...

+2
source

The only standard C or C ++ construct that is even close to the address of the instruction is a function pointer, which I suppose is not what you mean. However, you can accomplish most of what you can do with gcc label values, using function pointers instead containing the necessary blocks of code.

There are no other options in C / C ++.

0
source

Source: https://habr.com/ru/post/920744/


All Articles