[英]GCC's stack protection feature with optimization levels
我正在使用GCC的堆栈保护功能进行一些实验,以更好地理解它。 基本上,我提到了关于stackoverflow的文章 。
以下是我的代码。
测试
#include <stdio.h>
void write_at_index(char *arr, unsigned int idx, char val)
{
arr[idx] = val;
printf("\n%s %d arr[%u]=%d\n", __func__, __LINE__,
idx, arr[idx]);
}
void test_stack_overflow()
{
char a[16] = {0}; //Array of 16 bytes.
write_at_index(a, 30/*idx*/, 10/*val*/); //Ask the other function to access 30th index.
printf("\n%s %d Exiting a[0] %d\n", __func__, __LINE__, a[0]);
}
int main()
{
test_stack_overflow();
return 0;
}
以下是我的makefile。
生成文件
CC=gcc
BIN=./test.out
SRCS=./test.c
all: $(BIN)
OBJ = ${SRCS:.c=.o}
CFLAGS=-O0 -fstack-protector -fstack-protector-all
$(OBJ): %.o: %.c
$(CC) $(CFLAGS) $(INCLUDES) -c $*.c -o $*.o
$(BIN): $(OBJ)
$(CC) -o $@ $<
rm -rf ./*.o
clean:
rm -rf ./*.out
rm -rf ./*.o
我正在使用gcc(Ubuntu 7.3.0-27ubuntu1〜18.04)7.3.0
当我构建并运行test.out时,按预期出现“检测到堆栈崩溃”崩溃。
但是,如果我将优化级别更改为O3 (CFLAGS=-O3 -fstack-protector -fstack-protector-all)
并生成并执行test.out,则不会观察到崩溃。
所以我的问题是,启用优化后,编译器是否会删除“ -fstack-protector”选项? 还是我在这里缺少其他设置?
在较高的优化级别, write_at_index
内联到test_stack_overflow
和GCC检测整个阵列a
不以任何有意义的方式使用,并消除它。 结果,存储到阵列中以及相关的缓冲区溢出都消失了。 您必须添加一个编译器屏障,以防止这种情况发生。
此外,单字节溢出仅在设法击中金丝雀(或返回地址)时才触发堆栈保护器崩溃。 因此,它们不是练习堆栈溢出检测代码的好方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.