background image

Vol. 3A 5-23

PROTECTION

The SYSCALL instruction does not save the stack pointer, and the SYSRET instruction does not restore it. It is likely 
that the OS system-call handler will change the stack pointer from the user stack to the OS stack. If so, it is the 
responsibility of software first to save the user stack pointer. This might be done by user code, prior to executing 
SYSCALL, or by the OS system-call handler after SYSCALL.
Because the SYSRET instruction does not modify the stack pointer, it is necessary for software to switch back to the 
user stack. The OS may load the user stack pointer (if it was saved after SYSCALL) before executing SYSRET; alter-
natively, user code may load the stack pointer (if it was saved before SYSCALL) after receiving control from 
SYSRET.
If the OS loads the stack pointer before executing SYSRET, it must ensure that the handler of any interrupt or 
exception delivered between restoring the stack pointer and successful execution of SYSRET is not invoked with the 
user stack. It can do so using approaches such as the following:

External interrupts. The OS can prevent an external interrupt from being delivered by clearing EFLAGS.IF 
before loading the user stack pointer.

Nonmaskable interrupts (NMIs). The OS can ensure that the NMI handler is invoked with the correct stack by 
using the interrupt stack table (IST) mechanism for gate 2 (NMI) in the IDT (see Section 6.14.5, “Interrupt 
Stack Table”).

General-protection exceptions (#GP). The SYSRET instruction generates #GP(0) if the value of RCX is not 
canonical. The OS can address this possibility using one or more of the following approaches:
— Confirming that the value of RCX is canonical before executing SYSRET.
— Using paging to ensure that the SYSCALL instruction will never save a non-canonical value into RCX.
— Using the IST mechanism for gate 13 (#GP) in the IDT.

5.9 PRIVILEGED 

INSTRUCTIONS

Some of the system instructions (called “privileged instructions”) are protected from use by application programs. 
The privileged instructions control system functions (such as the loading of system registers). They can be 
executed only when the CPL is 0 (most privileged). If one of these instructions is executed when the CPL is not 0, 
a general-protection exception (#GP) is generated. The following system instructions are privileged instructions:

LGDT — Load GDT register.

LLDT — Load LDT register.

Figure 5-14.  MSRs Used by SYSCALL and SYSRET

63

32 31

0

63

0

63

0

Target RIP for 64-bit Mode Calling Program

SYSRET CS and SS

SYSCALL CS and SS

48 47

IA32_STAR

IA32_LSTAR

IA32_FMASK

32 31

SYSCALL EFLAGS Mask

Reserved

Reserved