你的浏览器版本过低,可能导致网站不能正常访问!
为了你能正常使用网站功能,请使用这些浏览器。

【GCC 栈溢出的保护机制】

[复制链接]
andeyqi 发布时间:2019-11-14 20:48
代码中出现栈溢出的问题是程序员特别头疼的问题,gcc 提供了栈保护的选项能够在一定程度上帮助我们发现程序中存在的栈溢出的问题。

gcc 提供了如下的编译选项:
http://www.cnblogs.com/napoleon_liu/archive/2011/02/14/1953983.html
-fstack-protector
  1. Emit extra code to check for buffer overflows, such as stack smashing attacks.
  2. This is done by adding a guard variable to functions with vulnerable objects.
  3. This includes functions that call alloca, and functions with buffers larger than
  4. 8 bytes. The guards are initialized when a function is entered and then checked
  5. when the function exits. If a guard check fails, an error message is printed and
  6. the program exits.
复制代码

编译时加上上述的编译选项,会在栈空间中额外追加8个字节保护变量(guard variable),函数退出的时候会check该guard variable,如果值被修改了,则会输出error message 并退出程序
按照上述的描述,编译选项也不是完全保证检测出栈溢出的问题,如果跳过了描述的规则也是无法检出的,如果正好避开了检查规则的话也是无法检出问题的。


测试代码如下:
  1. //gcc -fno-stack-protector fno-stack-protector_test.c -o fno-stack-protector_test
  2. //gcc fno-stack-protector_test.c -o fno-stack-protector_test
  3. ///sdk/4.3.2/bin/arm-linux-gcc-4.3.2 -fno-stack-protector -fomit-frame-pointer fno-stack-protector_test.c -o fno-stack-protector_test
  4. ///sdk/4.3.2/bin/arm-linux-gcc-4.3.2 -fstack-protector-all -fomit-frame-pointer fno-stack-protector_test.c -o fno-stack-protector_test
  5. ///sdk/4.3.2/bin/arm-linux-objdump -S fno-stack-protector_test > fno-stack-protector_test.dis
  6. #include <stdio.h>
  7. int main(void)
  8. {
  9.         char buffer[2];
  10.         int i;
  11.         i = 1;
  12.         buffer[0] = 'a';
  13.         buffer[9] = 'b';
  14.         printf("hello.world\n");
  15.         //while(1);
  16.         return 0;
  17. }
复制代码
上述代码加上栈保护选项和去除时的代码比较会发现,加上编译选项的代码会在函数栈中额外多开辟8个字节的溢出检出空间,并在函数退出的时候追加固定值的比较,一旦发生变化则跳到对应的栈溢出处理函数中,从而产生core 文件让程序员解析问题。通过反汇编的代码可以看出来,实际比较的长度为四个字节,这个应该时跟编译器有关系,回头在用别的编译器在验证下。



stack_overflow.png
收藏 3 评论0 发布时间:2019-11-14 20:48

举报

0个回答

所属标签

STM32团队

意法半导体微控制器和微处理器拥有广泛的产品线,包含低成本的8位单片机和基于ARM® Cortex®-M0、M0+、M3、M4、M33、M7及A7内核并具备丰富外设选择的32位微控制器及微处理器


最新内容

关于
我们是谁
投资者关系
意法半导体可持续发展举措
创新与技术
意法半导体官网
联系我们
联系ST分支机构
寻找销售人员和分销渠道
社区
媒体中心
活动与培训
隐私策略
隐私策略
Cookies管理
行使您的权利
官方最新发布
STM32N6 AI生态系统
STM32MCU,MPU高性能GUI
ST ACEPACK电源模块
意法半导体生物传感器
STM32Cube扩展软件包
关注我们
st-img 微信公众号
st-img 手机版