aboutsummaryrefslogtreecommitdiff
path: root/rust/qemu-api/src/vmstate.rs
blob: a262c315da13c465b49c52e9f45b9919285edf66 (plain)
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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
// Copyright 2024, Linaro Limited
// Author(s): Manos Pitsidianakis <manos.pitsidianakis@linaro.org>
// SPDX-License-Identifier: GPL-2.0-or-later

//! Helper macros to declare migration state for device models.
//!
//! This module includes three families of macros:
//!
//! * [`vmstate_unused!`](crate::vmstate_unused) and
//!   [`vmstate_of!`](crate::vmstate_of), which are used to express the
//!   migration format for a struct.  This is based on the [`VMState`] trait,
//!   which is defined by all migrateable types.
//!
//! * helper macros to declare a device model state struct, in particular
//!   [`vmstate_subsections`](crate::vmstate_subsections) and
//!   [`vmstate_fields`](crate::vmstate_fields).
//!
//! * direct equivalents to the C macros declared in
//!   `include/migration/vmstate.h`. These are not type-safe and should not be
//!   used if the equivalent functionality is available with `vmstate_of!`.

use core::{marker::PhantomData, mem, ptr::NonNull};

pub use crate::bindings::{VMStateDescription, VMStateField};
use crate::{
    bindings::{self, VMStateFlags},
    zeroable::Zeroable,
};

/// This macro is used to call a function with a generic argument bound
/// to the type of a field.  The function must take a
/// [`PhantomData`]`<T>` argument; `T` is the type of
/// field `$field` in the `$typ` type.
///
/// # Examples
///
/// ```
/// # use qemu_api::call_func_with_field;
/// # use core::marker::PhantomData;
/// const fn size_of_field<T>(_: PhantomData<T>) -> usize {
///     std::mem::size_of::<T>()
/// }
///
/// struct Foo {
///     x: u16,
/// };
/// // calls size_of_field::<u16>()
/// assert_eq!(call_func_with_field!(size_of_field, Foo, x), 2);
/// ```
#[macro_export]
macro_rules! call_func_with_field {
    // Based on the answer by user steffahn (Frank Steffahn) at
    // https://users.rust-lang.org/t/inferring-type-of-field/122857
    // and used under MIT license
    ($func:expr, $typ:ty, $($field:tt).+) => {
        $func(loop {
            #![allow(unreachable_code)]
            const fn phantom__<T>(_: &T) -> ::core::marker::PhantomData<T> { ::core::marker::PhantomData }
            // Unreachable code is exempt from checks on uninitialized values.
            // Use that trick to infer the type of this PhantomData.
            break ::core::marker::PhantomData;
            break phantom__(&{ let value__: $typ; value__.$($field).+ });
        })
    };
}

/// Workaround for lack of `const_refs_static`: references to global variables
/// can be included in a `static`, but not in a `const`; unfortunately, this
/// is exactly what would go in the `VMStateField`'s `info` member.
///
/// This enum contains the contents of the `VMStateField`'s `info` member,
/// but as an `enum` instead of a pointer.
#[allow(non_camel_case_types)]
pub enum VMStateFieldType {
    null,
    vmstate_info_bool,
    vmstate_info_int8,
    vmstate_info_int16,
    vmstate_info_int32,
    vmstate_info_int64,
    vmstate_info_uint8,
    vmstate_info_uint16,
    vmstate_info_uint32,
    vmstate_info_uint64,
    vmstate_info_timer,
}

