简体   繁体   English

在C中调试堆栈溢出?

[英]Debugging stack overflow in C?

I have this sample program which when compiled with fstack-protector-all gives a stack smashing. 我有这个示例程序,当使用fstack-protector-all进行编译时,会产生堆栈粉碎。

#include <stdio.h>
#include <stdint.h>


int func(int* value)
{
    uint8_t port = 1;

    *value = port; //Canary value changes at this point when seen in GDB

    return 1;
}

int main()
{
    uint16_t index = 0;

    int ret = func((int*)&index);

}

I don't understand what is wrong with the line. 我不明白这条线怎么了。 Is any typecasting required? 是否需要任何类型转换?

It's because the size of int and the size of int16_t are different. 这是因为int的大小和int16_t的大小不同。 The size of int is (usually) 32 bits (four bytes) while int16_t is 16 bits (two bytes). int的大小(通常)是32位(四个字节),而int16_t是16位(两个字节)。

So when you write an int to a int16_t variable you write two bytes too many, and leads to undefined behavior (and in this case will "smash" the stack). 因此,当您将int写入int16_t变量时,您将写入两个字节过多,从而导致未定义的行为 (在这种情况下,将“破坏”堆栈)。

The problem is more specifically because you call the function with a pointer to index which is a 16-bit variable, but the function expects (and uses its argument) as a 32-bit variable. 更具体地讲,问题出在因为调用带有16位变量index的指针的函数,但是该函数期望(并使用其参数)作为32位变量。 You should not do the cast there in the call, as that hides the problem but doesn't solve it. 您不应该在呼叫中进行强制转换 ,因为这隐藏了问题,但无法解决。 It doesn't matter that you only write an 8-bit value to the dereference pointer inside the function, the destination is still a 32-bit variable and the compiler will convert the 8-bit value to a 32-bit value before writing to memory. 只需将8位值写入函数内部的取消引用指针没关系,目标仍然是32位变量,编译器将在写入之前将8位值转换为32位值。记忆。

Since the type of index is uint16_t , only 16 bits are allocated for it. 由于index的类型为uint16_t ,因此仅为其分配了16位。 By casting the address of index to int* , you are pretending you have access to more than 16 bits -- 32 bits in most cases. 通过将index的地址转换为int* ,您就可以访问超过16位-在大多数情况下为32位。

In

*value = port;

you are trying to set the value in those bits that haven't been allocated. 您正在尝试在尚未分配的那些位中设置值。 Since unauthorized memory gets used in that line, any thing can happen after that. 由于该行中使用了未经授权的内存,因此之后可能会发生任何事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM