Skip to main content

alef_component_runtime/
loader.rs

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