/// Workaround for lack of `const_refs_static`.  Converts a `VMStateFieldType`
/// to a `*const VMStateInfo`, for inclusion in a `VMStateField`.
#[macro_export]
macro_rules! info_enum_to_ref {
    ($e:expr) => {
        unsafe {
            match $e {
                $crate::vmstate::VMStateFieldType::null => ::core::ptr::null(),
                $crate::vmstate::VMStateFieldType::vmstate_info_bool => {
                    ::core::ptr::addr_of!($crate::bindings::vmstate_info_bool)
                }
                $crate::vmstate::VMStateFieldType::vmstate_info_int8 => {
                    ::core::ptr::addr_of!($crate::bindings::vmstate_info_int8)
                }
                $crate::vmstate::VMStateFieldType::vmstate_info_int16 => {
                    ::core::ptr::addr_of!($crate::bindings::vmstate_info_int16)
                }
                $crate::vmstate::VMStateFieldType::vmstate_info_int32 => {
                    ::core::ptr::addr_of!($crate::bindings::vmstate_info_int32)
                }
                $crate::vmstate::VMStateFieldType::vmstate_info_int64 => {
                    ::core::ptr::addr_of!($crate::bindings::vmstate_info_int64)
                }
                $crate::vmstate::VMStateFieldType::vmstate_info_uint8 => {
                    ::core::ptr::addr_of!($crate::bindings::vmstate_info_uint8)
                }
                $crate::vmstate::VMStateFieldType::vmstate_info_uint16 => {
                    ::core::ptr::addr_of!($crate::bindings::vmstate_info_uint16)
                }
                $crate::vmstate::VMStateFieldType::vmstate_info_uint32 => {
                    ::core::ptr::addr_of!($crate::bindings::vmstate_info_uint32)
                }
                $crate::vmstate::VMStateFieldType::vmstate_info_uint64 => {
                    ::core::ptr::addr_of!($crate::bindings::vmstate_info_uint64)
                }
                $crate::vmstate::VMStateFieldType::vmstate_info_timer => {
                    ::core::ptr::addr_of!($crate::bindings::vmstate_info_timer)
                }
            }
        }
    };
}

/// A trait for types that can be included in a device's migration stream.  It
/// provides the base contents of a `VMStateField` (minus the name and offset).
///
/// # Safety
///
/// The contents of this trait go straight into structs that are parsed by C
/// code and used to introspect into other structs.  Be careful.
pub unsafe trait VMState {
    /// The `info` member of a `VMStateField` is a pointer and as such cannot
    /// yet be included in the [`BASE`](VMState::BASE) associated constant;
    /// this is only allowed by Rust 1.83.0 and newer.  For now, include the
    /// member as an enum which is stored in a separate constant.
    const SCALAR_TYPE: VMStateFieldType = VMStateFieldType::null;

    /// The base contents of a `VMStateField` (minus the name and offset) for
    /// the type that is implementing the trait.
    const BASE: VMStateField;

    /// A flag that is added to another field's `VMStateField` to specify the
    /// length's type in a variable-sized array.  If this is not a supported
    /// type for the length (i.e. if it is not `u8`, `u16`, `u32`), using it
    /// in a call to [`vmstate_of!`](crate::vmstate_of) will cause a
    /// compile-time error.
    const VARRAY_FLAG: VMStateFlags = {
        panic!("invalid type for variable-sized array");
    };
}

/// Internal utility function to retrieve a type's `VMStateFieldType`;
/// used by [`vmstate_of!`](crate::vmstate_of).
pub const fn vmstate_scalar_type<T: VMState>(_: PhantomData<T>) -> VMStateFieldType {
    T::SCALAR_TYPE
}

/// Internal utility function to retrieve a type's `VMStateField`;
/// used by [`vmstate_of!`](crate::vmstate_of).
pub const fn vmstate_base<T: VMState>(_: PhantomData<T>) -> VMStateField {
    T::BASE
}

/// Internal utility function to retrieve a type's `VMStateFlags` when it
/// is used as the element count of a `VMSTATE_VARRAY`; used by
/// [`vmstate_of!`](crate::vmstate_of).
pub const fn vmstate_varray_flag<T: VMState>(_: PhantomData<T>) -> VMStateFlags {
    T::VARRAY_FLAG
}

