Skip to main content

tvm_ffi/reflection/
unsafe_init.rs

1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements.  See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership.  The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License.  You may obtain a copy of the License at
9 *
10 *   http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied.  See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20//! Objects made with every field undefined, for reflection to set the fields,
21//! such as when a JSON graph is read back or `__ffi_init__` runs.
22//!
23//! A Rust reference is never null, so an object cannot hold a null reference
24//! for its setters to overwrite later; instead [`unsafe_init`]
25//! allocates the object zeroed, and a field holding all-zero bytes that are no
26//! value of its type ([`AnyCompatible::is_undefined`]) is undefined. The field
27//! setter writes an undefined field without dropping it, the field getter reads
28//! it as None, and the object's deleter drops only the defined fields, all
29//! through raw pointers, so no undefined field is ever viewed as its type.
30
31use std::alloc::Layout;
32use std::ffi::c_void;
33use std::panic::{AssertUnwindSafe, catch_unwind};
34use std::sync::atomic::AtomicU64;
35
36use crate::object::{Object, ObjectArc, ObjectCore, ObjectRef, ObjectRefCore};
37use crate::tvm_ffi_sys::TVMFFIObjectDeleterFlagBitMask::{
38    kTVMFFIObjectDeleterFlagBitMaskStrong, kTVMFFIObjectDeleterFlagBitMaskWeak,
39};
40use crate::tvm_ffi_sys::{COMBINED_REF_COUNT_BOTH_ONE, TVMFFIObject, TVMFFIObjectHandle};
41use crate::type_traits::AnyCompatible;
42use crate::{Error, INTERNAL_ERROR};
43
44/// An object type whose object can start with every field undefined, for
45/// reflection to set the fields.
46///
47/// The creator that `#[rs_object]` registers for its type makes the object with
48/// [`unsafe_init`], which a JSON graph read back, `__ffi_init__` and
49/// `__ffi_new__` then fill. `#[rs_object]` implements it for its object, so the
50/// parent's object must implement it too: [`Object`] does, and so does a
51/// binding with `#[object(rs_parent)]` on its [`derive(Object)`](crate::derive::Object).
52///
53/// `__ffi_init__` leaves an `init_off` field as the creator made it, so such a
54/// field's type must take all-zero bytes as a value, as a scalar, `Option<T>`
55/// or `Any` does; the type's registration fails otherwise.
56///
57/// # Safety
58///
59/// `drop_defined_fields` drops each defined field of the object and no
60/// undefined one, the parent's object's included.
61pub unsafe trait UnsafeInit: ObjectCore {
62    /// Drops the defined fields of the object at `this`, the parent's object's
63    /// included, and leaves the undefined ones.
64    ///
65    /// # Safety
66    ///
67    /// `this` points to an object that [`unsafe_init`] made, which is not used
68    /// afterwards.
69    #[doc(hidden)]
70    unsafe fn drop_defined_fields(this: *mut Self);
71}
72
73// The header holds nothing to drop.
74unsafe impl UnsafeInit for Object {
75    unsafe fn drop_defined_fields(_this: *mut Self) {}
76}
77
78/// Drops the field at `field` unless it is undefined.
79///
80/// # Safety
81///
82/// `field` points to a field of an object, defined or undefined, which is not
83/// used afterwards.
84#[inline]
85unsafe fn drop_if_defined<F: AnyCompatible>(field: *mut F) {
86    unsafe {
87        if !F::is_undefined(field) {
88            std::ptr::drop_in_place(field);
89        }
90    }
91}
92
93/// The field drops of a derived `UnsafeInit`, chosen by method resolution:
94/// `(&FieldPtr(field)).drop_field()` drops an [`AnyCompatible`] field or an
95/// [`Any`](crate::Any) unless it is undefined, and accepts any other field
96/// only if it has no drop glue.
97#[doc(hidden)]
98pub mod field_drop {
99    use super::drop_if_defined;
100    use crate::any::Any;
101    use crate::type_traits::AnyCompatible;
102
103    pub struct FieldPtr<F>(pub *mut F);
104
105    pub trait DropDefined {
106        /// # Safety
107        ///
108        /// The pointer is to a field of an object, defined or undefined,
109        /// which is not used afterwards.
110        unsafe fn drop_field(&self);
111    }
112
113    impl<F: AnyCompatible> DropDefined for FieldPtr<F> {
114        #[inline(always)]
115        unsafe fn drop_field(&self) {
116            unsafe { drop_if_defined(self.0) }
117        }
118    }
119
120    // All-zero bytes are `None`.
121    impl DropDefined for FieldPtr<Any> {
122        #[inline(always)]
123        unsafe fn drop_field(&self) {
124            unsafe { std::ptr::drop_in_place(self.0) }
125        }
126    }
127
128    pub trait DropNothing {
129        fn drop_field(&self);
130    }
131
132    impl<F> DropNothing for &FieldPtr<F> {
133        #[inline(always)]
134        fn drop_field(&self) {
135            const {
136                assert!(
137                    !std::mem::needs_drop::<F>(),
138                    "a field of an `UnsafeInit` object must implement `AnyCompatible`, be \
139                     `Any`, or have no drop glue"
140                )
141            };
142        }
143    }
144}
145
146/// An object of `T` with every field undefined, zero-filled, for reflection
147/// to set the fields through their setters.
148///
149/// The [`ObjectRef`] views only the object's header, which is valid all along.
150///
151/// # Safety
152///
153/// Each field that all-zero bytes leave undefined
154/// ([`AnyCompatible::is_undefined`]) is set before the object is viewed as a
155/// `T` (by a cast of the reference) or the field is read as its type. Until
156/// then, only the reflection's field setters and getters reach the fields.
157pub unsafe fn unsafe_init<T: UnsafeInit>() -> ObjectRef {
158    let layout = Layout::new::<T>();
159    unsafe {
160        let ptr = std::alloc::alloc_zeroed(layout);
161        if ptr.is_null() {
162            std::alloc::handle_alloc_error(layout);
163        }
164        std::ptr::write(
165            ptr.cast::<TVMFFIObject>(),
166            TVMFFIObject {
167                combined_ref_count: AtomicU64::new(COMBINED_REF_COUNT_BOTH_ONE),
168                type_index: T::type_index(),
169                __padding: 0,
170                deleter: Some(unsafe_init_deleter::<T>),
171            },
172        );
173        // SAFETY: `ObjectRef` is the view of any object.
174        ObjectRef::from_data(ObjectArc::from_raw(ptr.cast::<Object>()))
175    }
176}
177
178/// The deleter of an object that [`unsafe_init`] made, which may go before
179/// reflection sets every field, as when a JSON graph lacks one.
180unsafe extern "C" fn unsafe_init_deleter<T: UnsafeInit>(ptr: *mut c_void, flags: i32) {
181    // Objects made here drop field by field and never run the struct's `Drop::drop`.
182    unsafe {
183        if flags & kTVMFFIObjectDeleterFlagBitMaskStrong as i32 != 0 {
184            T::drop_defined_fields(ptr.cast::<T>());
185        }
186        if flags & kTVMFFIObjectDeleterFlagBitMaskWeak as i32 != 0 {
187            std::alloc::dealloc(ptr.cast::<u8>(), Layout::new::<T>());
188        }
189    }
190}
191
192/// The creator of `T` (`TVMFFITypeMetadata::creator`) that `#[rs_object]`
193/// registers: it writes the owned handle of an object that [`unsafe_init`]
194/// made to `result`.
195///
196/// # Safety
197///
198/// `result` is valid for writes.
199#[doc(hidden)]
200pub unsafe extern "C" fn unsafe_init_creator<T: UnsafeInit>(
201    result: *mut TVMFFIObjectHandle,
202) -> i32 {
203    let made = catch_unwind(AssertUnwindSafe(|| unsafe {
204        let object = unsafe_init::<T>();
205        let handle = ObjectArc::into_raw(ObjectRef::into_data(object));
206        std::ptr::write(result, handle as TVMFFIObjectHandle);
207    }));
208    match made {
209        Ok(()) => 0,
210        Err(_) => {
211            let message = format!("panic while creating an object of `{}`", T::TYPE_KEY);
212            Error::set_raised(&Error::new(INTERNAL_ERROR, &message));
213            -1
214        }
215    }
216}
217
218#[cfg(test)]
219mod tests {
220    use std::mem::MaybeUninit;
221
222    use crate::tvm_ffi_sys::dlpack::{DLDevice, DLDeviceType};
223    use crate::type_traits::AnyCompatible;
224    use crate::{Array, BigInt, String};
225
226    fn zero_is_undefined<F: AnyCompatible>() -> bool {
227        let zero = MaybeUninit::<F>::zeroed();
228        unsafe { F::is_undefined(zero.as_ptr()) }
229    }
230
231    fn is_undefined<F: AnyCompatible>(value: F) -> bool {
232        unsafe { F::is_undefined(&value) }
233    }
234
235    #[test]
236    fn all_zero_bytes_are_undefined_where_they_are_no_value() {
237        assert!(zero_is_undefined::<Array<i64>>());
238        assert!(zero_is_undefined::<String>());
239        assert!(zero_is_undefined::<BigInt>());
240        assert!(zero_is_undefined::<DLDevice>());
241
242        assert!(!zero_is_undefined::<i64>());
243        assert!(!zero_is_undefined::<bool>());
244        // `None`, through the niche of a reference or through a tag.
245        assert!(!zero_is_undefined::<Option<Array<i64>>>());
246        assert!(!zero_is_undefined::<Option<DLDevice>>());
247        assert!(!zero_is_undefined::<Option<String>>());
248    }
249
250    #[test]
251    fn values_are_defined() {
252        let cpu = DLDevice {
253            device_type: DLDeviceType::kDLCPU as i32,
254            device_id: 0,
255        };
256        assert!(!is_undefined(Array::<i64>::new()));
257        assert!(!is_undefined(String::from("")));
258        assert!(!is_undefined(BigInt::from(0_i64)));
259        assert!(!is_undefined(cpu));
260        assert!(!is_undefined(Some(cpu)));
261        assert!(!is_undefined(None::<DLDevice>));
262        assert!(!is_undefined(None::<Array<i64>>));
263    }
264}