GCC是否生成Canary? [英] GCC generate Canary or not?
问题描述
我的gcc版本是4.8.2,操作系统是ubuntu 14.04(64位). 我发现有时候gcc会自动生成canary来做缓冲区溢出保护,为什么不呢?
my gcc version is 4.8.2 and operating system is ubuntu 14.04 (64 bit). I found that sometimes gcc auto generate the canary to do buffer overflow protection sometimes not, why?
生成金丝雀的情况:当SIZE为4的倍数时
case to generate canary: when SIZE is multiple of four
#include<stdio.h>
#define SIZE 4
int main()
{
char s[SIZE];
scanf("%s", s);
return 0;
}
gcc -c -g -Wa,-a,-ad之后的asm
asm after gcc -c -g -Wa,-a,-ad
...
4:a.c **** int main()
5:a.c **** {
13 .loc 1 5 0
14 .cfi_startproc
15 0000 55 pushq %rbp
16 .cfi_def_cfa_offset 16
17 .cfi_offset 6, -16
18 0001 4889E5 movq %rsp, %rbp
19 .cfi_def_cfa_register 6
20 0004 4883EC10 subq $16, %rsp
21 .loc 1 5 0
22 0008 64488B04 movq %fs:40, %rax
22 25280000
22 00
23 0011 488945F8 movq %rax, -8(%rbp)
24 0015 31C0 xorl %eax, %eax
6:a.c **** char s[SIZE];
7:a.c **** scanf("%s", s);
...
不生成金丝雀的情况:不是四的倍数
case not to generate canary : not the multiple of four
#include<stdio.h>
#define SIZE 2
int main()
{
char s[SIZE];
scanf("%s", s);
return 0;
}
gcc -c -g -Wa,-a,-ad之后的asm
asm after gcc -c -g -Wa,-a,-ad
...
4:a.c **** int main()
5:a.c **** {
13 .loc 1 5 0
14 .cfi_startproc
15 0000 55 pushq %rbp
16 .cfi_def_cfa_offset 16
17 .cfi_offset 6, -16
18 0001 4889E5 movq %rsp, %rbp
19 .cfi_def_cfa_register 6
20 0004 4883EC10 subq $16, %rsp
6:a.c **** char s[SIZE];
7:a.c **** scanf("%s", s);
...
推荐答案
好的,我想我们知道注释中的答案,因此我将其张贴在此处以明确说明.
OK, I guess we know the answer from comments, so I'll post it here to state it explicitly.
将金丝雀放入许多功能中可能会导致性能下降.这就是为什么有几种方法告诉GCC我们要使用它们,这些方法已经很好地描述了
Putting canaries in a lot of functions can result in performance degradation. That's why there are several ways to tell GCC we want to use them, which are described well here. Main ideas:
- 默认情况下不使用金丝雀,需要传递启用它们的标志之一.
- 为了节省执行时间,GCC使用带有
-fstack-protector
标志的简单启发式:为使用alloca
或大于8
字节的本地缓冲区(默认情况下)的函数添加Canaries. - 可以使用
ssp-buffer-size
参数:--param ssp-buffer-size=4
调整启发式.
- Canaries are not used by default, one needs to pass one of flags that enable them.
- To save execution time, GCC uses simple heuristic with
-fstack-protector
flag: add canaries for functions that usealloca
or local buffers larger than8
bytes (by default). - The heuristic can be tweaked with
ssp-buffer-size
parameter:--param ssp-buffer-size=4
.
显然,Ubuntu发行了GCC版本,其缓冲区大小更改为4
,因此小于该大小的缓冲区不会触发金丝雀的生成.我通过使用--param ssp-buffer-size=4
编译两个示例来确认(并且其他任何人都可以重复)这一点,该示例只为其中一个生成了带有金丝雀的程序集.
Apparently Ubuntu ships version of GCC with size of buffer changed to 4
, so buffers less than that don't trigger generation of a canary. I confirm (and anyone else should be able to repeat) that by compiling two examples with --param ssp-buffer-size=4
, which produces assembly with canaries for only one of them.
这篇关于GCC是否生成Canary?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!