Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the reason for having read-only data defined in .text section?

Tags:

c++

assembly

I am learning assembly and low-level programming itself and reading a book about it. It is said there that we can put any data inside the .text section of an elf file but of course we can't mutate it because of different permissions of pages/segments. But it was not told there, what was the reason for it, for having data inside .text section. I was also told by many C++ programmers that g++ compiler puts

static const char DATA[] = "SOME DATA";

inside the .text section too. I wonder, why not to put this data inside .rodata section, what is the purpose? And if .text is used, what to store in the .rodata then?

The main question is about this behaviour in long mode.

like image 289
Victor Polevoy Avatar asked Jun 26 '18 11:06

Victor Polevoy


People also ask

Is the text section read-only?

Also, the text segment is often read-only, to prevent a program from accidentally modifying its instructions.

What is the read-only data section?

In software, read-only is a safety measure which protects files and data from accidental or intentional alteration or deletion and may be imposed only for select users or groups of users.

Why are code segments read-only?

The code segment in memory is typically read-only and has a fixed size, so on embedded systems it can usually be placed in read-only memory (ROM), without the need for loading. If the code segment is not read-only, then the particular architecture allows self-modifying code.

What does the .text section contain?

The (somewhat oddly named) text section (segment) usually contains the compiled binary code, as you suspect. An executable often contains other types of data besides the code, like initialized variable values, resources, debug information, relocation data, and so on, which are placed in sections with other names.


1 Answers

Traditionally, read-only data was placed in the text section for two reasons:

  • the text section is not writable, so memory protection can catch accidental writes to read-only data and make your program crash instead
  • with a memory-management unit (MMU), multiple instances of the same process can share one copy of the text section (as its guaranteed to be the same in all instances of the program), saving memory

On ELF targets, this scheme was modified a bit. Read-only data is now placed in the new .rodata section which is like the .text section except it also cannot be executed, preventing certain attack vectors. The advantages remain.

like image 141
fuz Avatar answered Oct 06 '22 00:10

fuz