Recently I realized that you can do this in 64-bit code:
const size_t kLowStackSize = 1024UL * 1024UL * 4UL;
void *low_stack = mmap(NULL, kLowStackSize, PROT_READ | PROT_WRITE,
MAP_PRIVATE | MAP_ANONYMOUS | MAP_32BIT, -1, 0);
struct __attribute__((packed, aligned(16))) {
int32_t address;
int16_t segment;
} target = {(uint32_t) (uint64_t) code, 0x23};
asm volatile(
"mov %%rsp, %%r8\n"
"mov %[stack], %%rsp\n"
"push %%r8\n"
"lcall *(%[target])\n"
"pop %%rsp"
:
: [stack] "r" (low_stack + kLowStackSize), [target] "r" (&target)
: "r8");
where code
points to a piece of 32-bit code located on an executable page in the lower 4GiB of the address space, and 0x23
is the value of the __USER32_CS
segment selector in Linux's x86 headers. I don't know whether the attributes are necessary for the jump target, but I added the for good measure. Of course, to make the far return possible this calling code itself must be located somewhere in the lower 4 GiB of the virtual address space. I found that placing it into main
is sufficient.
I understand this is mostly useless (there are no 32-bit libraries loaded, the calling conventions are different, etc.) and prone to breakage (the value of __USER32_CS
is not part of Linux's userspace-facing API).
My question: Is there a simple way to demonstrate the the target of the call is indeed executed in 32-bit mode? Are the any practical uses (existing software of libraries leveraging it, or at least not-so-impractical possibilites) for this kind of call?
XOR EAX, EAX; DEC RAX; RAX; LRET
because that, due to the REX prefix being interpreted asDEC EAX
in 32bit mode, evaluates there toXOR EAX, EAX; DEC EAX; DEC EAX; LRET
(firstDEC
from the prefix, secondDEC
the actual two-byte-opcode) and therefore gives a different result.__USER_CS
and__USER32_CS
in userspace, I think I will accept yours.