1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
const X86 = struct {
gprs: std.enums.EnumArray(GprName, Gpr),
/// The first 8 registers here intentionally match the order of registers in the x86 instruction
/// encoding. This order is inherited by the PUSHA instruction and the DWARF register mappings,
/// among other things.
pub const GprName = enum {
// zig fmt: off
eax, ecx, edx, ebx,
esp, ebp, esi, edi,
eip,
// zig fmt: on
};
pub const Gpr = u32;
pub inline fn current() X86 {
var ctx: X86 = undefined;
asm volatile (
\\ movl %%eax, 0x00(%%edi)
\\ movl %%ecx, 0x04(%%edi)
\\ movl %%edx, 0x08(%%edi)
\\ movl %%ebx, 0x0c(%%edi)
\\ movl %%esp, 0x10(%%edi)
\\ movl %%ebp, 0x14(%%edi)
\\ movl %%esi, 0x18(%%edi)
\\ movl %%edi, 0x1c(%%edi)
\\ call 1f
\\1:
\\ popl 0x20(%%edi)
:
: [gprs] "{edi}" (&ctx.gprs.values),
: .{ .memory = true });
return ctx;
}
pub fn getFp(ctx: *const X86) usize {
return ctx.gprs.get(.ebp);
}
pub fn getPc(ctx: *const X86) usize {
return ctx.gprs.get(.eip);
}
pub fn dwarfRegisterBytes(ctx: *X86, register_num: u16) DwarfRegisterError![]u8 {
// System V Application Binary Interface Intel386 Architecture Processor Supplement Version 1.1
// § 2.4.2 "DWARF Register Number Mapping"
switch (register_num) {
// The order of `Gpr` intentionally matches DWARF's mappings.
//
// x86-macos sometimes uses different mappings (ebp and esp are reversed when the unwind
// information is from `__eh_frame`). This deviation is not considered here, because
// x86-macos is a deprecated target which is not supported by the Zig Standard Library.
0...8 => return @ptrCast(&ctx.gprs.values[register_num]),
9 => return error.UnsupportedRegister, // eflags
11...18 => return error.UnsupportedRegister, // st0 - st7
21...28 => return error.UnsupportedRegister, // xmm0 - xmm7
29...36 => return error.UnsupportedRegister, // mm0 - mm7
39 => return error.UnsupportedRegister, // mxcsr
40...45 => return error.UnsupportedRegister, // es, cs, ss, ds, fs, gs
48 => return error.UnsupportedRegister, // tr
49 => return error.UnsupportedRegister, // ldtr
93...100 => return error.UnsupportedRegister, // k0 - k7 (AVX-512)
else => return error.InvalidRegister,
}
}
}