1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
extern crate proc_macro;

use proc_macro::TokenStream;
use quote::{quote, format_ident};
use syn::parse::{Parse, ParseStream};
use syn::{ItemEnum, Visibility, Expr, Error};
use syn::{Ident, Token, braced, parse_macro_input, LitStr, LitInt};

struct VMCSFieldArguments {
    width: u64,
    access: LitStr,
}

impl Parse for VMCSFieldArguments {
    fn parse(input: ParseStream) -> Result<Self, Error> {
        let width_lit: LitInt = input.parse()?;
        input.parse::<Token![,]>()?;
        let access: LitStr = input.parse()?;
        let width: u64 = width_lit.base10_parse().expect("Invalid width");

        if width != 16 && width != 32 && width != 64 {
            panic!("width can only be \"16\", \"32\", and \"64\"");
        }

        if access.value().as_str() != "R" && access.value().as_str() != "RW" {
            panic!("access can only be \"R\" or \"RW\"");
        }

        Ok(VMCSFieldArguments {
            width,
            access,
        })
    }
}

///
/// Macro usage:
///
/// #[vmcs_field({16, 32, 64}, {"R", "RW"})
///
/// This can only be used for "enums"
#[proc_macro_attribute]
pub fn vmcs_access(args: TokenStream, input: TokenStream) -> TokenStream {
    let VMCSFieldArguments {
        width,
        access,
    } = parse_macro_input!(args as VMCSFieldArguments);

    let enum_stream = parse_macro_input!(input as ItemEnum);
    let name = enum_stream.ident.clone();
    let vm_size = format_ident!("u{}", width);

    let read_fn = quote! {
        pub unsafe fn read(&self) -> #vm_size {
            let mut value: u64;
            asm!("vmread $1, $0": "=r" (value): "r" (*self as u64));
            value as #vm_size
        }
    };

    let write_fn = quote! {
        pub unsafe fn write(&self, value: #vm_size) {
            asm!("vmwrite $0, $1":: "r" (value as u64), "r" (*self as u64));
        }
    };

    if access.value().as_str() == "R" {
        return TokenStream::from(
            quote! {
                #enum_stream

                impl #name {
                    #read_fn
                }
            });
    } else {
        return TokenStream::from(
            quote! {
                #enum_stream

                impl #name {
                    #read_fn
                    #write_fn
                }
            });
    }
}

struct PageTable {
    visibility: Visibility,
    table: Ident,
    valid_flags: Expr,
    valid_huge_flags: Expr,
    huge_flags: Expr,
    normal_shift: Expr,
    huge_shift: Expr,
    index_shift: Expr,
}

///
/// Format of special syntax:
///
/// page_table! (
///     pub struct <table> {
///         valid_flags: <valid_bits>,
///         valid_huge_flags: <valid_huge_flags>,
///         huge_flags: <huge_flags>,
///         normal_shift: <normal_shift>,
///         huge_shift: <huge_shift>,
///         index_shift: <index_shift>,
///     }
/// )
///
impl Parse for PageTable {
    fn parse(input: ParseStream) -> Result<Self, Error> {
        let visibility: Visibility = input.parse()?;
        input.parse::<Token![struct]>()?;
        let table: Ident = input.parse()?;

        let content;
        braced!(content in input);

        let mut valid_flags: Option<Expr> = None;
        let mut valid_huge_flags: Option<Expr> = None;
        let mut huge_flags: Option<Expr> = None;
        let mut normal_shift: Option<Expr> = None;
        let mut huge_shift: Option<Expr> = None;
        let mut index_shift: Option<Expr> = None;

        loop {
            if content.is_empty() {
                break;
            }

            let ident: Ident = content.parse()?;
            content.parse::<Token![:]>()?;

            match ident.to_string().as_str() {
                "valid_flags" => { valid_flags.replace(content.parse()?); },
                "valid_huge_flags" => { valid_huge_flags.replace(content.parse()?); },
                "huge_flags" => { huge_flags.replace(content.parse()?); },
                "normal_shift" => { normal_shift.replace(content.parse()?); },
                "huge_shift" => { huge_shift.replace(content.parse()?); },
                "index_shift" => { index_shift.replace(content.parse()?); },
                _ => panic!("wrong identifier"),
            }

            content.parse::<Token![,]>()?;

            if content.is_empty() {
                break;
            }

        }

        Ok(PageTable {
            visibility: visibility,
            table: table,
            valid_flags: valid_flags.expect("missing 'valid_flags' attribute"),
            valid_huge_flags: valid_huge_flags.expect("missing 'valid_huge_flags' attribute"),
            huge_flags: huge_flags.expect("missing 'huge_flags' attribute"),
            normal_shift: normal_shift.expect("missing 'normal_shift' attribute"),
            huge_shift: huge_shift.expect("missing 'huge_shift' attribute"),
            index_shift: index_shift.expect("missing 'index_shift' attribute"),
        })
    }
}

#[proc_macro]
pub fn construct_pt_types(input: TokenStream) -> TokenStream {
    let PageTable {
        visibility,
        table,
        valid_flags,
        valid_huge_flags,
        huge_flags,
        normal_shift,
        huge_shift,
        index_shift,
    } = parse_macro_input!(input as PageTable);

    let entry_name = format_ident!("{}Entry", table);
    //let convert_macro_name = format_ident!("cast_to_{}", table);

    let output = quote! {
        #[repr(packed)]
        #[derive(Debug, Clone, Copy)]
        #visibility struct #entry_name(u64);

        #[repr(packed)]
        #visibility struct #table {
            entries: [#entry_name; 512],
        }

        impl core::ops::Index<u64> for #table {
            type Output = #entry_name;

            fn index(&self, address: u64) -> &Self::Output {
                let index = ((address) >> (#index_shift)) & 0x1ff;
                &self.entries[index as usize]
            }
        }

        impl core::ops::IndexMut<u64> for #table {
            fn index_mut(&mut self, address: u64) -> &mut Self::Output {
                let index = ((address) >> (#index_shift)) & 0x1ff;
                &mut self.entries[index as usize]
            }
        }

/* -- "[E0658]: procedural macros cannot expand to macro definitions"
        #[macro_export]
        macro_rules! #convert_macro_name {
            ($x:expr) => {
                unsafe_cast!($x => &mut #table)
            }
        }
*/

        impl #entry_name {
            pub fn new(address: u64, flags: u64) -> Option<Self> {
                let mut shift: u8 = #normal_shift;
                let mut valid: u64 = #valid_flags;

                if #huge_flags != 0 && ((flags & #huge_flags) == #huge_flags) {
                    valid |= #valid_huge_flags;
                    shift = #huge_shift;
                }

                let aligned = ((address & ((1 << shift) - 1)) == 0);
                if !aligned || ((valid & flags) != flags) {
                    return None;
                }

                Some(Self(address | flags))
            }

            pub fn raw(&self) -> u64 {
                self.0
            }

            pub fn huge(&self) -> bool {
                (self.0 & #huge_flags) == #huge_flags
            }
        }
    };

    TokenStream::from(output)
}