Skip to main content

rutis_dylib/
loader.rs

1//! guarantee: bridge/marked-services
2//! Optional in-process loader for trusted, first-party Rust dylib plugins.
3//! A verified, immutable bundle launcher must run the host before this API is
4//! used: a mismatched SDK can execute during Rust startup, before `Loader::new`.
5//!
6//! Everything here is platform-independent; opening libraries, finding
7//! symbols and locating the loaded SDK live in `crate::platform`.
8
9#[cfg(panic = "abort")]
10compile_error!("rutis-dylib requires panic = unwind");
11
12use crate::platform::{self, Handle};
13use rutis::host::{CtxHost, ErrorKind};
14use rutis::host::{DynPlugin, FiberView, PluginFactory, TypeKey};
15use rutis::internal::service::Generation;
16use rutis::{Ctx, Error};
17use rutis_sdk::{ConfigValue, PluginMeta, BOOT_MAGIC, BOOT_SIZE, SDK_ID};
18use serde::Deserialize;
19use sha2::{Digest, Sha256};
20use std::collections::HashMap;
21#[cfg(any(test, feature = "testing"))]
22use std::ffi::c_void;
23use std::fs;
24use std::io::{Read, Write};
25use std::path::{Path, PathBuf};
26use std::sync::{Arc, Mutex};
27use std::time::SystemTime;
28
29#[derive(Debug, thiserror::Error)]
30#[error("plugin {plugin} {version}: {step}: {reason}")]
31pub struct LoadError {
32    pub plugin: String,
33    pub version: String,
34    pub step: &'static str,
35    pub reason: String,
36}
37
38fn error(plugin: &str, version: &str, step: &'static str, reason: impl Into<String>) -> LoadError {
39    LoadError {
40        plugin: plugin.into(),
41        version: version.into(),
42        step,
43        reason: reason.into(),
44    }
45}
46
47#[derive(Deserialize)]
48struct Manifest {
49    plugin: PluginManifest,
50    sdk: SdkManifest,
51    #[serde(default)]
52    interfaces: HashMap<String, String>,
53    build: BuildManifest,
54}
55
56#[derive(Deserialize)]
57struct PluginManifest {
58    id: String,
59    version: String,
60    library: String,
61    library_sha256: String,
62    /// Native libraries the plugin links, as its dynamic section records them.
63    native_deps: Vec<String>,
64}
65#[derive(Deserialize)]
66struct SdkManifest {
67    version: String,
68    id: String,
69    artifact_sha256: String,
70}
71#[derive(Deserialize)]
72struct BuildManifest {
73    target: String,
74    rustc: String,
75    lock_sha256: String,
76}
77
78#[derive(Debug, Clone)]
79pub struct ModuleDiagnostic {
80    pub id: String,
81    pub version: String,
82    pub library_sha256: String,
83    pub mapped_bytes: u64,
84    pub loaded_at: SystemTime,
85    /// Includes the loader's own reference, plus caller and fiber references.
86    pub strong_references: usize,
87    pub usable: bool,
88}
89
90struct Retained {
91    id: String,
92    version: String,
93    hash: String,
94    bytes: u64,
95    loaded_at: SystemTime,
96    module: Option<Arc<Module>>,
97    generation: Generation,
98    _handle: Handle,
99}
100
101/// The generation each library mapped in this process was loaded as
102/// (`rutis::service::loading`), by its handle: opening a library again
103/// returns the mapping already there, whose initializers do not run again,
104/// so its blocks stay those of the first opening. One entry per library
105/// mapped, which is never unmapped: bounded, like the libraries, by the
106/// loaders' version limits.
107static GENERATIONS: Mutex<Vec<(usize, Generation)>> = Mutex::new(Vec::new());
108
109/// Open `path`, its initializers registering its `#[rutis::service]`
110/// blocks as a generation of their own (two builds of one plugin keep their
111/// types' TypeIds; each serves its values with its own blocks). The lock is
112/// held across the opening and the recording, so two loaders opening the
113/// same file at once agree on the generation of its one mapping.
114///
115/// # Safety
116///
117/// As `platform::open_library`: the library's initializers run in this
118/// process.
119unsafe fn open_generation(path: &Path) -> Result<(Handle, Generation), String> {
120    open_generation_with(|| unsafe { platform::open_library(path) })
121}
122
123/// [`open_generation`] with `open` mapping the library.
124fn open_generation_with(
125    open: impl FnOnce() -> Result<Handle, String>,
126) -> Result<(Handle, Generation), String> {
127    let mut known = GENERATIONS
128        .lock()
129        .unwrap_or_else(|poison| poison.into_inner());
130    let (opened, generation) = rutis::internal::service::loading(open);
131    let handle = opened?;
132    let key = handle.as_ptr() as usize;
133    if let Some((_, generation)) = known.iter().find(|(handle, _)| *handle == key) {
134        return Ok((handle, *generation));
135    }
136    known.push((key, generation));
137    Ok((handle, generation))
138}
139
140// Library handles are process-global, remain mapped forever, and may be used
141// on any thread. We never call dlclose or FreeLibrary, including when a
142// rejected load is dropped.
143unsafe impl Send for Retained {}
144
145/// What [`Loader::load`] does once its checks on the files pass: map the
146/// library and look up its exported symbols. The platform supplies these in
147/// every real build; a test replaces them to prove that a rejected plugin
148/// never reaches `dlopen`, and to answer for a library it does not open.
149#[cfg(any(test, feature = "testing"))]
150pub trait Backend: Send + Sync {
151    /// Maps `path`, as `dlopen`/`LoadLibraryExW` does.
152    ///
153    /// # Safety
154    ///
155    /// The library's initializers run in this process.
156    unsafe fn open(&self, path: &Path) -> Result<Handle, String>;
157    /// Finds the symbol `name` (which ends with a NUL byte) in `handle`, as
158    /// `dlsym`/`GetProcAddress` does.
159    ///
160    /// # Safety
161    ///
162    /// `handle` must be one this backend returned from [`Backend::open`].
163    unsafe fn symbol(&self, handle: Handle, name: &[u8]) -> Result<*mut c_void, String>;
164}
165
166/// Host-side loader. Construct it after the independent bundle launcher has
167/// verified the host, SDK and dynamic libstd files, and before creating root.
168pub struct Loader {
169    sdk_artifact_sha256: String,
170    /// File names plugins must use for the SDK and the host's libstd.
171    sdk_library: String,
172    std_library: String,
173    #[cfg(target_os = "macos")]
174    allowed_team_ids: Option<Vec<String>>,
175    cache: PathBuf,
176    interfaces: HashMap<String, semver::Version>,
177    max_versions: usize,
178    retained: Mutex<Vec<Retained>>,
179    #[cfg(any(test, feature = "testing"))]
180    backend: Option<Box<dyn Backend>>,
181}
182
183impl Loader {
184    pub fn new(
185        sdk_artifact_sha256: impl Into<String>,
186        cache: impl Into<PathBuf>,
187        interfaces: HashMap<String, semver::Version>,
188        max_versions: usize,
189    ) -> Result<Self, LoadError> {
190        let sdk_artifact_sha256 = sdk_artifact_sha256.into();
191        if !rutis_sdk::is_sha256(&sdk_artifact_sha256) {
192            return Err(error(
193                "<host>",
194                "",
195                "startup",
196                "invalid embedded SDK artifact SHA-256",
197            ));
198        }
199        let mut buf = [0_u8; 128];
200        let len = unsafe { rutis_sdk::rutis_sdk_boot_id(buf.as_mut_ptr(), buf.len()) };
201        if len != SDK_ID.len() || &buf[..len] != SDK_ID.as_bytes() {
202            return Err(error(
203                "<host>",
204                "",
205                "startup",
206                "loaded SDK identity differs from host",
207            ));
208        }
209        let actual = platform::loaded_sdk_path().map_err(|e| error("<host>", "", "startup", e))?;
210        let sdk_bytes = fs::read(&actual).map_err(|e| {
211            error(
212                "<host>",
213                "",
214                "startup",
215                format!("{}: {e}", actual.display()),
216            )
217        })?;
218        let actual_hash = sha_bytes(&sdk_bytes);
219        if actual_hash != sdk_artifact_sha256 {
220            return Err(error("<host>", "", "startup", format!("loaded SDK artifact mismatch at {}: expected {sdk_artifact_sha256}, got {actual_hash}", actual.display())));
221        }
222        let startup = |e: String| error("<host>", "", "startup", e);
223        let sdk_library =
224            rutis_dylib_meta::sdk_reference(rutis_sdk::SDK_TARGET).map_err(startup)?;
225        let std_library =
226            rutis_dylib_meta::std_reference(&sdk_bytes, rutis_sdk::SDK_TARGET).map_err(startup)?;
227        Ok(Self {
228            sdk_artifact_sha256,
229            sdk_library,
230            std_library,
231            #[cfg(target_os = "macos")]
232            allowed_team_ids: None,
233            cache: cache.into(),
234            interfaces,
235            max_versions,
236            retained: Mutex::new(Vec::new()),
237            #[cfg(any(test, feature = "testing"))]
238            backend: None,
239        })
240    }
241
242    /// A loader for tests: the host identity checks [`Loader::new`] makes are
243    /// skipped, `sdk_library` and `std_library` stand for the names of the
244    /// host's copies, and `backend` answers for a library that is never
245    /// really opened.
246    #[cfg(any(test, feature = "testing"))]
247    pub fn testing(
248        sdk_artifact_sha256: impl Into<String>,
249        sdk_library: impl Into<String>,
250        std_library: impl Into<String>,
251        cache: impl Into<PathBuf>,
252        interfaces: &[(&str, &str)],
253        max_versions: usize,
254        backend: Box<dyn Backend>,
255    ) -> Self {
256        Self {
257            sdk_artifact_sha256: sdk_artifact_sha256.into(),
258            sdk_library: sdk_library.into(),
259            std_library: std_library.into(),
260            #[cfg(target_os = "macos")]
261            allowed_team_ids: None,
262            cache: cache.into(),
263            interfaces: interfaces
264                .iter()
265                .map(|(name, version)| {
266                    (
267                        name.to_string(),
268                        semver::Version::parse(version).expect("test interface version"),
269                    )
270                })
271                .collect(),
272            max_versions,
273            retained: Mutex::new(Vec::new()),
274            backend: Some(backend),
275        }
276    }
277
278    /// Opens `path` as a generation of its own, through the test backend when
279    /// there is one.
280    fn open_library(&self, path: &Path) -> Result<(Handle, Generation), String> {
281        #[cfg(any(test, feature = "testing"))]
282        if let Some(backend) = &self.backend {
283            return open_generation_with(|| unsafe { backend.open(path) });
284        }
285        unsafe { open_generation(path) }
286    }
287
288    /// Finds the symbol `name` in `handle`, through the test backend when
289    /// there is one.
290    unsafe fn find_symbol(
291        &self,
292        handle: Handle,
293        name: &[u8],
294    ) -> Result<*mut std::ffi::c_void, String> {
295        #[cfg(any(test, feature = "testing"))]
296        if let Some(backend) = &self.backend {
297            return unsafe { backend.symbol(handle, name) };
298        }
299        unsafe { platform::find_symbol(handle, name) }
300    }
301
302    unsafe fn optional_symbol<T>(&self, handle: Handle, name: &[u8]) -> Option<T> {
303        unsafe { self.find_symbol(handle, name) }
304            .ok()
305            .map(|ptr| unsafe { std::mem::transmute_copy(&ptr) })
306    }
307
308    unsafe fn symbol<T>(&self, handle: Handle, name: &[u8]) -> Result<T, String> {
309        debug_assert_eq!(
310            std::mem::size_of::<T>(),
311            std::mem::size_of::<*mut std::ffi::c_void>()
312        );
313        unsafe { self.find_symbol(handle, name) }
314            .map(|ptr| unsafe { std::mem::transmute_copy(&ptr) })
315    }
316
317    /// Only load plugins with a valid signature from an Apple-issued
318    /// certificate of one of these Team IDs. Ad-hoc signed plugins are then
319    /// rejected. Without this call, the signer is not checked.
320    #[cfg(target_os = "macos")]
321    pub fn require_team_ids(mut self, team_ids: Vec<String>) -> Self {
322        self.allowed_team_ids = Some(team_ids);
323        self
324    }
325
326    /// Loads trusted code.
327    ///
328    /// # Safety
329    ///
330    /// The caller is responsible for accepting that library initializers run
331    /// inside the host as soon as `dlopen` is called.
332    pub unsafe fn load(&self, dir: impl AsRef<Path>) -> Result<Arc<Module>, LoadError> {
333        let manifest_path = dir.as_ref().join("plugin.toml");
334        let source = fs::read_to_string(&manifest_path)
335            .map_err(|e| error("<unknown>", "", "manifest", e.to_string()))?;
336        let manifest: Manifest = toml::from_str(&source)
337            .map_err(|e| error("<unknown>", "", "manifest", e.to_string()))?;
338        let id = &manifest.plugin.id;
339        let version = &manifest.plugin.version;
340        let fail = |step, reason| error(id, version, step, reason);
341        if id.is_empty() || version.is_empty() {
342            return Err(fail(
343                "manifest",
344                "plugin id and version must be nonempty".into(),
345            ));
346        }
347        if manifest.build.target != rutis_sdk::SDK_TARGET {
348            return Err(fail(
349                "manifest",
350                format!("target mismatch: {}", manifest.build.target),
351            ));
352        }
353        if manifest.build.rustc != rutis_sdk::SDK_RUSTC_VERSION {
354            return Err(fail(
355                "manifest",
356                format!("rustc mismatch: {}", manifest.build.rustc),
357            ));
358        }
359        if manifest.sdk.id != SDK_ID || manifest.sdk.artifact_sha256 != self.sdk_artifact_sha256 {
360            return Err(fail(
361                "manifest",
362                format!(
363                    "SDK mismatch: manifest id={} artifact={}, host id={} artifact={}",
364                    manifest.sdk.id, manifest.sdk.artifact_sha256, SDK_ID, self.sdk_artifact_sha256
365                ),
366            ));
367        }
368        if manifest.sdk.version != rutis_sdk::SDK_VERSION {
369            return Err(fail(
370                "manifest",
371                format!("SDK version mismatch: {}", manifest.sdk.version),
372            ));
373        }
374        if !rutis_sdk::is_sha256(&manifest.plugin.library_sha256)
375            || !rutis_sdk::is_sha256(&manifest.build.lock_sha256)
376        {
377            return Err(fail("manifest", "invalid SHA-256 field".into()));
378        }
379        for (name, requirement) in &manifest.interfaces {
380            let req = semver::VersionReq::parse(requirement)
381                .map_err(|e| fail("interfaces", e.to_string()))?;
382            let actual = self
383                .interfaces
384                .get(name)
385                .ok_or_else(|| fail("interfaces", format!("missing interface {name}")))?;
386            if !req.matches(actual) {
387                return Err(fail(
388                    "interfaces",
389                    format!("{name} {actual} does not meet {req}"),
390                ));
391            }
392        }
393        let library = Path::new(&manifest.plugin.library);
394        if library.components().count() != 1 || library.file_name().is_none() {
395            return Err(fail("manifest", "library must be a filename".into()));
396        }
397        let source_library = dir.as_ref().join(library);
398        // Checked before the bytes are read: the cache copy drops extended
399        // attributes, and copying it there is no consent to load it.
400        #[cfg(target_os = "macos")]
401        reject_quarantined(&source_library).map_err(|e| fail("quarantine", e))?;
402        let bytes = fs::read(&source_library).map_err(|e| fail("binary", e.to_string()))?;
403        let actual_hash = sha_bytes(&bytes);
404        if actual_hash != manifest.plugin.library_sha256 {
405            return Err(fail(
406                "binary",
407                format!("library SHA-256 mismatch: {actual_hash}"),
408            ));
409        }
410        let boot = rutis_dylib_meta::read_boot(&bytes, rutis_sdk::SDK_TARGET)
411            .map_err(|e| fail("boot metadata", e))?;
412        if boot.sdk_id != SDK_ID
413            || boot.sdk_artifact != self.sdk_artifact_sha256
414            || boot.sdk_id != manifest.sdk.id
415            || boot.sdk_artifact != manifest.sdk.artifact_sha256
416            || boot.id != *id
417            || boot.version != *version
418        {
419            return Err(fail(
420                "boot metadata",
421                "binary identity differs from manifest or host".into(),
422            ));
423        }
424        // dlopen would resolve these before any check of ours could run again.
425        let native = rutis_dylib_meta::check_plugin_dependencies(
426            &bytes,
427            rutis_sdk::SDK_TARGET,
428            &rutis_dylib_meta::SharedLibraries {
429                sdk: &self.sdk_library,
430                std: &self.std_library,
431            },
432        )
433        .map_err(|e| fail("dependencies", e))?;
434        let mut declared = manifest.plugin.native_deps.clone();
435        declared.sort();
436        declared.dedup();
437        if native != declared {
438            return Err(fail(
439                "dependencies",
440                format!("binary links native libraries {native:?}, manifest declares {declared:?}"),
441            ));
442        }
443        let mut retained = self.retained.lock().unwrap();
444        let existing_slot = retained
445            .iter()
446            .position(|entry| entry.id == *id && entry.hash == actual_hash);
447        let (handle, generation, slot) = if let Some(slot) = existing_slot {
448            if let Some(module) = &retained[slot].module {
449                return Ok(module.clone());
450            }
451            // A previous entry/metadata attempt failed after dlopen. Retry on
452            // the retained mapping without consuming another version slot.
453            (retained[slot]._handle, retained[slot].generation, slot)
454        } else {
455            if retained.iter().filter(|entry| entry.id == *id).count() >= self.max_versions {
456                return Err(fail(
457                    "retention",
458                    format!(
459                        "version limit {} reached; restart the host to reclaim code",
460                        self.max_versions
461                    ),
462                ));
463            }
464            let cached = self.cache.join(&actual_hash).join(library);
465            // Held from the hash check until the library is mapped. On
466            // Windows the share mode refuses writes, deletes and renames
467            // meanwhile; elsewhere the cache must be trusted (SDK design ยง5).
468            let _pinned =
469                ensure_cached(&cached, &bytes, &actual_hash).map_err(|e| fail("cache", e))?;
470            // A reused cache entry may have been placed by hand.
471            #[cfg(target_os = "macos")]
472            {
473                reject_quarantined(&cached).map_err(|e| fail("quarantine", e))?;
474                if let Some(team_ids) = &self.allowed_team_ids {
475                    crate::macos::check_team_id(&cached, team_ids)
476                        .map_err(|e| fail("code signature", e))?;
477                }
478            }
479            let (handle, generation) = self
480                .open_library(&cached)
481                .map_err(|e| fail(platform::OPEN_STEP, e))?;
482            // This is the plugin's newest build: names are looked up in it,
483            // not in the earlier ones, whose blocks keep serving the values
484            // they provided.
485            rutis::internal::service::supersede(
486                retained
487                    .iter()
488                    .filter(|entry| entry.id == *id && entry.generation != generation)
489                    .map(|entry| entry.generation),
490            );
491            // Every successfully opened library remains mapped, even if entry fails.
492            retained.push(Retained {
493                id: id.clone(),
494                version: version.clone(),
495                hash: actual_hash.clone(),
496                bytes: bytes.len() as u64,
497                loaded_at: SystemTime::now(),
498                module: None,
499                generation,
500                _handle: handle,
501            });
502            (handle, generation, retained.len() - 1)
503        };
504        let meta_fn: unsafe fn() -> PluginMeta =
505            unsafe { self.symbol(handle, b"rutis_plugin_meta\0") }
506                .map_err(|e| fail("metadata", e))?;
507        let meta = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| meta_fn()))
508            .map_err(|_| fail("metadata", "metadata function panicked".into()))?;
509        if meta.sdk_id != SDK_ID
510            || meta.sdk_artifact_sha256 != self.sdk_artifact_sha256
511            || meta.sdk_id != boot.sdk_id
512            || meta.sdk_artifact_sha256 != boot.sdk_artifact
513            || meta.id != id
514            || meta.version != version
515        {
516            return Err(fail(
517                "metadata",
518                "runtime identity differs from boot metadata or manifest".into(),
519            ));
520        }
521        let entry: unsafe fn() -> Result<Box<dyn PluginFactory<ConfigValue>>, Error> =
522            unsafe { self.symbol(handle, b"rutis_plugin_entry\0") }
523                .map_err(|e| fail("entry", e))?;
524        let factory = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| entry()))
525            .map_err(|_| fail("entry", "factory entry panicked".into()))?
526            .map_err(|e| fail("entry", e.to_string()))?;
527        let (name, injects) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
528            (factory.name().to_string(), factory.injects().to_vec())
529        }))
530        .map_err(|_| fail("entry", "factory metadata panicked".into()))?;
531        // Optional: plugins built before the symbol existed have no schema.
532        let schema = match unsafe {
533            self.optional_symbol::<unsafe fn() -> Option<String>>(
534                handle,
535                b"rutis_plugin_config_schema\0",
536            )
537        } {
538            None => None,
539            Some(schema_fn) => {
540                let text = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| schema_fn()))
541                    .map_err(|_| fail("schema", "schema function panicked".into()))?;
542                match text {
543                    None => None,
544                    Some(text) => Some(
545                        rutis_sdk::serde_json::from_str(&text)
546                            .map_err(|e| fail("schema", format!("invalid JSON: {e}")))?,
547                    ),
548                }
549            }
550        };
551        let module = Arc::new(Module {
552            id: id.clone(),
553            version: version.clone(),
554            library_sha256: actual_hash,
555            name,
556            injects,
557            schema,
558            factory,
559            generation,
560            _handle: handle,
561        });
562        retained[slot].module = Some(module.clone());
563        Ok(module)
564    }
565
566    pub fn diagnostics(&self) -> Vec<ModuleDiagnostic> {
567        self.retained
568            .lock()
569            .unwrap()
570            .iter()
571            .map(|entry| ModuleDiagnostic {
572                id: entry.id.clone(),
573                version: entry.version.clone(),
574                library_sha256: entry.hash.clone(),
575                mapped_bytes: entry.bytes,
576                loaded_at: entry.loaded_at,
577                strong_references: entry.module.as_ref().map(Arc::strong_count).unwrap_or(0),
578                usable: entry.module.is_some(),
579            })
580            .collect()
581    }
582
583    pub fn spawn(
584        &self,
585        ctx: &Ctx,
586        module: &Arc<Module>,
587        value: ConfigValue,
588    ) -> Result<FiberView, Error> {
589        let factory = DylibFactory {
590            id: module.id.clone(),
591            name: module.name.clone(),
592            injects: module.injects.clone(),
593        };
594        factory.validate_config(&DylibConfig::new(module.clone(), value.clone()))?;
595        Ok(ctx.plugin_with(factory, DylibConfig::new(module.clone(), value)))
596    }
597
598    pub async fn swap(
599        &self,
600        view: &FiberView,
601        module: &Arc<Module>,
602        value: ConfigValue,
603    ) -> Result<(), Arc<ErrorKind>> {
604        let current = view.current_config::<DylibConfig>().ok_or_else(|| {
605            Arc::new(ErrorKind::Validation {
606                issues: vec!["fiber is not a dylib plugin".into()],
607            })
608        })?;
609        let expected = DylibFactory {
610            id: current.module.id.clone(),
611            name: current.module.name.clone(),
612            injects: current.module.injects.clone(),
613        };
614        expected
615            .check_module(module)
616            .map_err(|error| Arc::new(error.into_kind()))?;
617        view.update(DylibConfig::new(module.clone(), value)).await
618    }
619}
620
621pub struct Module {
622    id: String,
623    version: String,
624    library_sha256: String,
625    name: String,
626    injects: Vec<TypeKey>,
627    schema: Option<rutis_sdk::serde_json::Value>,
628    factory: Box<dyn PluginFactory<ConfigValue>>,
629    generation: Generation,
630    _handle: Handle,
631}
632unsafe impl Send for Module {}
633unsafe impl Sync for Module {}
634
635impl Module {
636    pub fn id(&self) -> &str {
637        &self.id
638    }
639    pub fn version(&self) -> &str {
640        &self.version
641    }
642    pub fn library_sha256(&self) -> &str {
643        &self.library_sha256
644    }
645    /// The factory's display name.
646    pub fn name(&self) -> &str {
647        &self.name
648    }
649    pub fn injects(&self) -> Vec<TypeKey> {
650        self.injects.to_vec()
651    }
652    /// The config's JSON Schema, when the plugin exported one.
653    pub fn schema(&self) -> Option<&rutis_sdk::serde_json::Value> {
654        self.schema.as_ref()
655    }
656    /// The plugin's factory over JSON config. Build plugins with
657    /// [`Module::build`]: a plugin built here directly is not marked as
658    /// this library's code, and what it provides of a `#[rutis::service]`
659    /// type of the library is not served by name (only the program's own
660    /// marked types are, for code of no library).
661    pub fn factory(&self) -> &dyn PluginFactory<ConfigValue> {
662        self.factory.as_ref()
663    }
664    /// The generation the library was loaded as (`rutis::service::loading`).
665    pub fn generation(&self) -> Generation {
666        self.generation
667    }
668    /// Build the plugin for `config`, its fiber marked as this library's
669    /// code (`rutis::service::set_generation`): a `#[rutis::service]` value
670    /// it provides is served with this library's blocks, even when another
671    /// build of the same plugin, with the same `TypeId`s, is loaded too.
672    pub fn build(&self, config: &ConfigValue) -> Result<Box<dyn DynPlugin>, Error> {
673        Ok(Box::new(InGeneration {
674            plugin: self.factory.build(config)?,
675            generation: self.generation,
676        }))
677    }
678}
679
680/// A plugin of a loaded library, which marks its fiber as that library's
681/// code when it is applied.
682struct InGeneration {
683    plugin: Box<dyn DynPlugin>,
684    generation: Generation,
685}
686
687impl DynPlugin for InGeneration {
688    fn name(&self) -> &str {
689        self.plugin.name()
690    }
691    fn injects(&self) -> Vec<TypeKey> {
692        self.plugin.injects()
693    }
694    fn validate(&self) -> Result<(), Error> {
695        self.plugin.validate()
696    }
697    fn platform(&self) -> bool {
698        self.plugin.platform()
699    }
700    fn apply<'a>(
701        &'a self,
702        ctx: &'a Ctx,
703    ) -> rutis::host::BoxFuture<'a, Result<rutis::host::Effect, Error>> {
704        rutis::internal::service::set_generation(ctx, self.generation);
705        self.plugin.apply(ctx)
706    }
707}
708
709#[derive(Clone)]
710pub struct DylibConfig {
711    module: Arc<Module>,
712    value: ConfigValue,
713}
714impl DylibConfig {
715    pub fn new(module: Arc<Module>, value: ConfigValue) -> Self {
716        Self { module, value }
717    }
718    pub fn module(&self) -> &Arc<Module> {
719        &self.module
720    }
721}
722
723struct DylibFactory {
724    id: String,
725    name: String,
726    injects: Vec<TypeKey>,
727}
728impl DylibFactory {
729    fn check_module(&self, module: &Module) -> Result<(), Error> {
730        if self.id != module.id || self.name != module.name || self.injects != module.injects {
731            return Err(rutis::Error::from(ErrorKind::Validation { issues: vec!["plugin identity or dependency declaration changed; dispose and spawn a new fiber".into()] }));
732        }
733        Ok(())
734    }
735}
736impl PluginFactory<DylibConfig> for DylibFactory {
737    fn name(&self) -> &str {
738        &self.name
739    }
740    fn injects(&self) -> Vec<TypeKey> {
741        self.injects.to_vec()
742    }
743    fn validate_config(&self, config: &DylibConfig) -> Result<(), Error> {
744        self.check_module(&config.module)?;
745        config.module.factory.validate_config(&config.value)
746    }
747    fn build(&self, config: &DylibConfig) -> Result<Box<dyn DynPlugin>, Error> {
748        self.check_module(&config.module)?;
749        config.module.build(&config.value)
750    }
751}
752
753// The SDK cannot depend on rutis-dylib-meta (that would change its identity),
754// so the boot format is written down twice. Keep the two in step.
755const _: () = {
756    assert!(BOOT_SIZE == rutis_dylib_meta::BOOT_SIZE);
757    assert!(BOOT_MAGIC.len() == rutis_dylib_meta::BOOT_MAGIC.len());
758    let mut i = 0;
759    while i < BOOT_MAGIC.len() {
760        assert!(BOOT_MAGIC[i] == rutis_dylib_meta::BOOT_MAGIC[i]);
761        i += 1;
762    }
763};
764
765fn sha_bytes(bytes: &[u8]) -> String {
766    format!("{:x}", Sha256::digest(bytes))
767}
768
769#[cfg(target_os = "macos")]
770fn reject_quarantined(path: &Path) -> Result<(), String> {
771    if crate::macos::quarantined(path)? {
772        return Err(format!(
773            "{} has the com.apple.quarantine attribute; loading it would wait for Gatekeeper. \
774             If you trust it, run: xattr -d com.apple.quarantine {}",
775            path.display(),
776            path.display()
777        ));
778    }
779    Ok(())
780}
781
782/// Places `bytes` at `path` unless a correct copy is already there, and
783/// returns the file opened by `platform::open_pinned` after its hash was
784/// checked through that handle.
785fn ensure_cached(path: &Path, bytes: &[u8], hash: &str) -> Result<fs::File, String> {
786    if let Ok(file) = open_matching(path, hash) {
787        return Ok(file);
788    }
789    let dir = path.parent().ok_or("cache path has no parent")?;
790    fs::create_dir_all(dir).map_err(|e| e.to_string())?;
791    let mut staged = tempfile::NamedTempFile::new_in(dir).map_err(|e| e.to_string())?;
792    staged.write_all(bytes).map_err(|e| e.to_string())?;
793    staged.as_file().sync_all().map_err(|e| e.to_string())?;
794    staged.persist(path).map_err(|e| e.to_string())?;
795    open_matching(path, hash)
796        .map_err(|e| format!("cached library SHA-256 mismatch after atomic replacement: {e}"))
797}
798
799fn open_matching(path: &Path, hash: &str) -> Result<fs::File, String> {
800    let mut file = platform::open_pinned(path).map_err(|e| format!("{}: {e}", path.display()))?;
801    let mut bytes = Vec::new();
802    file.read_to_end(&mut bytes)
803        .map_err(|e| format!("{}: {e}", path.display()))?;
804    let actual = sha_bytes(&bytes);
805    if actual != hash {
806        return Err(format!("{}: SHA-256 is {actual}", path.display()));
807    }
808    Ok(file)
809}
810
811#[cfg(test)]
812mod generation_tests {
813    use super::*;
814    use std::ptr::NonNull;
815    use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
816
817    /// Two loaders opening one file at once agree on the generation its
818    /// initializers ran in: the first opening runs them (slowly here), the
819    /// second gets the mapping already there.
820    #[test]
821    fn concurrent_openings_record_the_generation_the_initializers_ran_in() {
822        static INITIALIZED: AtomicBool = AtomicBool::new(false);
823        static RAN_IN: AtomicU64 = AtomicU64::new(0);
824        let fake = NonNull::new(0x5eed_usize as *mut std::ffi::c_void).unwrap();
825        let handle = fake.as_ptr() as usize;
826        let open = move || -> Result<Handle, String> {
827            if !INITIALIZED.swap(true, Ordering::SeqCst) {
828                // The initializers: they register as the current generation.
829                let generation =
830                    rutis::internal::service::current_loading().expect("inside loading");
831                std::thread::sleep(std::time::Duration::from_millis(100));
832                RAN_IN.store(generation.id(), Ordering::SeqCst);
833            }
834            Ok(NonNull::new(handle as *mut std::ffi::c_void).unwrap())
835        };
836        let (a, b) = std::thread::scope(|scope| {
837            let a = scope.spawn(|| open_generation_with(open).unwrap().1);
838            std::thread::sleep(std::time::Duration::from_millis(20));
839            let b = scope.spawn(|| open_generation_with(open).unwrap().1);
840            (a.join().unwrap(), b.join().unwrap())
841        });
842        assert_eq!(a, b);
843        assert_eq!(a.id(), RAN_IN.load(Ordering::SeqCst));
844    }
845}