/// Return the `VMStateField` for a field of a struct.  The field must be
/// visible in the current scope.
///
/// Only a limited set of types is supported out of the box:
/// * scalar types (integer and `bool`)
/// * the C struct `QEMUTimer`
/// * a transparent wrapper for any of the above (`Cell`, `UnsafeCell`,
///   [`BqlCell`](crate::cell::BqlCell), [`BqlRefCell`](crate::cell::BqlRefCell)
/// * a raw pointer to any of the above
/// * a `NonNull` pointer or a `Box` for any of the above
/// * an array of any of the above
///
/// In order to support other types, the trait `VMState` must be implemented
/// for them.
#[macro_export]
macro_rules! vmstate_of {
    ($struct_name:ty, $field_name:ident $([0 .. $num:ident $(* $factor:expr)?])? $(,)?) => {
        $crate::bindings::VMStateField {
            name: ::core::concat!(::core::stringify!($field_name), "\0")
                .as_bytes()
                .as_ptr() as *const ::std::os::raw::c_char,
            offset: $crate::offset_of!($struct_name, $field_name),
            $(.num_offset: $crate::offset_of!($struct_name, $num),)?
            // The calls to `call_func_with_field!` are the magic that
            // computes most of the VMStateField from the type of the field.
            info: $crate::info_enum_to_ref!($crate::call_func_with_field!(
                $crate::vmstate::vmstate_scalar_type,
                $struct_name,
                $field_name
            )),
            ..$crate::call_func_with_field!(
                $crate::vmstate::vmstate_base,
                $struct_name,
                $field_name
            )$(.with_varray_flag($crate::call_func_with_field!(
                    $crate::vmstate::vmstate_varray_flag,
                    $struct_name,
                    $num))
               $(.with_varray_multiply($factor))?)?
        }
    };
}

impl VMStateFlags {
    const VMS_VARRAY_FLAGS: VMStateFlags = VMStateFlags(
        VMStateFlags::VMS_VARRAY_INT32.0
            | VMStateFlags::VMS_VARRAY_UINT8.0
            | VMStateFlags::VMS_VARRAY_UINT16.0
            | VMStateFlags::VMS_VARRAY_UINT32.0,
    );
}

// Add a couple builder-style methods to VMStateField, allowing
// easy derivation of VMStateField constants from other types.
impl VMStateField {
    #[must_use]
    pub const fn with_version_id(mut self, version_id: i32) -> Self {
        assert!(version_id >= 0);
        self.version_id = version_id;
        self
    }

    #[must_use]
    pub const fn with_array_flag(mut self, num: usize) -> Self {
        assert!(num <= 0x7FFF_FFFFusize);
        assert!((self.flags.0 & VMStateFlags::VMS_ARRAY.0) == 0);
        assert!((self.flags.0 & VMStateFlags::VMS_VARRAY_FLAGS.0) == 0);
        if (self.flags.0 & VMStateFlags::VMS_POINTER.0) != 0 {
            self.flags = VMStateFlags(self.flags.0 & !VMStateFlags::VMS_POINTER.0);
            self.flags = VMStateFlags(self.flags.0 | VMStateFlags::VMS_ARRAY_OF_POINTER.0);
        }
        self.flags = VMStateFlags(self.flags.0 & !VMStateFlags::VMS_SINGLE.0);
        self.flags = VMStateFlags(self.flags.0 | VMStateFlags::VMS_ARRAY.0);
        self.num = num as i32;
        self
    }

    #[must_use]
    pub const fn with_pointer_flag(mut self) -> Self {
        assert!((self.flags.0 & VMStateFlags::VMS_POINTER.0) == 0);
        self.flags = VMStateFlags(self.flags.0 | VMStateFlags::VMS_POINTER.0);
        self
    }

    #[must_use]
    pub const fn with_varray_flag<T: VMState>(mut self, flag: VMStateFlags) -> VMStateField {
        assert!((self.flags.0 & VMStateFlags::VMS_ARRAY.0) != 0);
        self.flags = VMStateFlags(self.flags.0 & !VMStateFlags::VMS_ARRAY.0);
        self.flags = VMStateFlags(self.flags.0 | flag.0);
        self
    }

