RE: [PATCH] x86/ia32: Do not modify the DPL bits for a null selector

From: Li, Xin3
Date: Fri Jul 07 2023 - 00:11:09 EST


> > When a null selector is to be loaded into a segment register,
> > reload_segments() sets its DPL bits to 3. Later when an IRET
> > instruction loads it, it zeros the segment register. The two
> > operations offset each other to actually effect a nop.
> >
> > Fix it by not modifying the DPL bits for a null selector.
>
> Maybe this is the right thing but this needs some serious comments about what is
> going on.
>
> In particular how does sel <= 3 equate to a null selector? Is that defined
> somewhere?

In protected mode, a NULL selector (values 0000 through 0003) can be
loaded into DS, ES, FS, or GS registers without causing a protection
exception.

This can be found at the description of instruction LDS/LES/LFS/LGS/LSS,
in section 3.3 "instructions (A-L)" of Intel SDM Volume 2, Instruction Set
Reference.

>At a minimum you should have static asserts to make certain no
> one redefines the first 4 segment selectors as anything else, if you want to refer to
> them by number instead of testing for specific properties.

Bits 0 and 1 of a selector are NOT used to index the GDT or IDT, thus
selector values 0 ~ 3 all point to the first entry of the GDT, i.e.,
the null selector.

Thus 3 as a selector is the same as 0, and it doesn't matter to change
it or not. But when IRET sees an invalid segment register in ES, FS, GS,
and DS, it sets it to 0, making 0 a preferred null selector value.

The sigreturn selftest sets DS of its signal context to 0 and then checks
if it's still 0 after sigreturn. And it passes. However if it sets DS to
any other null selector value, e.g., 1, it fails. For FRED, if we don't
modify the DPL bits, the test passes, because ERETU doesn't change segment
registers.

> As written this looks like it requires an enormous amount of knowledge about
> how other parts of the code works, to be comprehensible or to change safely.
> That level of non-local knowledge should be unnecessary.