4

I want to write a c++ program that can find the location of a global variable. Here is the relevant readelf

...
 <1><98>: Abbrev Number: 7 (DW_TAG_variable)
    <99>   DW_AT_name        : (indirect string, offset: 0x32): sbox_bit
    <9d>   DW_AT_decl_file   : 1
    <9e>   DW_AT_decl_line   : 3
    <9f>   DW_AT_type        : <0x81>
    <a3>   DW_AT_external    : 1
    <a3>   DW_AT_location    : 5 byte block: 3 e8 0 1 0     (DW_OP_addr: 100e8)
...

I already got the DIE that has the Tag "DW_TAG_variable" with the dwarf_diename "sbox_bit". It shouldn't be too hard to find the location of this variable from here but I can't figure it out.

Arcane
  • 43
  • 4
  • 1
    See e.g. [use and meaning of DW_AT_location](https://stackoverflow.com/questions/9719266/use-and-meaning-of-dw-at-location) – Some programmer dude Dec 27 '19 at 14:52
  • 1
    A variable may not be at just one location. If the compiler figured out it was a constant it may not even exist. The compiler may also have split it into some combination of multiple variables + a number of inline constants. You can *not*, in general, assume that a C++ level variable is represented as a single named thing in the final machine code. That's way too naive. – Jesper Juhl Dec 27 '19 at 15:17
  • Thank you. In this case, the variable is at the constant address 0x000100e8. The variable in question is always a pointer to an array of ints. I think I can figure out the rest myself. I would appreciate it if you could link some examples/tutorials on elfutils/libdw.h. Since that is the library I'm forced to use. I can't find good examples online and I am going by the documentation in the comments [here](https://github.com/kushaldas/elfutils/blob/master/libdw/libdw.h) – Arcane Dec 27 '19 at 15:34
  • 1
    Please take some time to read [the help pages](http://stackoverflow.com/help), especially the section named ["What topics can I ask about here?"](http://stackoverflow.com/help/on-topic). Then you will understand why asking for examples or tutorials is off-topic. – Some programmer dude Dec 27 '19 at 15:36
  • @JesperJuhl I've never seen a compiler do that, for a non-const global variable. It could do that for constants. – user253751 Dec 27 '19 at 15:40

1 Answers1

3

I want to write a c++ program that can find the location of a global variable.

You are "holding it wrong".

While it is possible to find the location of a global variable (as well as its type, size, number of elements if it's an array, etc.) from debug info (the readelf output you presented), it is much simpler to find that address from the symbol table (i.e. output from nm).

Parsing the symbol table can be done using libelf, or just manually (if your host matches the target, it's quite easy to do). Example.

Employed Russian
  • 199,314
  • 34
  • 295
  • 362