C++编译器自动生成的堆栈保护检查

C++编译器自动生成的堆栈保护检查,第1张

目录

背景

1.C++源程序

2.Ghidra反编译结果

3.IDA反编译结果

4.代码分析小结

4.1 堆栈保护的原理

4.2 Release编译特性


背景

    在反编译C++程序时,看到一些多出来的代码,探究一番发现是一些编译器自动生成的,本文说明一下。

1.C++源程序
#include 
#include 
using namespace std;

int main()
{
    int a;
    a = 100;
    for (int i = 0; i < a; i++)
    {
        cout << "Hello World! " << endl;
    }
    cin >> a;
    return 0;
}

编译时Visual studio 2022,选择了Release:

2.Ghidra反编译结果

   在IDA反编译的过程中,反编译出来一些源代码上没有的代码(__security_cookie和):

int __cdecl main(int _Argc,char **_Argv,char **_Env)

{
  basic_ostream_> *this;
  char *unaff_ESI;
  int iVar1;
  code *pcVar2;
  int local_c;
  uint local_8;
  
  local_8 = __security_cookie ^ (uint)&stack0xfffffffc;//源代码没有的代码
  local_c = 100;
  iVar1 = 0;
  do {
    pcVar2 = std::endl_>;
    this = std::operator<<_>
                     ((basic_ostream_> *)
                      std::endl_>,unaff_ESI);
    std::basic_ostream_>::operator<<
              ((basic_ostream_> *)this,pcVar2);
    iVar1 = iVar1 + 1;
  } while (iVar1 < local_c);
  std::basic_istream_>::operator>>
            ((basic_istream_> *)cin_exref,&local_c);
  iVar1 = 0;
  __security_check_cookie(local_8 ^ (uint)&stack0xfffffffc);//源代码没有的代码
  return iVar1;
}
3.IDA反编译结果

        因为导入了pdb文件,所以识别出了i和a这些变量名字,IDA就没有这部分代码出现,智能过滤掉了吧。

int __cdecl main(int argc, const char **argv, const char **envp)
{
  int i; // esi
  std::ostream *v4; // eax
  int v6; // [esp-4h] [ebp-10h]
  int a; // [esp+4h] [ebp-8h] BYREF

  a = 100;
  for ( i = 0; i < a; ++i )
  {
    v4 = std::operator<<>(std::cout, (const char *)std::endl>);
    std::ostream::operator<<(v4, v6);
  }
  std::istream::operator>>(std::cin, &a);
  return 0;
}
4.代码分析小结

__security_cookie等源代码没有的代码,百度查了发现是编译器生成的保护代码:

4.1 堆栈保护的原理

其中成对出现的梁行代码:

  local_8 = __security_cookie ^ (uint)&stack0xfffffffc;

 __security_check_cookie(local_8 ^ (uint)&stack0xfffffffc);

     __security_cookie和0xfffffffc异或放入local_8中,程序运行结束后,在把local_8和0xfffffffc异或得到原始的__security_cookie,那么程序就是正常的没有产生参数堆栈溢出。

4.2 Release编译特性

    编译的结果不像Debug版本,直接显示字符串(如下代码),字符串是放到别的地方去的,反编译就看不到这个字符串,需要去搜索。

int __cdecl main()
{
  std::ostream *v0; // eax
  int i; // [esp+D0h] [ebp-18h]
  int a; // [esp+DCh] [ebp-Ch] BYREF
 
  a = 100;
  for ( i = 0; i < a; ++i )
  {
    v0 = std::operator<<>(std::cout, "Hello World! ");
    std::ostream::operator<<(v0, std::endl>);
  }
  std::istream::operator>>(std::cin, &a);
  return 0;
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/866990.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-12
下一篇 2022-05-12

发表评论

登录后才能评论

评论列表(0条)

保存