Skip to main content

alef_component_runtime/
loader.rs

1use crate::host_services::ServicesHandle;
2use crate::stdio::SidecarProcess;
3use crate::{
4    ArtifactCache, COMPONENT_ABI_VERSION, COMPONENT_MANIFEST_SCHEMA, ComponentError, ComponentLockEntry,
5    ComponentManifest, HostServices,
6};
7use alef_component_abi::{
8    ABI_MAJOR_V1, ABI_MINOR_V1, AlefComponentEntryV1, AlefComponentV1, AlefContract, AlefHostApiV1, AlefOwnedBuffer,
9};
10use libloading::Library;
11use std::ffi::c_void;
12use std::marker::PhantomData;
13use std::ptr::NonNull;
14use std::sync::{Arc, Mutex, OnceLock};
15
16const MAX_DESCRIPTOR_STRING: usize = 16 * 1024;
17
18/// What a loaded component's descriptor must match.
19///
20/// `contract_name` identifies which of a component's `provides` entries this
21/// is for; `contract_hash` is that specific contract's hash, not the
22/// component-wide legacy `ComponentIdentity::contract_hash`. A component that
23/// provides several contracts is loaded once per contract, each through its
24/// own entry point (see [`crate::ComponentManager::ensure_contract`]), so each
25/// load only ever validates one contract's requirements.
26#[derive(Clone, Debug)]
27pub struct ComponentRequirements {
28    pub component_id: String,
29    pub contract_name: String,
30    pub contract_hash: [u8; 32],
31    pub feature_set_hash: Option<[u8; 32]>,
32}
33
34#[derive(Clone, Debug)]
35pub struct Runtime {
36    cache: ArtifactCache,
37}
38
39impl Runtime {
40    pub fn new(cache: ArtifactCache) -> Self {
41        Self { cache }
42    }
43
44    pub fn install_and_load(
45        &self,
46        entry: &ComponentLockEntry,
47        entry_symbol: &[u8],
48        requirements: &ComponentRequirements,
49        host: AlefHostApiV1,
50    ) -> Result<LoadedComponent, ComponentError> {
51        let cached = self.cache.install(entry)?;
52        validate_manifest(&cached.manifest, requirements)?;
53        LoadedComponent::load(cached.library, entry_symbol, requirements, host)
54    }
55}
56
57pub struct LoadedComponent {
58    library: Option<Arc<Library>>,
59    sidecar: Option<(Arc<SidecarProcess>, String)>,
60    _sidecar_descriptor: Option<Box<AlefComponentV1>>,
61    descriptor: NonNull<AlefComponentV1>,
62    host: Box<AlefHostApiV1>,
63    /// Keeps the context behind the host table's service callbacks alive with the component.
64    _services: Option<ServicesHandle>,
65    component_id: String,
66    component_version: String,
67}
68
69/// A live instance created by a component, paired with its typed C function table.
70///
71/// Dropping the instance invokes the component's own destructor while the
72/// originating dynamic library remains pinned.
73pub struct ComponentInstance<T: AlefContract> {
74    component: Arc<LoadedComponent>,
75    handle: NonNull<c_void>,
76    _contract: PhantomData<T>,
77}
78
79// SAFETY: native metadata is static and pinned; sidecar metadata is owned and immutable,
80// and its process serializes calls. Host callback context thread-safety is part of the
81// `AlefHostApiV1` contract supplied by the caller. ~keep
82unsafe impl Send for LoadedComponent {}
83unsafe impl Sync for LoadedComponent {}
84
85// SAFETY: the C ABI requires every contract method to take `&self` (see
86// `component::map_method`) and calls it through a plain function pointer, so the
87// component's own implementation is the only thing that can make concurrent access
88// unsound; the ABI async wrapper already calls back into an instance from a spawned
89// worker thread, so components are contractually required to tolerate this. The
90// instance handle itself is owned exclusively by this `ComponentInstance` for its
91// lifetime, with no interior aliasing on the host side. ~keep
92unsafe impl<T: AlefContract> Send for ComponentInstance<T> {}
93unsafe impl<T: AlefContract> Sync for ComponentInstance<T> {}
94
95impl LoadedComponent {
96    /// Load one contract's descriptor from a component's shared library.
97    ///
98    /// A component that provides several contracts exports one entry point
99    /// per contract (`alef_component_entry_v1_<contract>`, see
100    /// `alef::codegen::component::entry_point_symbol`); `entry_symbol` is that
101    /// NUL-terminated symbol name, so this loads exactly one contract's
102    /// descriptor per call even when the underlying `.so`/`.dylib`/`.dll` is
103    /// shared across several `LoadedComponent`s.
104    pub fn load(
105        path: impl Into<std::path::PathBuf>,
106        entry_symbol: &[u8],
107        requirements: &ComponentRequirements,
108        host: AlefHostApiV1,
109    ) -> Result<Self, ComponentError> {
110        Self::load_with_services(path, entry_symbol, requirements, host, None)
111    }
112
113    /// Like [`Self::load`], additionally publishing `services` through the host table's
114    /// `service_call` / `service_notify` callbacks. With `None` the service fields of `host`
115    /// are passed through unchanged (null by default, so components see no service table).
116    pub fn load_with_services(
117        path: impl Into<std::path::PathBuf>,
118        entry_symbol: &[u8],
119        requirements: &ComponentRequirements,
120        mut host: AlefHostApiV1,
121        services: Option<Arc<dyn HostServices>>,
122    ) -> Result<Self, ComponentError> {
123        let path = path.into();
124        host.struct_size = core::mem::size_of::<AlefHostApiV1>();
125        host.abi_major = ABI_MAJOR_V1;
126        host.abi_minor = ABI_MINOR_V1;
127        let services = services.map(ServicesHandle::new);
128        if let Some(handle) = &services {
129            handle.install(&mut host);
130        }
131        let host = Box::new(host);
132
133        let library = Arc::new(
134            unsafe { Library::new(&path) }.map_err(|error| ComponentError::LibraryLoad {
135                path: path.clone(),
136                message: error.to_string(),
137            })?,
138        );
139        let descriptor = unsafe {
140            let entry: libloading::Symbol<'_, AlefComponentEntryV1> = library
141                .get(entry_symbol)
142                .map_err(|error| ComponentError::MissingEntrypoint(error.to_string()))?;
143            let mut raw = core::ptr::null();
144            let status = entry(ABI_MAJOR_V1, host.as_ref(), &mut raw);
145            if !status.is_ok() {
146                return Err(ComponentError::EntrypointFailed(status.0));
147            }
148            NonNull::new(raw.cast_mut()).ok_or(ComponentError::InvalidDescriptor("null descriptor"))?
149        };
150
151        // Reject a too-small descriptor before a `&AlefComponentV1` reference is ever formed
152        // over it: forming that reference asserts the pointee is valid for
153        // `size_of::<AlefComponentV1>()` bytes, which is undefined behavior when the
154        // component actually returned a shorter, older-ABI struct.
155        unsafe { reject_undersized_descriptor(descriptor)? };
156        let validated = unsafe { validate_descriptor(descriptor.as_ref(), requirements)? };
157        pin_for_process(Arc::clone(&library));
158        Ok(Self {
159            library: Some(library),
160            sidecar: None,
161            _sidecar_descriptor: None,
162            descriptor,
163            host,
164            _services: services,
165            component_id: validated.0,
166            component_version: validated.1,
167        })
168    }
169
170    pub(crate) fn from_sidecar(
171        process: Arc<SidecarProcess>,
172        manifest: &ComponentManifest,
173        requirements: &ComponentRequirements,
174        host: AlefHostApiV1,
175    ) -> Result<Self, ComponentError> {
176        let component_id = manifest.identity.component.clone();
177        let component_version = manifest.identity.version.clone();
178        let mut descriptor = Box::new(AlefComponentV1 {
179            struct_size: core::mem::size_of::<AlefComponentV1>(),
180            abi_major: ABI_MAJOR_V1,
181            abi_minor: ABI_MINOR_V1,
182            component_id: alef_component_abi::AlefStr {
183                ptr: component_id.as_ptr().cast(),
184                len: component_id.len(),
185            },
186            component_version: alef_component_abi::AlefStr {
187                ptr: component_version.as_ptr().cast(),
188                len: component_version.len(),
189            },
190            contract_hash: requirements.contract_hash,
191            feature_set_hash: decode_hash(&manifest.identity.feature_hash)?,
192            contract: core::ptr::null(),
193            contract_size: 0,
194            create: None,
195            destroy: None,
196        });
197        Ok(Self {
198            library: None,
199            sidecar: Some((process, requirements.contract_name.clone())),
200            descriptor: NonNull::from(descriptor.as_mut()),
201            _sidecar_descriptor: Some(descriptor),
202            host: Box::new(host),
203            _services: None,
204            component_id,
205            component_version,
206        })
207    }
208
209    pub(crate) fn ensure_active(&self) -> Result<(), ComponentError> {
210        if let Some((process, _)) = &self.sidecar {
211            process.ensure_running()?;
212        }
213        Ok(())
214    }
215
216    /// Passive liveness probe: true when a sidecar connection is currently running, with no
217    /// healing side effect — unlike [`Self::ensure_active`], it never respawns. Status reporting
218    /// observes; only a real call may spend the restart budget.
219    pub(crate) fn is_active(&self) -> bool {
220        match &self.sidecar {
221            Some((process, _)) => process.is_running(),
222            None => true,
223        }
224    }
225
226    /// Invoke a named bytes-only method on this contract's stdio component.
227    ///
228    /// Native typed function tables require their generated bindings and do not implement
229    /// this operation. Stdio components likewise cannot expose typed C function tables.
230    pub fn invoke_bytes(&self, method: &str, payload: &[u8]) -> Result<Vec<u8>, ComponentError> {
231        let (process, contract) = self.sidecar.as_ref().ok_or(ComponentError::UnsupportedTransport(
232            "bytes invocation requires a stdio component",
233        ))?;
234        process.invoke(contract, method, payload)
235    }
236
237    #[must_use]
238    pub fn component_id(&self) -> &str {
239        &self.component_id
240    }
241
242    #[must_use]
243    pub fn component_version(&self) -> &str {
244        &self.component_version
245    }
246
247    #[must_use]
248    pub fn descriptor(&self) -> &AlefComponentV1 {
249        unsafe { self.descriptor.as_ref() }
250    }
251
252    #[must_use]
253    pub fn contract(&self) -> *const c_void {
254        self.descriptor().contract
255    }
256
257    #[must_use]
258    pub fn contract_size(&self) -> usize {
259        self.descriptor().contract_size
260    }
261
262    pub fn contract_table<T: AlefContract>(&self) -> Result<&T, ComponentError> {
263        if self.sidecar.is_some() {
264            return Err(ComponentError::UnsupportedTransport(
265                "stdio components support bytes invocation, not typed C function tables",
266            ));
267        }
268        contract_table_from_descriptor(self.descriptor())
269    }
270
271    /// Create an instance and bind it to a generated contract-table type.
272    pub fn instantiate<T: AlefContract>(self: &Arc<Self>) -> Result<ComponentInstance<T>, ComponentError> {
273        self.contract_table::<T>()?;
274        let create = self.descriptor().create.ok_or(ComponentError::MissingInstanceFactory)?;
275        self.descriptor()
276            .destroy
277            .ok_or(ComponentError::MissingInstanceDestructor)?;
278        let mut raw = core::ptr::null_mut();
279        let mut error = AlefOwnedBuffer::EMPTY;
280        let status = unsafe { create(self.host_api(), &mut raw, &mut error) };
281        if !status.is_ok() {
282            return Err(ComponentError::InstanceCreation {
283                status: status.0,
284                message: unsafe { take_owned_buffer(error) },
285            });
286        }
287        let handle = NonNull::new(raw).ok_or(ComponentError::NullInstance)?;
288        Ok(ComponentInstance {
289            component: Arc::clone(self),
290            handle,
291            _contract: PhantomData,
292        })
293    }
294
295    #[must_use]
296    pub fn host_api(&self) -> &AlefHostApiV1 {
297        &self.host
298    }
299
300    #[must_use]
301    pub fn strong_library_references(&self) -> usize {
302        self.library.as_ref().map_or(0, Arc::strong_count)
303    }
304}
305
306impl<T: AlefContract> ComponentInstance<T> {
307    #[must_use]
308    pub fn table(&self) -> &T {
309        // The table was validated before this instance was constructed.
310        self.component
311            .contract_table::<T>()
312            .expect("validated component contract table changed")
313    }
314
315    #[must_use]
316    pub fn handle(&self) -> *mut c_void {
317        self.handle.as_ptr()
318    }
319
320    #[must_use]
321    pub fn component(&self) -> &Arc<LoadedComponent> {
322        &self.component
323    }
324}
325
326impl<T: AlefContract> Drop for ComponentInstance<T> {
327    fn drop(&mut self) {
328        if let Some(destroy) = self.component.descriptor().destroy {
329            unsafe { destroy(self.handle.as_ptr()) };
330        }
331    }
332}
333
334/// Copy an owned buffer's bytes into a `Vec<u8>` and release the original
335/// allocation through its own `free` callback.
336///
337/// Generated contract proxies use this to convert a component's
338/// `AlefOwnedBuffer` results into owned Rust values without re-implementing
339/// buffer ownership handling in every generated snippet.
340///
341/// # Safety
342///
343/// `buffer` must be a valid `AlefOwnedBuffer`: `ptr` must be non-null and
344/// valid for `len` bytes whenever `len > 0`, and `free` (if present) must be
345/// safe to call with this buffer's own `context`, `ptr`, `len`, and
346/// `capacity`.
347#[must_use]
348pub unsafe fn take_owned_bytes(buffer: AlefOwnedBuffer) -> Vec<u8> {
349    let bytes = if buffer.ptr.is_null() || buffer.len == 0 {
350        Vec::new()
351    } else {
352        // SAFETY: upheld by this function's caller contract.
353        unsafe { core::slice::from_raw_parts(buffer.ptr, buffer.len) }.to_vec()
354    };
355    if let Some(free) = buffer.free {
356        // SAFETY: upheld by this function's caller contract.
357        unsafe { free(buffer.context, buffer.ptr, buffer.len, buffer.capacity) };
358    }
359    bytes
360}
361
362/// Like [`take_owned_bytes`], but lossily decodes the bytes as UTF-8.
363///
364/// Generated proxies use this to turn a component's error buffer into a
365/// `String` for constructing the contract's error type; a component that
366/// returns non-UTF-8 error text gets a replacement-character message instead
367/// of a panic or a dropped allocation.
368///
369/// # Safety
370///
371/// Same obligations as [`take_owned_bytes`].
372#[must_use]
373pub unsafe fn take_owned_text(buffer: AlefOwnedBuffer) -> String {
374    // SAFETY: upheld by this function's caller contract.
375    String::from_utf8_lossy(&unsafe { take_owned_bytes(buffer) }).into_owned()
376}
377
378unsafe fn take_owned_buffer(buffer: AlefOwnedBuffer) -> String {
379    let message = if buffer.ptr.is_null() {
380        if buffer.len == 0 {
381            String::new()
382        } else {
383            "component returned an invalid error buffer".to_string()
384        }
385    } else {
386        String::from_utf8_lossy(unsafe { core::slice::from_raw_parts(buffer.ptr, buffer.len) }).into_owned()
387    };
388    if let Some(free) = buffer.free {
389        unsafe { free(buffer.context, buffer.ptr, buffer.len, buffer.capacity) };
390    }
391    message
392}
393
394fn contract_table_from_descriptor<T: AlefContract>(descriptor: &AlefComponentV1) -> Result<&T, ComponentError> {
395    if descriptor.contract_hash != T::CONTRACT_HASH
396        || descriptor.contract_size < core::mem::size_of::<T>()
397        || descriptor.contract.is_null()
398        || !(descriptor.contract as usize).is_multiple_of(core::mem::align_of::<T>())
399    {
400        return Err(ComponentError::InvalidContractTable);
401    }
402    Ok(unsafe { &*descriptor.contract.cast::<T>() })
403}
404
405fn process_pins() -> &'static Mutex<Vec<Arc<Library>>> {
406    static PINS: OnceLock<Mutex<Vec<Arc<Library>>>> = OnceLock::new();
407    PINS.get_or_init(|| Mutex::new(Vec::new()))
408}
409
410fn pin_for_process(library: Arc<Library>) {
411    process_pins()
412        .lock()
413        .unwrap_or_else(|poisoned| poisoned.into_inner())
414        .push(library);
415}
416
417pub(crate) fn validate_manifest(
418    manifest: &ComponentManifest,
419    requirements: &ComponentRequirements,
420) -> Result<(), ComponentError> {
421    if manifest.schema_version != COMPONENT_MANIFEST_SCHEMA || manifest.abi_version != COMPONENT_ABI_VERSION {
422        return Err(ComponentError::UnsupportedManifest);
423    }
424    if manifest.identity.component != requirements.component_id {
425        return Err(ComponentError::IdentityMismatch {
426            expected: requirements.component_id.clone(),
427            actual: manifest.identity.component.clone(),
428        });
429    }
430    let provided = manifest
431        .provides
432        .iter()
433        .find(|provided| provided.contract == requirements.contract_name)
434        .ok_or_else(|| ComponentError::ContractNotProvided {
435            component_id: requirements.component_id.clone(),
436            contract: requirements.contract_name.clone(),
437        })?;
438    if decode_hash(&provided.contract_hash)? != requirements.contract_hash {
439        return Err(ComponentError::ContractHashMismatch);
440    }
441    if let Some(expected) = requirements.feature_set_hash
442        && decode_hash(&manifest.identity.feature_hash)? != expected
443    {
444        return Err(ComponentError::FeatureSetHashMismatch);
445    }
446    Ok(())
447}
448
449// `struct_size` must be a descriptor's first field: only that guarantees a raw read of it
450// never touches memory beyond what the component actually allocated, even when the
451// allocation is shorter than `size_of::<AlefComponentV1>()`. If this ever fails, the raw
452// read in `reject_undersized_descriptor` is no longer sound and must be revisited.
453const _: () = assert!(core::mem::offset_of!(AlefComponentV1, struct_size) == 0);
454
455/// Read a just-returned descriptor's `struct_size` and reject it while it is still smaller
456/// than the current ABI, before a `&AlefComponentV1` reference is formed over it.
457///
458/// # Safety
459///
460/// `descriptor` must be non-null and point to memory valid for reads of at least
461/// `size_of::<usize>()` bytes at `AlefComponentV1`'s alignment; no wider reference to it may
462/// have been formed yet. Both are upheld by [`LoadedComponent::load`]'s caller contract: a
463/// component's entry point must return a pointer to at least a valid `struct_size` field.
464unsafe fn reject_undersized_descriptor(descriptor: NonNull<AlefComponentV1>) -> Result<(), ComponentError> {
465    // SAFETY: upheld by this function's caller contract; `struct_size` sits at offset 0
466    // (asserted above), so this read never reaches past the caller-guaranteed
467    // `size_of::<usize>()` bytes regardless of how large the real descriptor is.
468    let struct_size = unsafe { descriptor.as_ptr().cast::<usize>().read_unaligned() };
469    if struct_size < core::mem::size_of::<AlefComponentV1>() {
470        return Err(ComponentError::InvalidDescriptor("descriptor is smaller than ABI v1"));
471    }
472    Ok(())
473}
474
475unsafe fn validate_descriptor(
476    descriptor: &AlefComponentV1,
477    requirements: &ComponentRequirements,
478) -> Result<(String, String), ComponentError> {
479    if descriptor.struct_size < core::mem::size_of::<AlefComponentV1>() {
480        return Err(ComponentError::InvalidDescriptor("descriptor is smaller than ABI v1"));
481    }
482    if descriptor.abi_major != ABI_MAJOR_V1 || descriptor.abi_minor > ABI_MINOR_V1 {
483        return Err(ComponentError::IncompatibleAbi {
484            expected_major: ABI_MAJOR_V1,
485            expected_minor: ABI_MINOR_V1,
486            actual_major: descriptor.abi_major,
487            actual_minor: descriptor.abi_minor,
488        });
489    }
490    let component_id = unsafe { copy_abi_str(descriptor.component_id)? };
491    let component_version = unsafe { copy_abi_str(descriptor.component_version)? };
492    if component_id != requirements.component_id {
493        return Err(ComponentError::IdentityMismatch {
494            expected: requirements.component_id.clone(),
495            actual: component_id,
496        });
497    }
498    if descriptor.contract_hash != requirements.contract_hash {
499        return Err(ComponentError::ContractHashMismatch);
500    }
501    if requirements
502        .feature_set_hash
503        .is_some_and(|expected| descriptor.feature_set_hash != expected)
504    {
505        return Err(ComponentError::FeatureSetHashMismatch);
506    }
507    if descriptor.contract_size > 0 && descriptor.contract.is_null() {
508        return Err(ComponentError::InvalidDescriptor(
509            "non-empty contract has a null pointer",
510        ));
511    }
512    Ok((component_id, component_version))
513}
514
515unsafe fn copy_abi_str(value: alef_component_abi::AlefStr) -> Result<String, ComponentError> {
516    if value.len > MAX_DESCRIPTOR_STRING {
517        return Err(ComponentError::StringTooLong);
518    }
519    if value.len == 0 {
520        return Ok(String::new());
521    }
522    if value.ptr.is_null() {
523        return Err(ComponentError::InvalidDescriptor("non-empty string has a null pointer"));
524    }
525    let bytes = unsafe { core::slice::from_raw_parts(value.ptr.cast::<u8>(), value.len) };
526    let text = core::str::from_utf8(bytes).map_err(|_| ComponentError::InvalidUtf8)?;
527    Ok(text.to_owned())
528}
529
530pub(crate) fn decode_hash(value: &str) -> Result<[u8; 32], ComponentError> {
531    let bytes = hex::decode(value).map_err(|_| ComponentError::InvalidDigest(value.to_owned()))?;
532    bytes
533        .try_into()
534        .map_err(|_| ComponentError::InvalidDigest(value.to_owned()))
535}
536
537#[cfg(test)]
538mod tests {
539    use super::*;
540    use alef_component_abi::{AlefComponentV1, AlefStr};
541    use std::ffi::c_char;
542
543    static ID: &[u8] = b"demo";
544    static VERSION: &[u8] = b"1.2.3";
545
546    #[repr(C)]
547    struct DemoContract {
548        answer: u32,
549    }
550
551    unsafe impl AlefContract for DemoContract {
552        const CONTRACT_HASH: [u8; 32] = [7; 32];
553    }
554
555    static CONTRACT: DemoContract = DemoContract { answer: 42 };
556
557    fn descriptor(contract_hash: [u8; 32]) -> AlefComponentV1 {
558        AlefComponentV1 {
559            struct_size: core::mem::size_of::<AlefComponentV1>(),
560            abi_major: ABI_MAJOR_V1,
561            abi_minor: ABI_MINOR_V1,
562            component_id: AlefStr {
563                ptr: ID.as_ptr().cast::<c_char>(),
564                len: ID.len(),
565            },
566            component_version: AlefStr {
567                ptr: VERSION.as_ptr().cast::<c_char>(),
568                len: VERSION.len(),
569            },
570            contract_hash,
571            feature_set_hash: [8; 32],
572            contract: core::ptr::dangling(),
573            contract_size: 1,
574            create: None,
575            destroy: None,
576        }
577    }
578
579    fn requirements() -> ComponentRequirements {
580        ComponentRequirements {
581            component_id: "demo".into(),
582            contract_name: "engine".into(),
583            contract_hash: [7; 32],
584            feature_set_hash: Some([8; 32]),
585        }
586    }
587
588    #[test]
589    fn accepts_matching_descriptor() {
590        let descriptor = descriptor([7; 32]);
591        let validated = unsafe { validate_descriptor(&descriptor, &requirements()) }.unwrap();
592        assert_eq!(validated, ("demo".into(), "1.2.3".into()));
593    }
594
595    #[test]
596    fn rejects_wrong_contract_hash() {
597        let descriptor = descriptor([9; 32]);
598        assert!(matches!(
599            unsafe { validate_descriptor(&descriptor, &requirements()) },
600            Err(ComponentError::ContractHashMismatch)
601        ));
602    }
603
604    #[test]
605    fn rejects_short_descriptor_before_optional_fields_are_read() {
606        let mut descriptor = descriptor([7; 32]);
607        descriptor.struct_size = 8;
608        assert!(matches!(
609            unsafe { validate_descriptor(&descriptor, &requirements()) },
610            Err(ComponentError::InvalidDescriptor(_))
611        ));
612    }
613
614    /// Regression for forming a `&AlefComponentV1` over memory that only actually holds a
615    /// `struct_size` field. The backing allocation below is deliberately sized for nothing
616    /// more than that one `usize`, so `reject_undersized_descriptor`'s raw pointer read must
617    /// be the only access that happens -- ever forming a full `&AlefComponentV1` reference
618    /// over it would read past the allocation.
619    #[test]
620    fn rejects_a_descriptor_backed_by_memory_too_small_to_hold_the_full_struct() {
621        let layout = std::alloc::Layout::from_size_align(
622            core::mem::size_of::<usize>(),
623            core::mem::align_of::<AlefComponentV1>(),
624        )
625        .unwrap();
626        // SAFETY: `layout` has non-zero size.
627        let raw = unsafe { std::alloc::alloc(layout) };
628        assert!(!raw.is_null(), "test allocation failed");
629        // SAFETY: `raw` is valid for `size_of::<usize>()` bytes per `layout` and is
630        // sufficiently aligned for a `usize` write.
631        unsafe { raw.cast::<usize>().write_unaligned(8) };
632        let descriptor = NonNull::new(raw).unwrap().cast::<AlefComponentV1>();
633
634        // SAFETY: `descriptor` points to `size_of::<usize>()` valid bytes, matching this
635        // function's caller contract; no wider reference is formed here.
636        let result = unsafe { reject_undersized_descriptor(descriptor) };
637
638        // SAFETY: `raw`/`layout` match the earlier allocation exactly.
639        unsafe { std::alloc::dealloc(raw, layout) };
640        assert!(matches!(result, Err(ComponentError::InvalidDescriptor(_))));
641    }
642
643    #[test]
644    fn manifest_validation_checks_feature_identity() {
645        let manifest = ComponentManifest {
646            schema_version: COMPONENT_MANIFEST_SCHEMA,
647            abi_version: 1,
648            identity: crate::ComponentIdentity {
649                crate_name: "demo-core".into(),
650                component: "demo".into(),
651                version: "1.2.3".into(),
652                target: "test-target".into(),
653                feature_hash: hex::encode([9; 32]),
654                contract_hash: hex::encode([7; 32]),
655            },
656            provides: vec![crate::ComponentProvidedContract {
657                contract: "engine".into(),
658                interface_version: 1,
659                contract_hash: hex::encode([7; 32]),
660                implementation: "demo::Engine".into(),
661            }],
662            features: Vec::new(),
663            default_features: false,
664            library: crate::ComponentLibrary {
665                file: "libdemo.so".into(),
666                sha256: hex::encode([0; 32]),
667                size: 0,
668            },
669        };
670        assert!(matches!(
671            validate_manifest(&manifest, &requirements()),
672            Err(ComponentError::FeatureSetHashMismatch)
673        ));
674    }
675
676    #[test]
677    fn typed_contract_table_checks_hash_size_and_alignment() {
678        let mut descriptor = descriptor(DemoContract::CONTRACT_HASH);
679        descriptor.contract = (&raw const CONTRACT).cast();
680        descriptor.contract_size = core::mem::size_of::<DemoContract>();
681        assert_eq!(
682            contract_table_from_descriptor::<DemoContract>(&descriptor)
683                .unwrap()
684                .answer,
685            42
686        );
687
688        descriptor.contract_hash = [9; 32];
689        assert!(matches!(
690            contract_table_from_descriptor::<DemoContract>(&descriptor),
691            Err(ComponentError::InvalidContractTable)
692        ));
693    }
694}