miri/shims/x86/
aesni.rs

1use rustc_middle::ty::Ty;
2use rustc_middle::ty::layout::LayoutOf as _;
3use rustc_span::Symbol;
4use rustc_target::callconv::{Conv, FnAbi};
5
6use crate::*;
7
8impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
9pub(super) trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
10    fn emulate_x86_aesni_intrinsic(
11        &mut self,
12        link_name: Symbol,
13        abi: &FnAbi<'tcx, Ty<'tcx>>,
14        args: &[OpTy<'tcx>],
15        dest: &MPlaceTy<'tcx>,
16    ) -> InterpResult<'tcx, EmulateItemResult> {
17        let this = self.eval_context_mut();
18        this.expect_target_feature_for_intrinsic(link_name, "aes")?;
19        // Prefix should have already been checked.
20        let unprefixed_name = link_name.as_str().strip_prefix("llvm.x86.aesni.").unwrap();
21
22        match unprefixed_name {
23            // Used to implement the _mm_aesdec_si128, _mm256_aesdec_epi128
24            // and _mm512_aesdec_epi128 functions.
25            // Performs one round of an AES decryption on each 128-bit word of
26            // `state` with the corresponding 128-bit key of `key`.
27            // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_aesdec_si128
28            "aesdec" | "aesdec.256" | "aesdec.512" => {
29                let [state, key] = this.check_shim(abi, Conv::C, link_name, args)?;
30                aes_round(this, state, key, dest, |state, key| {
31                    let key = aes::Block::from(key.to_le_bytes());
32                    let mut state = aes::Block::from(state.to_le_bytes());
33                    // `aes::hazmat::equiv_inv_cipher_round` documentation states that
34                    // it performs the same operation as the x86 aesdec instruction.
35                    aes::hazmat::equiv_inv_cipher_round(&mut state, &key);
36                    u128::from_le_bytes(state.into())
37                })?;
38            }
39            // Used to implement the _mm_aesdeclast_si128, _mm256_aesdeclast_epi128
40            // and _mm512_aesdeclast_epi128 functions.
41            // Performs last round of an AES decryption on each 128-bit word of
42            // `state` with the corresponding 128-bit key of `key`.
43            // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_aesdeclast_si128
44            "aesdeclast" | "aesdeclast.256" | "aesdeclast.512" => {
45                let [state, key] = this.check_shim(abi, Conv::C, link_name, args)?;
46
47                aes_round(this, state, key, dest, |state, key| {
48                    let mut state = aes::Block::from(state.to_le_bytes());
49                    // `aes::hazmat::equiv_inv_cipher_round` does the following operations:
50                    // state = InvShiftRows(state)
51                    // state = InvSubBytes(state)
52                    // state = InvMixColumns(state)
53                    // state = state ^ key
54                    // But we need to skip the InvMixColumns.
55                    // First, use a zeroed key to skip the XOR.
56                    aes::hazmat::equiv_inv_cipher_round(&mut state, &aes::Block::from([0; 16]));
57                    // Then, undo the InvMixColumns with MixColumns.
58                    aes::hazmat::mix_columns(&mut state);
59                    // Finally, do the XOR.
60                    u128::from_le_bytes(state.into()) ^ key
61                })?;
62            }
63            // Used to implement the _mm_aesenc_si128, _mm256_aesenc_epi128
64            // and _mm512_aesenc_epi128 functions.
65            // Performs one round of an AES encryption on each 128-bit word of
66            // `state` with the corresponding 128-bit key of `key`.
67            // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_aesenc_si128
68            "aesenc" | "aesenc.256" | "aesenc.512" => {
69                let [state, key] = this.check_shim(abi, Conv::C, link_name, args)?;
70                aes_round(this, state, key, dest, |state, key| {
71                    let key = aes::Block::from(key.to_le_bytes());
72                    let mut state = aes::Block::from(state.to_le_bytes());
73                    // `aes::hazmat::cipher_round` documentation states that
74                    // it performs the same operation as the x86 aesenc instruction.
75                    aes::hazmat::cipher_round(&mut state, &key);
76                    u128::from_le_bytes(state.into())
77                })?;
78            }
79            // Used to implement the _mm_aesenclast_si128, _mm256_aesenclast_epi128
80            // and _mm512_aesenclast_epi128 functions.
81            // Performs last round of an AES encryption on each 128-bit word of
82            // `state` with the corresponding 128-bit key of `key`.
83            // https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_mm_aesenclast_si128
84            "aesenclast" | "aesenclast.256" | "aesenclast.512" => {
85                let [state, key] = this.check_shim(abi, Conv::C, link_name, args)?;
86                aes_round(this, state, key, dest, |state, key| {
87                    let mut state = aes::Block::from(state.to_le_bytes());
88                    // `aes::hazmat::cipher_round` does the following operations:
89                    // state = ShiftRows(state)
90                    // state = SubBytes(state)
91                    // state = MixColumns(state)
92                    // state = state ^ key
93                    // But we need to skip the MixColumns.
94                    // First, use a zeroed key to skip the XOR.
95                    aes::hazmat::cipher_round(&mut state, &aes::Block::from([0; 16]));
96                    // Then, undo the MixColumns with InvMixColumns.
97                    aes::hazmat::inv_mix_columns(&mut state);
98                    // Finally, do the XOR.
99                    u128::from_le_bytes(state.into()) ^ key
100                })?;
101            }
102            // Used to implement the _mm_aesimc_si128 function.
103            // Performs the AES InvMixColumns operation on `op`
104            "aesimc" => {
105                let [op] = this.check_shim(abi, Conv::C, link_name, args)?;
106                // Transmute to `u128`
107                let op = op.transmute(this.machine.layouts.u128, this)?;
108                let dest = dest.transmute(this.machine.layouts.u128, this)?;
109
110                let state = this.read_scalar(&op)?.to_u128()?;
111                let mut state = aes::Block::from(state.to_le_bytes());
112                aes::hazmat::inv_mix_columns(&mut state);
113
114                this.write_scalar(Scalar::from_u128(u128::from_le_bytes(state.into())), &dest)?;
115            }
116            // TODO: Implement the `llvm.x86.aesni.aeskeygenassist` when possible
117            // with an external crate.
118            _ => return interp_ok(EmulateItemResult::NotSupported),
119        }
120        interp_ok(EmulateItemResult::NeedsReturn)
121    }
122}
123
124// Performs an AES round (given by `f`) on each 128-bit word of
125// `state` with the corresponding 128-bit key of `key`.
126fn aes_round<'tcx>(
127    ecx: &mut crate::MiriInterpCx<'tcx>,
128    state: &OpTy<'tcx>,
129    key: &OpTy<'tcx>,
130    dest: &MPlaceTy<'tcx>,
131    f: impl Fn(u128, u128) -> u128,
132) -> InterpResult<'tcx, ()> {
133    assert_eq!(dest.layout.size, state.layout.size);
134    assert_eq!(dest.layout.size, key.layout.size);
135
136    // Transmute arguments to arrays of `u128`.
137    assert_eq!(dest.layout.size.bytes() % 16, 0);
138    let len = dest.layout.size.bytes() / 16;
139
140    let u128_array_layout = ecx.layout_of(Ty::new_array(ecx.tcx.tcx, ecx.tcx.types.u128, len))?;
141
142    let state = state.transmute(u128_array_layout, ecx)?;
143    let key = key.transmute(u128_array_layout, ecx)?;
144    let dest = dest.transmute(u128_array_layout, ecx)?;
145
146    for i in 0..len {
147        let state = ecx.read_scalar(&ecx.project_index(&state, i)?)?.to_u128()?;
148        let key = ecx.read_scalar(&ecx.project_index(&key, i)?)?.to_u128()?;
149        let dest = ecx.project_index(&dest, i)?;
150
151        let res = f(state, key);
152
153        ecx.write_scalar(Scalar::from_u128(res), &dest)?;
154    }
155
156    interp_ok(())
157}