en

How to get the address of main_arena

2022年8月1日

Introduction

In case of debugging the issue of memory broken, maybe you want to dump main_arena which is the root of all managed heap memory to investigate the issue. However, main_arena is a local symbol, so you cannot use dlsym.

Instead of this, you can use dl_iterate_phdr and elf.h, it’s relatively straightforward to resolve main_arena based on the local symbol.

 

Environment

CPU Architecture x86_64
OS Ubuntu 20.04 LTE
Linux Kernel 5.4.0-122
gcc 9.4.0
gdb 9.2
glibc 2.31

 

Sample program

This sample is for x86_64 architecture.

 

Explanation

dl_iterate_phdr is used to get one by one the base address of all libraries mapping to the caller process. The maped libc.so.6 does not contain the symbol table, so we need to find another ELF file containing debug symbol by using build_id defined in its  .note.gnu.build_id section.

readelf libc.so.6

 

The debug symbol file is located at /usr/lib/debug/.build-id/<build_id[0:1]>/<build_id[2:]>.debug as you can see  generate_symbol_file_path(), it might be cantaining the symbol table (.symtab). The final address of main_arena is determined by the base address plus the symbol value.

 

Run samples

You can compile with:

 command
$ gcc -o test -g -O0 -Wall -Werror get_main_arena.c -lc -ldl

and confirm as:

 command
$ gdb test
(gdb) b main
Breakpoint 1 at 0x1a7f: file get_main_arena.c, line 184.
(gdb) run
Starting program: /home/sanachan/test
Breakpoint 1, main () at get_main_arena.c:184
184 main(void) {
(gdb) n
185 dl_iterate_phdr(callback, NULL);
(gdb) n
debug symbol file: path=/usr/lib/debug/.build-id/18/78e6b475720c7c51969e69ab2d276fae6d1dee.debug
main_arena found: 0x7ffff7fb8b80
186 return 0;
(gdb) p &main_arena
$1 = (struct malloc_state *) 0x7ffff7fb8b80 <main_arena>
(gdb) p my_main_arena
$2 = (void *) 0x7ffff7fb8b80 <main_arena>

The value my_main_arena matches that of main_arena, so the correct address was found.

 

  • この記事を書いた人
  • 最新記事
SANACHAN

SANACHAN

「生涯一エンジニア」を掲げ、大手グローバル企業でSE/PGとして8年勤め、キャリアアップ転職した現役のエンジニアです。世にあるメジャーな全プログラム言語(コボル除く)を自由に扱えます。一児の父。自分のため、家族のため、日々勉強してます。システムエンジニア、プログラミングに関する情報を蓄積している雑記帳です。

-en
-, ,