CH 20
CH 20
Page 2
The Heap
Libraries (libc)
ELF Executable
.text segment
.data segment
Page 3
Basics of Dynamic Memory
int main()
{
char * buffer = NULL;
Page 4
Heap vs Stack
Heap Stack
• Dynamic memory • Fixed memory allocations
allocations at runtime known at compile time
Page 5
Heap in Linux (GNU C Library – glibc)
ptmalloc2
System call:
brk() mmap()
Page 6
The Heap
Page 7
Design your own Heap management system
Linked List
Page 8
Design your own Heap management system
H: header --> 11
bitmap B: Body --> 10
F: Free 00
Bitmap representation:
(HIGH) 11 00 00 10 10 10 11 00 00 00 00 00 00 00 10 11 (LOW)
Page 10
Arena
Page 11
Arena
Page 12
Bins and Chunks
Page 13
Doug Lea‘s malloc Heap Chunks
Page 14
malloc chunk
Page 15
Heap Chunks – Freed
free(buffer);
• Forward Pointer
– A pointer to the next freed chunk
• Backwards Pointer
– A pointer to the previous freed chunk
Page 16
Heap Chunks
Heap Chunk
Previous Chunk Size Chunk Size Data
Flags
Page 17
Pseudo Memory Map
ELF Executable
0x08048000 – Start of .text Segment
.text segment
.data segment
0x00000000
Runtime Memory Heap Segment
--------------------------------->
Libraries (libc) Previous Chunk Size
.data segment
Heap
Stack
0xFFFFFFFF
Page 19
Heap Allocations
0x00000000
Runtime Memory Heap Segment
--------------------------------->
Libraries (libc) Previous Chunk Size
Data
Heap
Stack
0xFFFFFFFF
Page 20
Heap Allocations
0x00000000
Runtime Memory Heap Segment
--------------------------------->
Libraries (libc) Previous Chunk Size
Data
0x00000000
Runtime Memory Heap Segment
--------------------------------->
Libraries (libc) Previous Chunk Size
Data
0x00000000
Runtime Memory Heap Segment
--------------------------------->
Libraries (libc) Previous Chunk Size
Heap AAAAAAAAAAAAAA
…
heap overflow
Stack
Previous Chunk Size
0xFFFFFFFF
Chunk Size
Page 23
Data
heap0.c
Page 24
First object on heap; name[64]
Page 25
Second object on heap; fp contains a pointer
Page 31
Heap Overflows
https://github.com/shellphish/how2heap
Page 33
Q&A
Page 39