我正在尝试确定堆内部的工作方式。现在特别是heap_info结构的功能和通用位置。
我了解基本功能以及如何定位main_arena。我知道有一个heap_info结构可能包含指向main_arenas的指针?
如glibc-2.23中所示,new_heap函数使用它来创建新的堆:
535 static heap_info *
536 internal_function
537 new_heap (size_t size, size_t top_pad)
538 {
539 size_t pagesize = GLRO (dl_pagesize);
540 char *p1, *p2;
541 unsigned long ul;
542 heap_info *h;
...
99 if (__mprotect (p2, size, PROT_READ | PROT_WRITE) != 0)
600 {
601 __munmap (p2, HEAP_MAX_SIZE);
602 return 0;
603 }
604 h = (heap_info *) p2;
605 h->size = size;
606 h->mprotect_size = size;
607 LIBC_PROBE (memory_heap_new, 2, h, h->size);
608 return h;
它还会在glibc代码的其他部分看到一些动作,例如:
> grep * -Rnie heap_info
ChangeLog.16:1043: * malloc/arena.c (heap_info): Adjust the padding size if
ChangeLog.17:11564: * malloc/arena.c (heap_info): Add mprotect_size field, adjust pad.
Binary file malloc/.arena.c.swo matches
malloc/malloc.c:2403: heap_info *old_heap, *heap;
malloc/malloc.c:3225: heap_info *heap = heap_for_ptr (oldtop);
malloc/malloc.c:4087: heap_info *heap = heap_for_ptr(top(av));
malloc/malloc.c:5177: heap_info *heap = heap_for_ptr (top (ar_ptr));
Binary file malloc/.arena.c.swn matches
malloc/arena.c:48:typedef struct _heap_info
malloc/arena.c:51: struct _heap_info *prev; /* Previous heap. */
malloc/arena.c:56: that sizeof (heap_info) + 2 * SIZE_SZ is a multiple of
malloc/arena.c:59:} heap_info;
malloc/arena.c:61:/* Get a compile-time error if the heap_info padding is not correct
malloc/arena.c:63:extern int sanity_check_heap_info_alignment[(sizeof (heap_info)
malloc/arena.c:126: ((heap_info *) ((unsigned long) (ptr) & ~(HEAP_MAX_SIZE - 1)))
malloc/arena.c:493:dump_heap (heap_info *heap)
malloc/arena.c:535:static heap_info *
malloc/arena.c:542: heap_info *h;
malloc/arena.c:604: h = (heap_info *) p2;
malloc/arena.c:615:grow_heap (heap_info *h, long diff)
malloc/arena.c:643:shrink_heap (heap_info *h, long diff)
malloc/arena.c:681:heap_trim (heap_info *heap, size_t pad)
malloc/arena.c:686: heap_info *prev_heap;
malloc/arena.c:776: heap_info *h;
我还知道,可以使用宏heap_for_ptr(ptr)和top(ar_ptr)在代码中定位该宏,如下所示:
42 #define top(ar_ptr) ((ar_ptr)->top)
...
123 /* find the heap and corresponding arena for a given ptr */
124
125 #define heap_for_ptr(ptr) \
126 ((heap_info *) ((unsigned long) (ptr) & ~(HEAP_MAX_SIZE - 1)))
127 #define arena_for_chunk(ptr) \
128 (chunk_non_main_arena (ptr) ? heap_for_ptr (ptr)->ar_ptr : &main_arena)
129
130
但是我在运行时无法在内存中找到这个实际的结构。有人知道如何在内存中找到heap_info结构吗?最好使用开源软件和广泛可用的工具,例如(gdb)。
感谢帮助!