Where do I find the assembly that creates a static variable in the .data section of my C program?

后端 未结 4 567
终归单人心
终归单人心 2021-01-05 21:27

First time poster. 2nd year CS student.

I am exploring the creation of static variables in the .data section of the Virtual Address Space in the context of a C sourc

4条回答
  •  礼貌的吻别
    2021-01-05 21:54

    As zneak answered in the object file there is no code initializing the staticVar variable. The actual bytes of the .data section are directly in the test.o file. If you define a const variable gcc will put it into .rodata section by default.

    The disassembly you obtained most probably by objdump --disassemble-all file.o. Maybe the disassembly of data confused you into thinking that it is a real code. For normal use I would recommend objdump --disassemble file.o which disassembles just sections containing actual machine code.

    You can get detailed relevant information by running: objdump -xdst test.o

    Shortly about the life of staticVar

    1. gcc puts the variable (including its value) to the .data section as it is a static initialized variable. The size of the section is just for the variable, the address is not determined yet. See objdump -xdst test.o.
    2. Linker determines the address of the .data section (and others) as the object files are known. In the .data section other variables from other object files appears. See objdump -xdst test.
    3. When the binary test is executed the contained segments are directly mapped (mmap()) to the address space of the process so the value of staticVar is directly read from the test binary (possibly when needed). Then the dynamic linked ld-linux maps shared libraries like libc. See cat /proc/$PID/maps or pmap $PID when the process with $PID is loaded in memory.

    There could be a variable initialization code in C

    Just try to change the staticVar to a local non-static variable (i.e. stored on the stack by default):

       int staticVar[10] = {1,2,3,4,5,6,7,8,9,-1};
    

    By default gcc will generate an initialization code directly in the main() function. Just see objdump -xdst test.o. This is because the stack variables are allocated (so their addresses are determined) at run-time.

提交回复
热议问题