Search code examples
embeddedexecutableramloaderreadonly

How do sections of RAM get marked as read-only in Embedded Systems


When we build an executable, and it gets loaded into RAM, my understanding is that the .text and .ro setions should be loaded into read-only memory locations. With an operating system and a virtual memory controller I can understand how the different sections could get loaded to the right memory locations.

However, considering a bare-metal system without an operating system and an ARM chip for example. How is the read-only attribute of those sections achieved. They could be stored in ROM or Flash? But then doesn't everything get loaded into RAM anyways? Thanks in advance.


Solution

  • It depends.

    Objects marked as const are checked by the compiler, that no statement writes into them. Executable code cannot be a target of such statements. Both are commonly linked into the sections .text and .rodata, respectively, or similar, as you write.

    Embedded systems with ROM (masked ROM, EPROM, EEPROM, Flash, are all regarded the same here) will commonly have these sections in the ROM. Usually there is no need to copy it into precious RAM. Just look at the sizes of ROM and RAM, and you know, why. Such systems execute the machine code directly from the ROM, and read constant data from the ROM.

    Embedded systems with RAM faster than ROM may copy .text and/or .rodata into RAM for better performance. If such a system has a memory management unit with protection capability, the loader will set these ranges to "read-only" after copying. Now the hardware stops your program from writing into this memory. BTW, I would not call this loader an "operating system", it is more a "bootloader".

    If you have a system with RAM and no support to write-protect it, and it uses RAM for machine code and constant data, you need to rest on the correctness of your compiler, and of your program.