Search code examples
gcclinker

working of “–print-memory-usage” in the GCC?


how does GCC provide a breakdown of the memory used in each memory region defined in the linker file using --print-memory-usage?


Solution

  • GCC just forwards --print-memory-usage to the linker, usually ld:

    https://sourceware.org/binutils/docs-2.40/ld.html#index-memory-usage

    gcc (or g++ for that matter) has no idea about memory usage, and the linker can only report usage of static storage memory, which is usually:

    .text: The "program" or code to be executed. This might be located in RAM or in ROM (e.g. Flash) depending on options and architecture.

    .rodata: Data in static storage that is read-only and does not need initialization at run-time. This is usually located in non-volatile memory like ROM or Flash; but there are exceptions, one of which is avr-gcc.

    .data, .bss and COMMON: Data in RAM that's initialized during start-up by the CRT (C Runtime).

    Apart from these common setcions, there might be other sections like .init*, .boot, .jumptables etc, which again depend on the application and architecture.


    By its very nature, the linker (or assembler or compiler) cannot determine memory usage that unfolds at run-time, which is:

    • Stack usage: Non-static local variables that cannot be held in registers, alloca, ...

    • Heap usage: malloc, new and friends.

    What the compiler can do for you is -fstack-usage and similar, which generates a text file *.su for each translation unit. The compiler reports stack usage that's known at compile time (static) and unknown stack usage that arises at run-time (dynamic). The functions marked as static use the specified amount of stack space, without counting the usages of non-inlined callees.

    In order to know the complete stack usage (or a reliable upper bound), the dynamic call graph must be known. Even if it's known, GCC won't do the analysis four you. You will need other more elaborate tools to work out these metrics, e.g. by abstract interpretation or other means of static analysis.

    Notice that data collected at run-time, like dynamic stack usage analysis at run time, only provide a lower bound of memory usage (or execution time for that matter). However, for sound analysis like in safety-scitical apps, what you meed are upper bounds.