    #[must_use]
    pub const fn with_varray_multiply(mut self, num: u32) -> VMStateField {
        assert!(num <= 0x7FFF_FFFFu32);
        self.flags = VMStateFlags(self.flags.0 | VMStateFlags::VMS_MULTIPLY_ELEMENTS.0);
        self.num = num as i32;
        self
    }
}

// Transparent wrappers: just use the internal type

macro_rules! impl_vmstate_transparent {
    ($type:ty where $base:tt: VMState $($where:tt)*) => {
        unsafe impl<$base> VMState for $type where $base: VMState $($where)* {
            const SCALAR_TYPE: VMStateFieldType = <$base as VMState>::SCALAR_TYPE;
            const BASE: VMStateField = VMStateField {
                size: mem::size_of::<$type>(),
                ..<$base as VMState>::BASE
            };
            const VARRAY_FLAG: VMStateFlags = <$base as VMState>::VARRAY_FLAG;
        }
    };
}

impl_vmstate_transparent!(std::cell::Cell<T> where T: VMState);
impl_vmstate_transparent!(std::cell::UnsafeCell<T> where T: VMState);
impl_vmstate_transparent!(crate::cell::BqlCell<T> where T: VMState);
impl_vmstate_transparent!(crate::cell::BqlRefCell<T> where T: VMState);

// Scalar types using predefined VMStateInfos

macro_rules! impl_vmstate_scalar {
    ($info:ident, $type:ty$(, $varray_flag:ident)?) => {
        unsafe impl VMState for $type {
            const SCALAR_TYPE: VMStateFieldType = VMStateFieldType::$info;
            const BASE: VMStateField = VMStateField {
                size: mem::size_of::<$type>(),
                flags: VMStateFlags::VMS_SINGLE,
                ..Zeroable::ZERO
            };
            $(const VARRAY_FLAG: VMStateFlags = VMStateFlags::$varray_flag;)?
        }
    };
}

impl_vmstate_scalar!(vmstate_info_bool, bool);
impl_vmstate_scalar!(vmstate_info_int8, i8);
impl_vmstate_scalar!(vmstate_info_int16, i16);
impl_vmstate_scalar!(vmstate_info_int32, i32);
impl_vmstate_scalar!(vmstate_info_int64, i64);
impl_vmstate_scalar!(vmstate_info_uint8, u8, VMS_VARRAY_UINT8);
impl_vmstate_scalar!(vmstate_info_uint16, u16, VMS_VARRAY_UINT16);
impl_vmstate_scalar!(vmstate_info_uint32, u32, VMS_VARRAY_UINT32);
impl_vmstate_scalar!(vmstate_info_uint64, u64);
impl_vmstate_scalar!(vmstate_info_timer, bindings::QEMUTimer);

// Pointer types using the underlying type's VMState plus VMS_POINTER
// Note that references are not supported, though references to cells
// could be allowed.

macro_rules! impl_vmstate_pointer {
    ($type:ty where $base:tt: VMState $($where:tt)*) => {
        unsafe impl<$base> VMState for $type where $base: VMState $($where)* {
            const SCALAR_TYPE: VMStateFieldType = <T as VMState>::SCALAR_TYPE;
            const BASE: VMStateField = <$base as VMState>::BASE.with_pointer_flag();
        }
    };
}

impl_vmstate_pointer!(*const T where T: VMState);
impl_vmstate_pointer!(*mut T where T: VMState);
impl_vmstate_pointer!(NonNull<T> where T: VMState);

// Unlike C pointers, Box is always non-null therefore there is no need
// to specify VMS_ALLOC.
impl_vmstate_pointer!(Box<T> where T: VMState);

// Arrays using the underlying type's VMState plus
// VMS_ARRAY/VMS_ARRAY_OF_POINTER

unsafe impl<T: VMState, const N: usize> VMState for [T; N] {
    const SCALAR_TYPE: VMStateFieldType = <T as VMState>::SCALAR_TYPE;
    const BASE: VMStateField = <T as VMState>::BASE.with_array_flag(N);
}

