In one my previous blog posts, I wrote about Segmentation Faults, although, I didn’t give much explanation to what a segment was and how it is used within the translation process.
Memory segmentation is the method of dividing the computer’s primary memory into segments, each segment will contain two parts which I’ll attempt to explain later. Memory segmentation is one of the protection mechanisms which can be used to restrict access to certain areas of memory.
It’s important to understand, that the CPU can only understand machine instructions (binary), and that higher level languages are simply used for programmers to be able to write large and complex programs without much difficulty. The language above machine code is called Assembly, which enables programmers to create very fast and small programs to perform very specific tasks.
It’s important to remember that programs can only use virtual memory (logical addresses), which have to be translated into physical addresses which the CPU will be able to use. You also may be wondering what is a linear address? A linear address is the logical address and the base of the segment. There are a few different segments: CS (Program Code); SS (Stack); DS, ES (Data).
With this blog post, you’ll hopefully also understand what role the GDT (Global Descriptor Table) and LDT (Local Descriptor Table) have with segmentation and the operating system.
These tables are only present in Protected Mode, which enabled programs to use things such as virtual memory and paging. When the system is first booted, the CPU is running in Real Mode, which simply uses physical memory addresses and allows direct access to hardware.
In Protected Mode, each segment contains a segment descriptor, which is stored within the GDT and LDT, a segment descriptor contains information about the descriptor privilege level (CPU Rings or more commonly Kernel Mode and User Mode), and the base and limit addresses of the segment which describe the beginning and the end of the segment.
You may want to also read about Memory Models, this a good thread to start with – Understanding Flat Memory Model and Segmented Memory Model.