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    /// Invoke a named bytes-only method on this contract's stdio component.
217    ///
218    /// Native typed function tables require their generated bindings and do not implement
219    /// this operation. Stdio components likewise cannot expose typed C function tables.
220    pub fn invoke_bytes(&self, method: &str, payload: &[u8]) -> Result<Vec<u8>, ComponentError> {
221        let (process, contract) = self.sidecar.as_ref().ok_or(ComponentError::UnsupportedTransport(
222            "bytes invocation requires a stdio component",
223        ))?;
224        process.invoke(contract, method, payload)
225    }
226
227    #[must_use]
228    pub fn component_id(&self) -> &str {
229        &self.component_id
230    }
231
232    #[must_use]
233    pub fn component_version(&self) -> &str {
234        &self.component_version
235    }
236
237    #[must_use]
238    pub fn descriptor(&self) -> &AlefComponentV1 {
239        unsafe { self.descriptor.as_ref() }
240    }
241
242    #[must_use]
243    pub fn contract(&self) -> *const c_void {
244        self.descriptor().contract
245    }
246
247    #[must_use]
248    pub fn contract_size(&self) -> usize {
249        self.descriptor().contract_size
250    }
251
252    pub fn contract_table<T: AlefContract>(&self) -> Result<&T, ComponentError> {
253        if self.sidecar.is_some() {
254            return Err(ComponentError::UnsupportedTransport(
255                "stdio components support bytes invocation, not typed C function tables",
256            ));
257        }
258        contract_table_from_descriptor(self.descriptor())
259    }
260
261    /// Create an instance and bind it to a generated contract-table type.
262    pub fn instantiate<T: AlefContract>(self: &Arc<Self>) -> Result<ComponentInstance<T>, ComponentError> {
263        self.contract_table::<T>()?;
264        let create = self.descriptor().create.ok_or(ComponentError::MissingInstanceFactory)?;
265        self.descriptor()
266            .destroy
267            .ok_or(ComponentError::MissingInstanceDestructor)?;
268        let mut raw = core::ptr::null_mut();
269        let mut error = AlefOwnedBuffer::EMPTY;
270        let status = unsafe { create(self.host_api(), &mut raw, &mut error) };
271        if !status.is_ok() {
272            return Err(ComponentError::InstanceCreation {
273                status: status.0,
274                message: unsafe { take_owned_buffer(error) },
275            });
276        }
277        let handle = NonNull::new(raw).ok_or(ComponentError::NullInstance)?;
278        Ok(ComponentInstance {
279            component: Arc::clone(self),
280            handle,
281            _contract: PhantomData,
282        })
283    }
284
285    #[must_use]
286    pub fn host_api(&self) -> &AlefHostApiV1 {
287        &self.host
288    }
289
290    #[must_use]
291    pub fn strong_library_references(&self) -> usize {
292        self.library.as_ref().map_or(0, Arc::strong_count)
293    }
294}
295
296impl<T: AlefContract> ComponentInstance<T> {
297    #[must_use]
298    pub fn table(&self) -> &T {
299        // The table was validated before this instance was constructed.
300        self.component
301            .contract_table::<T>()
302            .expect("validated component contract table changed")
303    }
304
305    #[must_use]
306    pub fn handle(&self) -> *mut c_void {
307        self.handle.as_ptr()
308    }
309
310    #[must_use]
311    pub fn component(&self) -> &Arc<LoadedComponent> {
312        &self.component
313    }
314}
315
316impl<T: AlefContract> Drop for ComponentInstance<T> {
317    fn drop(&mut self) {
318        if let Some(destroy) = self.component.descriptor().destroy {
319            unsafe { destroy(self.handle.as_ptr()) };
320        }
321    }
322}
323
324/// Copy an owned buffer's bytes into a `Vec<u8>` and release the original
325/// allocation through its own `free` callback.
326///
327/// Generated contract proxies use this to convert a component's
328/// `AlefOwnedBuffer` results into owned Rust values without re-implementing
329/// buffer ownership handling in every generated snippet.
330///
331/// # Safety
332///
333/// `buffer` must be a valid `AlefOwnedBuffer`: `ptr` must be non-null and
334/// valid for `len` bytes whenever `len > 0`, and `free` (if present) must be
335/// safe to call with this buffer's own `context`, `ptr`, `len`, and
336/// `capacity`.
337#[must_use]
338pub unsafe fn take_owned_bytes(buffer: AlefOwnedBuffer) -> Vec<u8> {
339    let bytes = if buffer.ptr.is_null() || buffer.len == 0 {
340        Vec::new()
341    } else {
342        // SAFETY: upheld by this function's caller contract.
343        unsafe { core::slice::from_raw_parts(buffer.ptr, buffer.len) }.to_vec()
344    };
345    if let Some(free) = buffer.free {
346        // SAFETY: upheld by this function's caller contract.
347        unsafe { free(buffer.context, buffer.ptr, buffer.len, buffer.capacity) };
348    }
349    bytes
350}
351
352/// Like [`take_owned_bytes`], but lossily decodes the bytes as UTF-8.
353///
354/// Generated proxies use this to turn a component's error buffer into a
355/// `String` for constructing the contract's error type; a component that
356/// returns non-UTF-8 error text gets a replacement-character message instead
357/// of a panic or a dropped allocation.
358///
359/// # Safety
360///
361/// Same obligations as [`take_owned_bytes`].
362#[must_use]
363pub unsafe fn take_owned_text(buffer: AlefOwnedBuffer) -> String {
364    // SAFETY: upheld by this function's caller contract.
365    String::from_utf8_lossy(&unsafe { take_owned_bytes(buffer) }).into_owned()
366}
367
368unsafe fn take_owned_buffer(buffer: AlefOwnedBuffer) -> String {
369    let message = if buffer.ptr.is_null() {
370        if buffer.len == 0 {
371            String::new()
372        } else {
373            "component returned an invalid error buffer".to_string()
374        }
375    } else {
376        String::from_utf8_lossy(unsafe { core::slice::from_raw_parts(buffer.ptr, buffer.len) }).into_owned()
377    };
378    if let Some(free) = buffer.free {
379        unsafe { free(buffer.context, buffer.ptr, buffer.len, buffer.capacity) };
380    }
381    message
382}
383
384fn contract_table_from_descriptor<T: AlefContract>(descriptor: &AlefComponentV1) -> Result<&T, ComponentError> {
385    if descriptor.contract_hash != T::CONTRACT_HASH
386        || descriptor.contract_size < core::mem::size_of::<T>()
387        || descriptor.contract.is_null()
388        || !(descriptor.contract as usize).is_multiple_of(core::mem::align_of::<T>())
389    {
390        return Err(ComponentError::InvalidContractTable);
391    }
392    Ok(unsafe { &*descriptor.contract.cast::<T>() })
393}
394
395fn process_pins() -> &'static Mutex<Vec<Arc<Library>>> {
396    static PINS: OnceLock<Mutex<Vec<Arc<Library>>>> = OnceLock::new();
397    PINS.get_or_init(|| Mutex::new(Vec::new()))
398}
399
400fn pin_for_process(library: Arc<Library>) {
401    process_pins()
402        .lock()
403        .unwrap_or_else(|poisoned| poisoned.into_inner())
404        .push(library);
405}
406
407pub(crate) fn validate_manifest(
408    manifest: &ComponentManifest,
409    requirements: &ComponentRequirements,
410) -> Result<(), ComponentError> {
411    if manifest.schema_version != COMPONENT_MANIFEST_SCHEMA || manifest.abi_version != COMPONENT_ABI_VERSION {
412        return Err(ComponentError::UnsupportedManifest);
413    }
414    if manifest.identity.component != requirements.component_id {
415        return Err(ComponentError::IdentityMismatch {
416            expected: requirements.component_id.clone(),
417            actual: manifest.identity.component.clone(),
418        });
419    }
420    let provided = manifest
421        .provides
422        .iter()
423        .find(|provided| provided.contract == requirements.contract_name)
424        .ok_or_else(|| ComponentError::ContractNotProvided {
425            component_id: requirements.component_id.clone(),
426            contract: requirements.contract_name.clone(),
427        })?;
428    if decode_hash(&provided.contract_hash)? != requirements.contract_hash {
429        return Err(ComponentError::ContractHashMismatch);
430    }
431    if let Some(expected) = requirements.feature_set_hash
432        && decode_hash(&manifest.identity.feature_hash)? != expected
433    {
434        return Err(ComponentError::FeatureSetHashMismatch);
435    }
436    Ok(())
437}
438
439// `struct_size` must be a descriptor's first field: only that guarantees a raw read of it
440// never touches memory beyond what the component actually allocated, even when the
441// allocation is shorter than `size_of::<AlefComponentV1>()`. If this ever fails, the raw
442// read in `reject_undersized_descriptor` is no longer sound and must be revisited.
443const _: () = assert!(core::mem::offset_of!(AlefComponentV1, struct_size) == 0);
444
445/// Read a just-returned descriptor's `struct_size` and reject it while it is still smaller
446/// than the current ABI, before a `&AlefComponentV1` reference is formed over it.
447///
448/// # Safety
449///
450/// `descriptor` must be non-null and point to memory valid for reads of at least
451/// `size_of::<usize>()` bytes at `AlefComponentV1`'s alignment; no wider reference to it may
452/// have been formed yet. Both are upheld by [`LoadedComponent::load`]'s caller contract: a
453/// component's entry point must return a pointer to at least a valid `struct_size` field.
454unsafe fn reject_undersized_descriptor(descriptor: NonNull<AlefComponentV1>) -> Result<(), ComponentError> {
455    // SAFETY: upheld by this function's caller contract; `struct_size` sits at offset 0
456    // (asserted above), so this read never reaches past the caller-guaranteed
457    // `size_of::<usize>()` bytes regardless of how large the real descriptor is.
458    let struct_size = unsafe { descriptor.as_ptr().cast::<usize>().read_unaligned() };
459    if struct_size < core::mem::size_of::<AlefComponentV1>() {
460        return Err(ComponentError::InvalidDescriptor("descriptor is smaller than ABI v1"));
461    }
462    Ok(())
463}
464
465unsafe fn validate_descriptor(
466    descriptor: &AlefComponentV1,
467    requirements: &ComponentRequirements,
468) -> Result<(String, String), ComponentError> {
469    if descriptor.struct_size < core::mem::size_of::<AlefComponentV1>() {
470        return Err(ComponentError::InvalidDescriptor("descriptor is smaller than ABI v1"));
471    }
472    if descriptor.abi_major != ABI_MAJOR_V1 || descriptor.abi_minor > ABI_MINOR_V1 {
473        return Err(ComponentError::IncompatibleAbi {
474            expected_major: ABI_MAJOR_V1,
475            expected_minor: ABI_MINOR_V1,
476            actual_major: descriptor.abi_major,
477            actual_minor: descriptor.abi_minor,
478        });
479    }
480    let component_id = unsafe { copy_abi_str(descriptor.component_id)? };
481    let component_version = unsafe { copy_abi_str(descriptor.component_version)? };
482    if component_id != requirements.component_id {
483        return Err(ComponentError::IdentityMismatch {
484            expected: requirements.component_id.clone(),
485            actual: component_id,
486        });
487    }
488    if descriptor.contract_hash != requirements.contract_hash {
489        return Err(ComponentError::ContractHashMismatch);
490    }
491    if requirements
492        .feature_set_hash
493        .is_some_and(|expected| descriptor.feature_set_hash != expected)
494    {
495        return Err(ComponentError::FeatureSetHashMismatch);
496    }
497    if descriptor.contract_size > 0 && descriptor.contract.is_null() {
498        return Err(ComponentError::InvalidDescriptor(
499            "non-empty contract has a null pointer",
500        ));
501    }
502    Ok((component_id, component_version))
503}
504
505unsafe fn copy_abi_str(value: alef_component_abi::AlefStr) -> Result<String, ComponentError> {
506    if value.len > MAX_DESCRIPTOR_STRING {
507        return Err(ComponentError::StringTooLong);
508    }
509    if value.len == 0 {
510        return Ok(String::new());
511    }
512    if value.ptr.is_null() {
513        return Err(ComponentError::InvalidDescriptor("non-empty string has a null pointer"));
514    }
515    let bytes = unsafe { core::slice::from_raw_parts(value.ptr.cast::<u8>(), value.len) };
516    let text = core::str::from_utf8(bytes).map_err(|_| ComponentError::InvalidUtf8)?;
517    Ok(text.to_owned())
518}
519
520pub(crate) fn decode_hash(value: &str) -> Result<[u8; 32], ComponentError> {
521    let bytes = hex::decode(value).map_err(|_| ComponentError::InvalidDigest(value.to_owned()))?;
522    bytes
523        .try_into()
524        .map_err(|_| ComponentError::InvalidDigest(value.to_owned()))
525}
526
527#[cfg(test)]
528mod tests {
529    use super::*;
530    use alef_component_abi::{AlefComponentV1, AlefStr};
531    use std::ffi::c_char;
532
533    static ID: &[u8] = b"demo";
534    static VERSION: &[u8] = b"1.2.3";
535
536    #[repr(C)]
537    struct DemoContract {
538        answer: u32,
539    }
540
541    unsafe impl AlefContract for DemoContract {
542        const CONTRACT_HASH: [u8; 32] = [7; 32];
543    }
544
545    static CONTRACT: DemoContract = DemoContract { answer: 42 };
546
547    fn descriptor(contract_hash: [u8; 32]) -> AlefComponentV1 {
548        AlefComponentV1 {
549            struct_size: core::mem::size_of::<AlefComponentV1>(),
550            abi_major: ABI_MAJOR_V1,
551            abi_minor: ABI_MINOR_V1,
552            component_id: AlefStr {
553                ptr: ID.as_ptr().cast::<c_char>(),
554                len: ID.len(),
555            },
556            component_version: AlefStr {
557                ptr: VERSION.as_ptr().cast::<c_char>(),
558                len: VERSION.len(),
559            },
560            contract_hash,
561            feature_set_hash: [8; 32],
562            contract: core::ptr::dangling(),
563            contract_size: 1,
564            create: None,
565            destroy: None,
566        }
567    }
568
569    fn requirements() -> ComponentRequirements {
570        ComponentRequirements {
571            component_id: "demo".into(),
572            contract_name: "engine".into(),
573            contract_hash: [7; 32],
574            feature_set_hash: Some([8; 32]),
575        }
576    }
577
578    #[test]
579    fn accepts_matching_descriptor() {
580        let descriptor = descriptor([7; 32]);
581        let validated = unsafe { validate_descriptor(&descriptor, &requirements()) }.unwrap();
582        assert_eq!(validated, ("demo".into(), "1.2.3".into()));
583    }
584
585    #[test]
586    fn rejects_wrong_contract_hash() {
587        let descriptor = descriptor([9; 32]);
588        assert!(matches!(
589            unsafe { validate_descriptor(&descriptor, &requirements()) },
590            Err(ComponentError::ContractHashMismatch)
591        ));
592    }
593
594    #[test]
595    fn rejects_short_descriptor_before_optional_fields_are_read() {
596        let mut descriptor = descriptor([7; 32]);
597        descriptor.struct_size = 8;
598        assert!(matches!(
599            unsafe { validate_descriptor(&descriptor, &requirements()) },
600            Err(ComponentError::InvalidDescriptor(_))
601        ));
602    }
603
604    /// Regression for forming a `&AlefComponentV1` over memory that only actually holds a
605    /// `struct_size` field. The backing allocation below is deliberately sized for nothing
606    /// more than that one `usize`, so `reject_undersized_descriptor`'s raw pointer read must
607    /// be the only access that happens -- ever forming a full `&AlefComponentV1` reference
608    /// over it would read past the allocation.
609    #[test]
610    fn rejects_a_descriptor_backed_by_memory_too_small_to_hold_the_full_struct() {
611        let layout = std::alloc::Layout::from_size_align(
612            core::mem::size_of::<usize>(),
613            core::mem::align_of::<AlefComponentV1>(),
614        )
615        .unwrap();
616        // SAFETY: `layout` has non-zero size.
617        let raw = unsafe { std::alloc::alloc(layout) };
618        assert!(!raw.is_null(), "test allocation failed");
619        // SAFETY: `raw` is valid for `size_of::<usize>()` bytes per `layout` and is
620        // sufficiently aligned for a `usize` write.
621        unsafe { raw.cast::<usize>().write_unaligned(8) };
622        let descriptor = NonNull::new(raw).unwrap().cast::<AlefComponentV1>();
623
624        // SAFETY: `descriptor` points to `size_of::<usize>()` valid bytes, matching this
625        // function's caller contract; no wider reference is formed here.
626        let result = unsafe { reject_undersized_descriptor(descriptor) };
627
628        // SAFETY: `raw`/`layout` match the earlier allocation exactly.
629        unsafe { std::alloc::dealloc(raw, layout) };
630        assert!(matches!(result, Err(ComponentError::InvalidDescriptor(_))));
631    }
632
633    #[test]
634    fn manifest_validation_checks_feature_identity() {
635        let manifest = ComponentManifest {
636            schema_version: COMPONENT_MANIFEST_SCHEMA,
637            abi_version: 1,
638            identity: crate::ComponentIdentity {
639                crate_name: "demo-core".into(),
640                component: "demo".into(),
641                version: "1.2.3".into(),
642                target: "test-target".into(),
643                feature_hash: hex::encode([9; 32]),
644                contract_hash: hex::encode([7; 32]),
645            },
646            provides: vec![crate::ComponentProvidedContract {
647                contract: "engine".into(),
648                interface_version: 1,
649                contract_hash: hex::encode([7; 32]),
650                implementation: "demo::Engine".into(),
651            }],
652            features: Vec::new(),
653            default_features: false,
654            library: crate::ComponentLibrary {
655                file: "libdemo.so".into(),
656                sha256: hex::encode([0; 32]),
657                size: 0,
658            },
659        };
660        assert!(matches!(
661            validate_manifest(&manifest, &requirements()),
662            Err(ComponentError::FeatureSetHashMismatch)
663        ));
664    }
665
666    #[test]
667    fn typed_contract_table_checks_hash_size_and_alignment() {
668        let mut descriptor = descriptor(DemoContract::CONTRACT_HASH);
669        descriptor.contract = (&raw const CONTRACT).cast();
670        descriptor.contract_size = core::mem::size_of::<DemoContract>();
671        assert_eq!(
672            contract_table_from_descriptor::<DemoContract>(&descriptor)
673                .unwrap()
674                .answer,
675            42
676        );
677
678        descriptor.contract_hash = [9; 32];
679        assert!(matches!(
680            contract_table_from_descriptor::<DemoContract>(&descriptor),
681            Err(ComponentError::InvalidContractTable)
682        ));
683    }
684}