#[doc(alias = "VMSTATE_UNUSED_BUFFER")]
#[macro_export]
macro_rules! vmstate_unused_buffer {
    ($field_exists_fn:expr, $version_id:expr, $size:expr) => {{
        $crate::bindings::VMStateField {
            name: c_str!("unused").as_ptr(),
            err_hint: ::core::ptr::null(),
            offset: 0,
            size: $size,
            start: 0,
            num: 0,
            num_offset: 0,
            size_offset: 0,
            info: unsafe { ::core::ptr::addr_of!($crate::bindings::vmstate_info_unused_buffer) },
            flags: VMStateFlags::VMS_BUFFER,
            vmsd: ::core::ptr::null(),
            version_id: $version_id,
            struct_version_id: 0,
            field_exists: $field_exists_fn,
        }
    }};
}

#[doc(alias = "VMSTATE_UNUSED_V")]
#[macro_export]
macro_rules! vmstate_unused_v {
    ($version_id:expr, $size:expr) => {{
        $crate::vmstate_unused_buffer!(None, $version_id, $size)
    }};
}

#[doc(alias = "VMSTATE_UNUSED")]
#[macro_export]
macro_rules! vmstate_unused {
    ($size:expr) => {{
        $crate::vmstate_unused_v!(0, $size)
    }};
}

#[doc(alias = "VMSTATE_SINGLE_TEST")]
#[macro_export]
macro_rules! vmstate_single_test {
    ($field_name:ident, $struct_name:ty, $field_exists_fn:expr, $version_id:expr, $info:expr, $size:expr) => {{
        $crate::bindings::VMStateField {
            name: ::core::concat!(::core::stringify!($field_name), 0)
                .as_bytes()
                .as_ptr() as *const ::std::os::raw::c_char,
            err_hint: ::core::ptr::null(),
            offset: $crate::offset_of!($struct_name, $field_name),
            size: $size,
            start: 0,
            num: 0,
            num_offset: 0,
            size_offset: 0,
            info: unsafe { $info },
            flags: VMStateFlags::VMS_SINGLE,
            vmsd: ::core::ptr::null(),
            version_id: $version_id,
            struct_version_id: 0,
            field_exists: $field_exists_fn,
        }
    }};
}

#[doc(alias = "VMSTATE_SINGLE")]
#[macro_export]
macro_rules! vmstate_single {
    ($field_name:ident, $struct_name:ty, $version_id:expr, $info:expr, $size:expr) => {{
        $crate::vmstate_single_test!($field_name, $struct_name, None, $version_id, $info, $size)
    }};
}

#[doc(alias = "VMSTATE_UINT32_V")]
#[macro_export]
macro_rules! vmstate_uint32_v {
    ($field_name:ident, $struct_name:ty, $version_id:expr) => {{
        $crate::vmstate_single!(
            $field_name,
            $struct_name,
            $version_id,
            ::core::ptr::addr_of!($crate::bindings::vmstate_info_uint32),
            ::core::mem::size_of::<u32>()
        )
    }};
}

#[doc(alias = "VMSTATE_UINT32")]
#[macro_export]
macro_rules! vmstate_uint32 {
    ($field_name:ident, $struct_name:ty) => {{
        $crate::vmstate_uint32_v!($field_name, $struct_name, 0)
    }};
}

#[doc(alias = "VMSTATE_ARRAY")]
#[macro_export]
macro_rules! vmstate_array {
    ($field_name:ident, $struct_name:ty, $length:expr, $version_id:expr, $info:expr, $size:expr) => {{
        $crate::bindings::VMStateField {
            name: ::core::concat!(::core::stringify!($field_name), 0)
                .as_bytes()
                .as_ptr() as *const ::std::os::raw::c_char,
            err_hint: ::core::ptr::null(),
            offset: $crate::offset_of!($struct_name, $field_name),
            size: $size,
            start: 0,
            num: $length as _,
            num_offset: 0,
            size_offset: 0,
            info: unsafe { $info },
            flags: VMStateFlags::VMS_ARRAY,
            vmsd: ::core::ptr::null(),
            version_id: $version_id,
            struct_version_id: 0,
            field_exists: None,
        }
    }};
}

