Gilgamesz
Gilgamesz

Reputation: 5073

Section bss and loading them to the memory

Here https://web.stanford.edu/~ouster/cgi-bin/cs140-winter16/pintos/pintos_6.html it is written:

The first step in main() is to call bss_init(), which clears out the kernel's "BSS", which is the traditional name for a segment that should be initialized to all zeros. In most C implementations, whenever you declare a variable outside a function without providing an initializer, that variable goes into the BSS. Because it's all zeros, the BSS isn't stored in the image that the loader brought into memory. We just use memset() to zero it out.

I highlighted a part I don't understand. Why bss section "equal to 0" causes that behaviour? The question is meaningful if and only if it is general point not implementation-dependant.

Upvotes: 2

Views: 1468

Answers (1)

Peter Cordes
Peter Cordes

Reputation: 364483

Instead of storing N bytes of all zero, all that's stored for the BSS is a length.

The entire point of having the BSS separate from the data section is to enable this space-saving. So it doesn't cause the behaviour, it enables it.

You can think of it as run-length encoding for everything that can be initialized with zeros.


So, what do we zero out?

The memory that we allocated when loading an image that says it needs an N-byte BSS.

Note that in non-toy OSes, all the BSS pages usually start out copy-on-write mapped to a single physical page of zeroes (shared system-wide). When a process dirties such a page, it triggers a "minor" page fault and the kernel gives it a private zeroed page as backing for the now-dirty virtual page. (And on return from the minor fault, the store instruction that faulted the first time execute successfully, causing a TLB miss to read the newly-updated page table.)

Upvotes: 3

Related Questions