为了更好地理解汇编,我使用g ++编译了一个简单的C ++程序,然后使用gdbgui逐步执行。我绘制了堆栈状态的图形,并在程序中的几个连续点进行了注册,以帮助自己更好地了解正在发生的事情。在执行过程中,程序似乎多次在堆栈指针之外的存储器中进行写入/读取。这让我感到惊讶。我的印象是,程序永远都不能写超出堆栈指针的内容。我了解它是如何工作的,相对寻址基于基本指针,但是我希望程序以某种方式调整堆栈指针以包含计划使用的内存。这种超出堆栈的写入方法是编译器的常用技术吗?
C ++:
#include <iostream>
int square(int i) {
i = i * i;
return i;
}
int main() {
int i = square(2);
}
在Ubuntu 19.10上编译,具有:
g++ -o square_2 square_2.cpp
g ++版本:
g++ -v
Using built-in specs.
COLLECT_GCC=g++
COLLECT_LTO_WRAPPER=/usr/lib/gcc/x86_64-linux-gnu/9/lto-wrapper
OFFLOAD_TARGET_NAMES=nvptx-none:hsa
OFFLOAD_TARGET_DEFAULT=1
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --with-pkgversion='Ubuntu 9.2.1-9ubuntu2' --with-bugurl=file:///usr/share/doc/gcc-9/README.Bugs --enable-languages=c,ada,c++,go,brig,d,fortran,objc,obj-c++,gm2 --prefix=/usr --with-gcc-major-version-only --program-suffix=-9 --program-prefix=x86_64-linux-gnu- --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --libdir=/usr/lib --enable-nls --enable-bootstrap --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --with-default-libstdcxx-abi=new --enable-gnu-unique-object --disable-vtable-verify --enable-plugin --enable-default-pie --with-system-zlib --with-target-system-zlib=auto --enable-multiarch --disable-werror --with-arch-32=i686 --with-abi=m64 --with-multilib-list=m32,m64,mx32 --enable-multilib --with-tune=generic --enable-offload-targets=nvptx-none,hsa --without-cuda-driver --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 9.2.1 20191008 (Ubuntu 9.2.1-9ubuntu2)
来自gdb的相关程序集:
0x55555555516d push rbp
0x55555555516e mov rbp,rsp
0x555555555171 mov DWORD PTR [rbp-0x4],edi
0x555555555174 mov eax,DWORD PTR [rbp-0x4]
0x555555555177 imul eax,eax
0x55555555517a mov DWORD PTR [rbp-0x4],eax
0x55555555517d mov eax,DWORD PTR [rbp-0x4]
0x555555555180 pop rbp
0x555555555181 ret
我使用黄色突出显示指示值何时更新,使用绿色突出显示堆栈指针当前指向的内存内容。
On x86-64 under the SysV ABI, it is legal for a function to write up to 128 bytes below the stack pointer; see Section 3.2.2. This area is known as the red zone. Any other code that might use the same stack is required to leave those 128 bytes alone.