#[doc(alias = "VMSTATE_UINT32_ARRAY_V")]
#[macro_export]
macro_rules! vmstate_uint32_array_v {
    ($field_name:ident, $struct_name:ty, $length:expr, $version_id:expr) => {{
        $crate::vmstate_array!(
            $field_name,
            $struct_name,
            $length,
            $version_id,
            ::core::ptr::addr_of!($crate::bindings::vmstate_info_uint32),
            ::core::mem::size_of::<u32>()
        )
    }};
}

#[doc(alias = "VMSTATE_UINT32_ARRAY")]
#[macro_export]
macro_rules! vmstate_uint32_array {
    ($field_name:ident, $struct_name:ty, $length:expr) => {{
        $crate::vmstate_uint32_array_v!($field_name, $struct_name, $length, 0)
    }};
}

#[doc(alias = "VMSTATE_STRUCT_POINTER_V")]
#[macro_export]
macro_rules! vmstate_struct_pointer_v {
    ($field_name:ident, $struct_name:ty, $version_id:expr, $vmsd:expr, $type:ty) => {{
        $crate::bindings::VMStateField {
            name: ::core::concat!(::core::stringify!($field_name), 0)
                .as_bytes()
                .as_ptr() as *const ::std::os::raw::c_char,
            err_hint: ::core::ptr::null(),
            offset: $crate::offset_of!($struct_name, $field_name),
            size: ::core::mem::size_of::<*const $type>(),
            start: 0,
            num: 0,
            num_offset: 0,
            size_offset: 0,
            info: ::core::ptr::null(),
            flags: VMStateFlags(VMStateFlags::VMS_STRUCT.0 | VMStateFlags::VMS_POINTER.0),
            vmsd: unsafe { $vmsd },
            version_id: $version_id,
            struct_version_id: 0,
            field_exists: None,
        }
    }};
}

#[doc(alias = "VMSTATE_ARRAY_OF_POINTER")]
#[macro_export]
macro_rules! vmstate_array_of_pointer {
    ($field_name:ident, $struct_name:ty, $num:expr, $version_id:expr, $info:expr, $type:ty) => {{
        $crate::bindings::VMStateField {
            name: ::core::concat!(::core::stringify!($field_name), 0)
                .as_bytes()
                .as_ptr() as *const ::std::os::raw::c_char,
            version_id: $version_id,
            num: $num as _,
            info: unsafe { $info },
            size: ::core::mem::size_of::<*const $type>(),
            flags: VMStateFlags(VMStateFlags::VMS_ARRAY.0 | VMStateFlags::VMS_ARRAY_OF_POINTER.0),
            offset: $crate::offset_of!($struct_name, $field_name),
            err_hint: ::core::ptr::null(),
            start: 0,
            num_offset: 0,
            size_offset: 0,
            vmsd: ::core::ptr::null(),
            struct_version_id: 0,
            field_exists: None,
        }
    }};
}

#[doc(alias = "VMSTATE_ARRAY_OF_POINTER_TO_STRUCT")]
#[macro_export]
macro_rules! vmstate_array_of_pointer_to_struct {
    ($field_name:ident, $struct_name:ty, $num:expr, $version_id:expr, $vmsd:expr, $type:ty) => {{
        $crate::bindings::VMStateField {
            name: ::core::concat!(::core::stringify!($field_name), 0)
                .as_bytes()
                .as_ptr() as *const ::std::os::raw::c_char,
            version_id: $version_id,
            num: $num as _,
            vmsd: unsafe { $vmsd },
            size: ::core::mem::size_of::<*const $type>(),
            flags: VMStateFlags(
                VMStateFlags::VMS_ARRAY.0
                    | VMStateFlags::VMS_STRUCT.0
                    | VMStateFlags::VMS_ARRAY_OF_POINTER.0,
            ),
            offset: $crate::offset_of!($struct_name, $field_name),
            err_hint: ::core::ptr::null(),
            start: 0,
            num_offset: 0,
            size_offset: 0,
            vmsd: ::core::ptr::null(),
            struct_version_id: 0,
            field_exists: None,
        }
    }};
}

