In x86 architecture, there are some segment registers such as SS, CS, DS, FS, GS.
I know that these 16bit registers indicates the
LDT, GDT entries(as segment selector) and MMU references
this(GDT, LDT) to calculate segment base + offset value. and check permissions
and etc.
What I am curious is: who fills in the segment register contents based on what? The kernel scheduler?
And what happens when application changes the segment register value itself?
I know that only CS can not be changed because it has CPL of current CPU.
but other registers(SS, DS…) can be changed.
The bootloader does. ISRs and exception handlers do. System call handlers do. The scheduler does. Some other parts may need to. The registers are assumed to be private and have to be saved and restored during various context switches. And, of course, they need to be initialized at some prior point too.
Based on what needs to be in those registers. Their values are not universally shared between different parts of the OS and between different programs.
What happens? It either changes it successfully or causes an exception (typically, #GP) and then happens whatever the exception handler does or, if there’s none or it’s buggy, a triple fault, a CPU reset and probably a reboot of the entire computer.
You can change any segment register if you somehow know what else can be loaded into it at the current privilege level. If your program is at level 3 and there are two code segments with DPL=3 set up for it by the OS, the program can use either of them for the CS register. If you don’t know that, you’re more likely to just crash the program.
Get yourself a copy of and read:
Intel® 64 and IA-32 Architectures Software Developer’s Manual Combined Volumes: 1, 2A, 2B, 3A and 3B.
You can either go by the relevant chapters (memory management, interrupt/exception handling, task switching) or search for specific registers (e.g. CS or SS or DS) or look at the description of and pseudo-code for specific instructions.
You’re not going to get any more precise answers to the questions this vague.