0

As I know all the segment registers or selectors are set to point to the same starting address of the 4gb segment in 32 bit protected mode flat model. So how the stack segment functionality is implemented which is it starts at one of the top address and grows downwards or heap segment functionality which grows upward.

Also how some portion of the memory is owned by the OS in the 4gb address space, is implemented?

Kaustav
  • 741
  • 1
  • 9
  • 18

1 Answers1

1

The stack segment (SS) is no different from the other ones: it begins at 0 and length 4GB.

The funny thing with x86 segmentation is that it is independent from paging. So the OS implements paging over th flat memory model. It is in paging where the OS implements memory protection.

Thus, when the OS starts a thread, it allocates a few memory pages for the stack, in the flat segment, and makes the ESP/'RSP' register to point to it. The important detail is to reserve the first page just below the stack and not to allocate it. This way, stack overflows can be easily detected as page faults.

The memory of the kernel usually mapped to the higher part of the 4GB memory map, but it is inaccesible to normal user code because of the page protection bits.

rodrigo
  • 94,151
  • 12
  • 143
  • 190
  • I can understand from your answer. So how the OS sets that the stack will grow from higher address to lower address? And also how the start address of the stack is decided for the thread? – Kaustav May 31 '16 at 14:25
  • In X86 the stack always grows down. That is because `push` decreases `ESP` and `pop` iincreases it. That is by design. About where the stack is allocated, that's up to the OS. Remember that a 32-bit process has 4GB of address space and that each thread stack is typically 1MB, so there is plenty of spare room. – rodrigo May 31 '16 at 18:13
  • 1
    @Kaustav: In a multi-thread process, each thread will have its own stack, but all those threads share address space. So the OS must allocate the stacks one next to the other. That old story about the stack growing down, the heap growing up, and a lot of free space in between is not true any more in modern OSes. – rodrigo May 31 '16 at 18:17