#[doc(alias = "VMSTATE_CLOCK_V")]
#[macro_export]
macro_rules! vmstate_clock_v {
    ($field_name:ident, $struct_name:ty, $version_id:expr) => {{
        $crate::vmstate_struct_pointer_v!(
            $field_name,
            $struct_name,
            $version_id,
            ::core::ptr::addr_of!($crate::bindings::vmstate_clock),
            $crate::bindings::Clock
        )
    }};
}

#[doc(alias = "VMSTATE_CLOCK")]
#[macro_export]
macro_rules! vmstate_clock {
    ($field_name:ident, $struct_name:ty) => {{
        $crate::vmstate_clock_v!($field_name, $struct_name, 0)
    }};
}

#[doc(alias = "VMSTATE_ARRAY_CLOCK_V")]
#[macro_export]
macro_rules! vmstate_array_clock_v {
    ($field_name:ident, $struct_name:ty, $num:expr, $version_id:expr) => {{
        $crate::vmstate_array_of_pointer_to_struct!(
            $field_name,
            $struct_name,
            $num,
            $version_id,
            ::core::ptr::addr_of!($crate::bindings::vmstate_clock),
            $crate::bindings::Clock
        )
    }};
}

#[doc(alias = "VMSTATE_ARRAY_CLOCK")]
#[macro_export]
macro_rules! vmstate_array_clock {
    ($field_name:ident, $struct_name:ty, $num:expr) => {{
        $crate::vmstate_array_clock_v!($field_name, $struct_name, $name, 0)
    }};
}

/// Helper macro to declare a list of
/// ([`VMStateField`](`crate::bindings::VMStateField`)) into a static and return
/// a pointer to the array of values it created.
#[macro_export]
macro_rules! vmstate_fields {
    ($($field:expr),*$(,)*) => {{
        static _FIELDS: &[$crate::bindings::VMStateField] = &[
            $($field),*,
            $crate::bindings::VMStateField {
                flags: $crate::bindings::VMStateFlags::VMS_END,
                ..$crate::zeroable::Zeroable::ZERO
            }
        ];
        _FIELDS.as_ptr()
    }}
}

/// A transparent wrapper type for the `subsections` field of
/// [`VMStateDescription`].
///
/// This is necessary to be able to declare subsection descriptions as statics,
/// because the only way to implement `Sync` for a foreign type (and `*const`
/// pointers are foreign types in Rust) is to create a wrapper struct and
/// `unsafe impl Sync` for it.
///
/// This struct is used in the
/// [`vm_state_subsections`](crate::vmstate_subsections) macro implementation.
#[repr(transparent)]
pub struct VMStateSubsectionsWrapper(pub &'static [*const crate::bindings::VMStateDescription]);

unsafe impl Sync for VMStateSubsectionsWrapper {}

/// Helper macro to declare a list of subsections ([`VMStateDescription`])
/// into a static and return a pointer to the array of pointers it created.
#[macro_export]
macro_rules! vmstate_subsections {
    ($($subsection:expr),*$(,)*) => {{
        static _SUBSECTIONS: $crate::vmstate::VMStateSubsectionsWrapper = $crate::vmstate::VMStateSubsectionsWrapper(&[
            $({
                static _SUBSECTION: $crate::bindings::VMStateDescription = $subsection;
                ::core::ptr::addr_of!(_SUBSECTION)
            }),*,
            ::core::ptr::null()
        ]);
        _SUBSECTIONS.0.as_ptr()
    }}
}