1

I need to get the address space of bss and data section of the DATA segment during run time. I need the start and end address of each section.

user429696
  • 51
  • 1
  • 2

2 Answers2

6

The terminology "data segment" is somewhat obsolete.

On Unix systems, there is a supposedly portable way to retrieve the end address: simply call brk. However, the brk function comes with a warning. From the man pages:

The brk and sbrk functions are historical curiosities left over from earlier days before the advent of virtual memory management.

Emphasis original.

If you use ELF: If you know you are using ELF binaries, that information is more or less ignored when your program is loaded. ELF programs are loaded by segments, but .data and .bss are sections. The .data and .bss sections are in the same segment, but that segment also has other sections (.ctors, .dtors, .got, etc.).

If you use Linux: If you know that you are using Linux specifically, then you can do the following:

  1. Read the ELF headers from your executable. You can use /proc/self/exe to find your executable.

  2. Read the memory maps from /proc/self/maps.

  3. For the maps that correspond to your file, you can figure out which map corresponds to the .data section by looking at the offsets.

If you are using glibc: The symbol __data_start points to the beginning of the data section, and I think I've seen __bss_start defined as well.

extern char __data_start;
extern char __bss_start;
void *get_data_start(void) { return &__data_start; }

But... what are you trying to accomplish? It's most productive to explain why you want to know where the sections are. Are you writing a garbage collector? A debugger? Do you want to save process images?

Word of warning: Who knows when any of the above things will break. Maybe __data_start isn't defined, or maybe brk points to some unrelated region of memory. Reading the ELF headers seems like the most reliable trick, and there are libraries for it too.

Dietrich Epp
  • 205,541
  • 37
  • 345
  • 415
-1

Perhaps not a satisfactory answer, but under linux, you can use /proc/self/exe which contains is a symlink to your process image.

Jo So
  • 25,005
  • 6
  • 42
  • 59