为什么我的静态变量在运行时不对齐?

问题描述 投票:0回答:1

我正在编写测试代码以处理2幂次边界上的内存,并且我需要在1MB边界上有1MB的内存块用于测试。该代码适用于小块,但不适用于大块。最终,我发现这是因为我应该对齐的数据未对齐1MB边界。

(显然,我可以解决此问题,但是我想知道发生了什么。)

此代码编译时没有警告,objdump说变量位于合理的地址,但是当我运行它时,它是在4K边界而不是1M上对齐的​​。

cat x.c ; gcc --version ; uname -a ; gcc -Wall x.c && ( objdump -x a.out | grep test_data  ; ./a.out )
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct data {
  char memory[1024*1024];
};

static struct data __attribute__(( aligned( 0x100000 ) )) test_data = { 0 };

int main( int argc, const char **argv )
{
  printf( "test_data is actually here: %p\n", &test_data );
  return 0;
}


gcc (Ubuntu 7.4.0-1ubuntu1~18.04.1) 7.4.0
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

Linux Lubuntutu 4.15.0-72-generic #81-Ubuntu SMP Tue Nov 26 12:20:02 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
0000000000400000 l     O .bss   0000000000100000              test_data
test_data is actually here: 0x5600cb9fe000

在gdb下运行很有趣:

Reading symbols from ./a.out...done.
(gdb) display &test_data
1: &test_data = (struct data *) 0x400000 <test_data>
(gdb) start
Temporary breakpoint 1 at 0x659: file x.c, line 13.
Starting program: /tmp/a.out 

Temporary breakpoint 1, main (argc=1, argv=0x7fffffffe038) at x.c:13
13    printf( "test_data is actually here: %p\n", &test_data );
1: &test_data = (struct data *) 0x555555954000 <test_data>
(gdb) print &test_data.memory[16]
$1 = 0x555555954010 <test_data+16> ""
(gdb) c
Continuing.
test_data is actually here: 0x555555954000
c linux ld
1个回答
0
投票

这是加载程序功能。

[代码在内存中的移动量相近,大概是地址空间布局随机化的一部分,但它是4k页的随机数,这将破坏程序所要求的任何较粗的对齐方式。

(答案从问题中提取-最初由Simon Willcocks提出。

© www.soinside.com 2019 - 2024. All rights reserved.