Call gate (Intel)
A call gate in the Intel x86 architecture (specifically in protected mode and long mode) is a special descriptor used to transfer control from one privilege level (ring) to another. It acts as a protected entry point to a code segment residing at a different privilege level. Unlike a direct call which can only occur within the same privilege level, a call gate provides a controlled and secure mechanism to execute code at a more privileged level.
The call gate itself is stored in either the Global Descriptor Table (GDT) or the Local Descriptor Table (LDT). It contains the following essential information:
- Selector: The segment selector of the code segment that the call gate points to. This determines the actual code that will be executed at the target privilege level.
- Offset: The offset within the target code segment where execution will begin.
- Parameter Count: The number of stack words that will be copied from the caller's stack to the callee's stack. This allows the caller to pass arguments to the code running at the higher privilege level.
- Privilege Level: Specifies the privilege level (0-3) required to access the call gate. This ensures that only trusted code can initiate a privilege level change through this specific gate.
When a CALL
instruction targets a call gate, the following sequence of events generally occurs:
- Privilege Check: The processor verifies that the caller's current privilege level (CPL) is numerically greater than or equal to the privilege level required to access the call gate. This is crucial for security. If the check fails, a general protection fault (#GP) is raised.
- Stack Switch: If the call gate transitions to a more privileged level, a stack switch occurs. The processor retrieves the appropriate stack segment and stack pointer from the Task State Segment (TSS) associated with the target privilege level. The original stack segment and stack pointer are saved.
- Parameter Copying: The specified number of parameters are copied from the caller's stack to the new stack.
- Control Transfer: The processor transfers control to the code segment and offset specified in the call gate.
- Privilege Level Change: The CPL is updated to reflect the privilege level of the target code segment.
Call gates are a fundamental part of the Intel architecture's protection model and are used extensively in operating systems to implement system calls and other privileged operations. They allow user-mode applications to securely request services from the kernel, preventing direct access to protected resources and ensuring system stability. The use of call gates helps prevent malicious or erroneous user-level code from compromising the entire system. Upon returning from the call gate, the parameters are not automatically popped from the initial stack as the parameters are copied to the new stack, meaning a RET
instruction with a pop value of the copied parameters needs to be done on the new stack for cleanup.