内存分配优化:从堆到堆栈

时间:2016-06-23 02:47:10

标签: c optimization memory-management malloc heap-memory

我正在对32-bit x86架构上的二进制文件执行一些逆向工程任务。

最近,我发现了从C源代码到汇编程序的一些有趣的优化。

例如,原始源代码就像(此源代码来自openssl library):

powerbufFree = (unsigned char *)malloc(powerbufLen);

编译后(gcc version 4.8.4 -O3),汇编代码如下:

807eaa0: cmp eax, 0xbff                         # eax holds the length of the buf.
807eaa5: mov dword ptr [ebp-0x68], eax          # store the length of powerbuf on the stack
807eaa8: jnle 0x807ec60                         # 0x807ec60 refers to the malloc
807eaae: mov edx, eax
807eab0: add eax, 0x5e
807eab3: and eax, 0xfffffff0
807eab6: sub esp, eax
807eab8: lea eax, ptr [esp+0x23]
807eabc: and eax, 0xffffffc0
807eabf: add eax, 0x40
807ead3: mov dword ptr [ebp-0x60], eax  # store the base addr of the buf on the stack.

令我惊讶的是,buf确实是在堆栈上分配的!这对我来说似乎是堆分配器的优化,但我不确定。

所以这是我的问题,以上优化(malloc - >堆栈分配)似乎对任何人都很熟悉吗?是否有意义?任何人都可以提供一些关于此类优化的手册/规范吗?

1 个答案:

答案 0 :(得分:5)

来自source of bn_exp.c:

0634 #ifdef alloca
0635     if (powerbufLen < 3072)
0636         powerbufFree = alloca(powerbufLen+MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH);
0637     else
0638 #endif
0639     if ((powerbufFree=(unsigned char*)OPENSSL_malloc(powerbufLen+MOD_EXP_CTIME_MIN_CACHE_LINE_WIDTH)) == NULL)
0640         goto err;

请注意0xbff等于3071.在支持它的系统上,alloca执行堆栈分配。 GNU version使用了Linux,而BSD implementations从AT&amp; T(according to FreeBSD)从32V UNIX复制了此API。

您只查看了第639行。但是如果定义了alloca,那么C代码将与您的程序集匹配。

如果分配相对较小,优化本身通常用于避免将malloc用于临时缓冲区的费用。对于C.1999,可以使用VLA(因为C.2011,VLA是可选功能)。

有时,优化只使用一些合理的小尺寸的固定大小的缓冲区。例如:

char tmp_buf[1024];
char *tmp = tmp_buf;

if (bytes_needed > 1024) {
    tmp = malloc(bytes_needed);
}
/* ... */
if (tmp != tmp_buf) {
    free(tmp);
}
相关问题