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?
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.