brk_printf

printf引起的一次…

起因

这次的事件是我想作死试试在堆顶部以外区域尝试访问,观察是否引起segment fault。正常来说堆顶部以外的区域是unmap的,同时也是禁止访问的。

1
2
3
4
5
6
7
8
#include <unistd.h>
#include <stdio.h>

void main()
{
char *p = sbrk(0);
p[4097] = 1;
}

引起了segment fault

1
2
3
4
5
6
7
8
9
#include <unistd.h>
#include <stdio.h>

void main()
{
char *p = sbrk(0);
printf("current brk end:%p\n",p);
p[4097] = 1;
}

没有引起segment fault

1
2
3
4
5
6
7
8
9
10
11
12
kk@WINDOWS-F01JDIP:/mnt/c/Users/DELL/Desktop/新建文件夹$ sudo cat /proc/19462/maps 
7f316e400000-7f316e5e7000 r-xp 00000000 00:00 496829 /lib/x86_64-linux-gnu/libc-2.27.so
7f316e5e7000-7f316e5f0000 ---p 001e7000 00:00 496829 /lib/x86_64-linux-gnu/libc-2.27.so
7f316e5f0000-7f316e7e7000 ---p 000001f0 00:00 496829 /lib/x86_64-linux-gnu/libc-2.27.so
7f316ea29000-7f316ea2a000 rw-p 00000000 00:00 0
7f316eb10000-7f316eb12000 rw-p 00000000 00:00 0
7f316ec00000-7f316ec01000 r-xp 00000000 00:00 43649 /mnt/c/Users/DELL/Desktop/新建文件夹/a.out
7f316ee00000-7f316ee01000 r--p 00000000 00:00 43649 /mnt/c/Users/DELL/Desktop/新建文件夹/a.out
7f316ee01000-7f316ee02000 rw-p 00001000 00:00 43649 /mnt/c/Users/DELL/Desktop/新建文件夹/a.out
7fffee7b1000-7fffee7d2000 rw-p 00000000 00:00 0 [heap]
7ffff506f000-7ffff586f000 rw-p 00000000 00:00 0 [stack]
7ffff5fec000-7ffff5fed000 r-xp 00000000 00:00 0 [vdso]

发现printf引起系统在堆上分配了大小为33个page的空间,于是尝试以下的代码,成功引起segment fault

1
2
3
4
5
6
7
8
9
#include <unistd.h>
#include <stdio.h>

void main()
{
char *p = sbrk(0);
printf("current brk end:%p\n",p);
p[135167] = 1;
}