堆相关数据结构小整理

本文最后更新于:2023年4月26日 下午

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
Each index of an array corresponds to a linked list(LIST)

Only Fast bin use FILO
(FILO is faster than FIFO)

#ifndef INTERNAL_SIZE_T
# define INTERNAL_SIZE_T size_t
#endif
#define SIZE_SZ (sizeof(INTERNAL_SIZE_T))
/* sizeof(size_t) or sizeof(unsigned int) */

struct malloc_chunk {
INTERNAL_SIZE_T prev_size;
INTERNAL_SIZE_T size;

struct malloc_chunk *fd;
struct malloc_chunk *bk;

struct malloc_chunk *fd_nextsize;
struct malloc_chunk *bk_nextsize;
};

typedef struct malloc_chunk *mbinptr;
#define next_bin(b) ((mbinptr)((char *) (b) + (sizeof(mchunkptr) << 1)))

#define NBINS 128
typedef struct malloc_chunk *mfastbinptr;
struct malloc_state {
// mutex_t mutex;
__libc_lock_define(, mutex);

int flags;

mfastbinptr fastbinsY[NFASTBINS];

mchunkptr top;
mchunkptr last_remainder;
mchunkptr bins[NBINS * 2 - 2];

unsigned int binmap[BINMAPSIZE];

struct malloc_state *next;
struct malloc_state *next_free;

INTERNAL_SIZE_T attached_threads;
INTERNAL_SIZE_T system_mem;
INTERNAL_SIZE_T max_system_mem;
};

typedef struct malloc_state *mstate;

fastbinY[] --> fastbin
bins[0] --> top_chunk(high, program use)
bins[1] --> unsorted bins
bins[2]~bins[63] --> small bins
bins[64]~bins[126] --> large bins

top_chunk stores information about the total size of the heap block and is addressed to heap top+0x8

main_arena(a global variable in data segment of libc.so) <--> sbrk
thread_arena(in the requested heap) <--> mmap
For 32 bit system:
arena.num_max = 2 * core.num
For 64 bit system:
arena.num_max = 8 * core.num

/* Check if m has acceptable alignment */
/* MALLOC_ALIGN_MASK = 2 * SIZE_SZ -1 */
#define aligned_OK(m) (((unsigned long) (m) & MALLOC_ALIGN_MASK) == 0)
#define misaligned_chunk(p) \
((uintptr_t)(MALLOC_ALIGNMENT == 2 * SIZE_SZ ? (p) : chunk2mem(p)) & \
MALLOC_ALIGN_MASK)

malloc(1); --> malloc(0x20);
sizeof(prev_size) + sizeof(size) = 0x10
sizeof(fd) = 0x20 - 0x10 = 0x10

malloc(0x21) --> malloc(0x30)
sizeof(prev_size) + sizeof(size) = 0x10
sizeof(fd) = 0x30 - 0x10 = 0x20

typedef struct _heap_info {
mstate ar_ptr; // pointed to the arena for this heap
struct _heap_info *prev;
size_t size;
size_t mprotect_size;
// ensure the heap has been alined
char pad[-6 * SIZE_SZ & MALLOC_ALIGN_MASK];
} heap_info;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
typedef struct malloc_state *mstate;
int __malloc_trim(size_t s) {
int result = 0;
if(!__malloc_initialized)
ptmalloc_init();
mstate ar_ptr = &main_arena;
do {
__libc_lock_lock(ar_ptr->mutex);
result |= mtrim(ar_ptr, s);
__libc_lock_unlock(ar_ptr->mutex);
ar_ptr = ar_ptr->next;
}while(ar_ptr != &main_arena);
return result;
}

堆相关数据结构小整理
http://example.com/2023/03/21/堆相关数据结构小整理/
作者
OSLike
发布于
2023年3月21日
许可协议