本文共 2528 字,大约阅读时间需要 8 分钟。
对于大型Linux C/C++程序,内存越界和野指针类问题往往比较难定位。有的由于内存被非法改写造成了业务功能问题,有的则直接导致了程序crash,而且还经常不是第一现场。针对这种问题,可以采取的解决方法有:
这里用一个小例子介绍下mprotect用法。根据说明,使用mprotect这里最重要的一点是被保护的内存是按页对齐的,范围也是按页来的。这是因为Linux管理进程地址空间是一VMA(Virtual Memory Area)为单位来管理进程虚拟地址空间的,而VMA必须是page size大小的整数倍,可以看这篇文章 .
对于按页对齐申请内存,可以看这篇。 也可以使用posix_memalign
来申请,如下: #include#include #include #include int *result = 0;void add(int a, int b){ *result = a + b;}void subtract(int a, int b){ *result = a - b;}int main(){ int ret; int pagesize; // 获取操作系统一个页的大小, 一般是 4KB == 4096 pagesize = sysconf(_SC_PAGE_SIZE); printf("pagesize is: %d Byte\n", pagesize); if (pagesize == -1) { perror("sysconf"); return -1; } // 按页对齐来申请一页内存, result会是一个可以被页(0x1000 == 4096)整除的地址 ret = posix_memalign((void**)&result, pagesize, pagesize); printf("posix_memalign mem %p\n", result); if (ret != 0) { // posix_memalign 返回失败不会设置系统的errno, 不能用perror输出错误 printf("posix_memalign fail, ret %u\n", ret); return -1; } add(1, 1); // 结果写入 *result printf("the result is %d\n", *result); // 保护result指向的内存, 权限设为只读 ret = mprotect(result, pagesize, PROT_READ); if (ret == -1) { perror("mprotect"); return -1; } subtract(1, 1); // 结果写入 *result, 但是 *result 只读, 引发segment fault printf("the result is %d\n", *result); free(result); return 0;}
运行定位如下, 执行ulimit -c unlimited
打开生成coredump,执行过程如下
root@ubuntu:/media/psf/Home/iLearn/learn_mprotect# ulimit -c unlimitedroot@ubuntu:/media/psf/Home/iLearn/learn_mprotect# gcc -g main.croot@ubuntu:/media/psf/Home/iLearn/learn_mprotect# ./a.outpagesize is: 4096 Byteposix_memalign mem 0x1b2f000the result is 2Segmentation fault (core dumped)root@ubuntu:/media/psf/Home/iLearn/learn_mprotect# lsa.out core main.croot@ubuntu:/media/psf/Home/iLearn/learn_mprotect# gdb a.out coreGNU gdb (Ubuntu 7.7-0ubuntu3.1) 7.7Reading symbols from a.out...done.[New LWP 20389]Core was generated by `./a.out'.Program terminated with signal SIGSEGV, Segmentation fault.#0 0x00000000004006e5 in subtract (a=1, b=1) at main.c:1515 *result = a - b;(gdb) bt#0 0x00000000004006e5 in subtract (a=1, b=1) at main.c:15#1 0x00000000004007f2 in main () at main.c:50
这样由于野指针或越界导致的内存被非法改写就可以crash到第一现场了,通过coredump就可以很容易找到问题点 ?
转载地址:http://ybqli.baihongyu.com/