rutis-dylib 0.19.2

Optional loader for trusted rutis dylib plugins
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
//! guarantee: bridge/marked-services
//! Optional in-process loader for trusted, first-party Rust dylib plugins.
//! A verified, immutable bundle launcher must run the host before this API is
//! used: a mismatched SDK can execute during Rust startup, before `Loader::new`.
//!
//! Everything here is platform-independent; opening libraries, finding
//! symbols and locating the loaded SDK live in `crate::platform`.

#[cfg(panic = "abort")]
compile_error!("rutis-dylib requires panic = unwind");

use crate::platform::{self, Handle};
use rutis::host::{CtxHost, ErrorKind};
use rutis::host::{DynPlugin, FiberView, PluginFactory, TypeKey};
use rutis::internal::service::Generation;
use rutis::{Ctx, Error};
use rutis_sdk::{ConfigValue, PluginMeta, BOOT_MAGIC, BOOT_SIZE, SDK_ID};
use serde::Deserialize;
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::fs;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::SystemTime;

#[derive(Debug, thiserror::Error)]
#[error("plugin {plugin} {version}: {step}: {reason}")]
pub struct LoadError {
    pub plugin: String,
    pub version: String,
    pub step: &'static str,
    pub reason: String,
}

fn error(plugin: &str, version: &str, step: &'static str, reason: impl Into<String>) -> LoadError {
    LoadError {
        plugin: plugin.into(),
        version: version.into(),
        step,
        reason: reason.into(),
    }
}

#[derive(Deserialize)]
struct Manifest {
    plugin: PluginManifest,
    sdk: SdkManifest,
    #[serde(default)]
    interfaces: HashMap<String, String>,
    build: BuildManifest,
}

#[derive(Deserialize)]
struct PluginManifest {
    id: String,
    version: String,
    library: String,
    library_sha256: String,
    /// Native libraries the plugin links, as its dynamic section records them.
    native_deps: Vec<String>,
}
#[derive(Deserialize)]
struct SdkManifest {
    version: String,
    id: String,
    artifact_sha256: String,
}
#[derive(Deserialize)]
struct BuildManifest {
    target: String,
    rustc: String,
    lock_sha256: String,
}

#[derive(Debug, Clone)]
pub struct ModuleDiagnostic {
    pub id: String,
    pub version: String,
    pub library_sha256: String,
    pub mapped_bytes: u64,
    pub loaded_at: SystemTime,
    /// Includes the loader's own reference, plus caller and fiber references.
    pub strong_references: usize,
    pub usable: bool,
}

struct Retained {
    id: String,
    version: String,
    hash: String,
    bytes: u64,
    loaded_at: SystemTime,
    module: Option<Arc<Module>>,
    generation: Generation,
    _handle: Handle,
}

/// The generation each library mapped in this process was loaded as
/// (`rutis::service::loading`), by its handle: opening a library again
/// returns the mapping already there, whose initializers do not run again,
/// so its blocks stay those of the first opening. One entry per library
/// mapped, which is never unmapped: bounded, like the libraries, by the
/// loaders' version limits.
static GENERATIONS: Mutex<Vec<(usize, Generation)>> = Mutex::new(Vec::new());

/// Open `path`, its initializers registering its `#[rutis::service]`
/// blocks as a generation of their own (two builds of one plugin keep their
/// types' TypeIds; each serves its values with its own blocks). The lock is
/// held across the opening and the recording, so two loaders opening the
/// same file at once agree on the generation of its one mapping.
///
/// # Safety
///
/// As `platform::open_library`: the library's initializers run in this
/// process.
unsafe fn open_generation(path: &Path) -> Result<(Handle, Generation), String> {
    open_generation_with(|| unsafe { platform::open_library(path) })
}

/// [`open_generation`] with `open` mapping the library.
fn open_generation_with(
    open: impl FnOnce() -> Result<Handle, String>,
) -> Result<(Handle, Generation), String> {
    let mut known = GENERATIONS
        .lock()
        .unwrap_or_else(|poison| poison.into_inner());
    let (opened, generation) = rutis::internal::service::loading(open);
    let handle = opened?;
    let key = handle.as_ptr() as usize;
    if let Some((_, generation)) = known.iter().find(|(handle, _)| *handle == key) {
        return Ok((handle, *generation));
    }
    known.push((key, generation));
    Ok((handle, generation))
}

// Library handles are process-global, remain mapped forever, and may be used
// on any thread. We never call dlclose or FreeLibrary, including when a
// rejected load is dropped.
unsafe impl Send for Retained {}

/// Host-side loader. Construct it after the independent bundle launcher has
/// verified the host, SDK and dynamic libstd files, and before creating root.
pub struct Loader {
    sdk_artifact_sha256: String,
    /// File names plugins must use for the SDK and the host's libstd.
    sdk_library: String,
    std_library: String,
    #[cfg(target_os = "macos")]
    allowed_team_ids: Option<Vec<String>>,
    cache: PathBuf,
    interfaces: HashMap<String, semver::Version>,
    max_versions: usize,
    retained: Mutex<Vec<Retained>>,
}

impl Loader {
    pub fn new(
        sdk_artifact_sha256: impl Into<String>,
        cache: impl Into<PathBuf>,
        interfaces: HashMap<String, semver::Version>,
        max_versions: usize,
    ) -> Result<Self, LoadError> {
        let sdk_artifact_sha256 = sdk_artifact_sha256.into();
        if !rutis_sdk::is_sha256(&sdk_artifact_sha256) {
            return Err(error(
                "<host>",
                "",
                "startup",
                "invalid embedded SDK artifact SHA-256",
            ));
        }
        let mut buf = [0_u8; 128];
        let len = unsafe { rutis_sdk::rutis_sdk_boot_id(buf.as_mut_ptr(), buf.len()) };
        if len != SDK_ID.len() || &buf[..len] != SDK_ID.as_bytes() {
            return Err(error(
                "<host>",
                "",
                "startup",
                "loaded SDK identity differs from host",
            ));
        }
        let actual = platform::loaded_sdk_path().map_err(|e| error("<host>", "", "startup", e))?;
        let sdk_bytes = fs::read(&actual).map_err(|e| {
            error(
                "<host>",
                "",
                "startup",
                format!("{}: {e}", actual.display()),
            )
        })?;
        let actual_hash = sha_bytes(&sdk_bytes);
        if actual_hash != sdk_artifact_sha256 {
            return Err(error("<host>", "", "startup", format!("loaded SDK artifact mismatch at {}: expected {sdk_artifact_sha256}, got {actual_hash}", actual.display())));
        }
        let startup = |e: String| error("<host>", "", "startup", e);
        let sdk_library =
            rutis_dylib_meta::sdk_reference(rutis_sdk::SDK_TARGET).map_err(startup)?;
        let std_library =
            rutis_dylib_meta::std_reference(&sdk_bytes, rutis_sdk::SDK_TARGET).map_err(startup)?;
        Ok(Self {
            sdk_artifact_sha256,
            sdk_library,
            std_library,
            #[cfg(target_os = "macos")]
            allowed_team_ids: None,
            cache: cache.into(),
            interfaces,
            max_versions,
            retained: Mutex::new(Vec::new()),
        })
    }

    /// Only load plugins with a valid signature from an Apple-issued
    /// certificate of one of these Team IDs. Ad-hoc signed plugins are then
    /// rejected. Without this call, the signer is not checked.
    #[cfg(target_os = "macos")]
    pub fn require_team_ids(mut self, team_ids: Vec<String>) -> Self {
        self.allowed_team_ids = Some(team_ids);
        self
    }

    /// Loads trusted code.
    ///
    /// # Safety
    ///
    /// The caller is responsible for accepting that library initializers run
    /// inside the host as soon as `dlopen` is called.
    pub unsafe fn load(&self, dir: impl AsRef<Path>) -> Result<Arc<Module>, LoadError> {
        let manifest_path = dir.as_ref().join("plugin.toml");
        let source = fs::read_to_string(&manifest_path)
            .map_err(|e| error("<unknown>", "", "manifest", e.to_string()))?;
        let manifest: Manifest = toml::from_str(&source)
            .map_err(|e| error("<unknown>", "", "manifest", e.to_string()))?;
        let id = &manifest.plugin.id;
        let version = &manifest.plugin.version;
        let fail = |step, reason| error(id, version, step, reason);
        if id.is_empty() || version.is_empty() {
            return Err(fail(
                "manifest",
                "plugin id and version must be nonempty".into(),
            ));
        }
        if manifest.build.target != rutis_sdk::SDK_TARGET {
            return Err(fail(
                "manifest",
                format!("target mismatch: {}", manifest.build.target),
            ));
        }
        if manifest.build.rustc != rutis_sdk::SDK_RUSTC_VERSION {
            return Err(fail(
                "manifest",
                format!("rustc mismatch: {}", manifest.build.rustc),
            ));
        }
        if manifest.sdk.id != SDK_ID || manifest.sdk.artifact_sha256 != self.sdk_artifact_sha256 {
            return Err(fail(
                "manifest",
                format!(
                    "SDK mismatch: manifest id={} artifact={}, host id={} artifact={}",
                    manifest.sdk.id, manifest.sdk.artifact_sha256, SDK_ID, self.sdk_artifact_sha256
                ),
            ));
        }
        if manifest.sdk.version != rutis_sdk::SDK_VERSION {
            return Err(fail(
                "manifest",
                format!("SDK version mismatch: {}", manifest.sdk.version),
            ));
        }
        if !rutis_sdk::is_sha256(&manifest.plugin.library_sha256)
            || !rutis_sdk::is_sha256(&manifest.build.lock_sha256)
        {
            return Err(fail("manifest", "invalid SHA-256 field".into()));
        }
        for (name, requirement) in &manifest.interfaces {
            let req = semver::VersionReq::parse(requirement)
                .map_err(|e| fail("interfaces", e.to_string()))?;
            let actual = self
                .interfaces
                .get(name)
                .ok_or_else(|| fail("interfaces", format!("missing interface {name}")))?;
            if !req.matches(actual) {
                return Err(fail(
                    "interfaces",
                    format!("{name} {actual} does not meet {req}"),
                ));
            }
        }
        let library = Path::new(&manifest.plugin.library);
        if library.components().count() != 1 || library.file_name().is_none() {
            return Err(fail("manifest", "library must be a filename".into()));
        }
        let source_library = dir.as_ref().join(library);
        // Checked before the bytes are read: the cache copy drops extended
        // attributes, and copying it there is no consent to load it.
        #[cfg(target_os = "macos")]
        reject_quarantined(&source_library).map_err(|e| fail("quarantine", e))?;
        let bytes = fs::read(&source_library).map_err(|e| fail("binary", e.to_string()))?;
        let actual_hash = sha_bytes(&bytes);
        if actual_hash != manifest.plugin.library_sha256 {
            return Err(fail(
                "binary",
                format!("library SHA-256 mismatch: {actual_hash}"),
            ));
        }
        let boot = rutis_dylib_meta::read_boot(&bytes, rutis_sdk::SDK_TARGET)
            .map_err(|e| fail("boot metadata", e))?;
        if boot.sdk_id != SDK_ID
            || boot.sdk_artifact != self.sdk_artifact_sha256
            || boot.sdk_id != manifest.sdk.id
            || boot.sdk_artifact != manifest.sdk.artifact_sha256
            || boot.id != *id
            || boot.version != *version
        {
            return Err(fail(
                "boot metadata",
                "binary identity differs from manifest or host".into(),
            ));
        }
        // dlopen would resolve these before any check of ours could run again.
        let native = rutis_dylib_meta::check_plugin_dependencies(
            &bytes,
            rutis_sdk::SDK_TARGET,
            &rutis_dylib_meta::SharedLibraries {
                sdk: &self.sdk_library,
                std: &self.std_library,
            },
        )
        .map_err(|e| fail("dependencies", e))?;
        let mut declared = manifest.plugin.native_deps.clone();
        declared.sort();
        declared.dedup();
        if native != declared {
            return Err(fail(
                "dependencies",
                format!("binary links native libraries {native:?}, manifest declares {declared:?}"),
            ));
        }
        let mut retained = self.retained.lock().unwrap();
        let existing_slot = retained
            .iter()
            .position(|entry| entry.id == *id && entry.hash == actual_hash);
        let (handle, generation, slot) = if let Some(slot) = existing_slot {
            if let Some(module) = &retained[slot].module {
                return Ok(module.clone());
            }
            // A previous entry/metadata attempt failed after dlopen. Retry on
            // the retained mapping without consuming another version slot.
            (retained[slot]._handle, retained[slot].generation, slot)
        } else {
            if retained.iter().filter(|entry| entry.id == *id).count() >= self.max_versions {
                return Err(fail(
                    "retention",
                    format!(
                        "version limit {} reached; restart the host to reclaim code",
                        self.max_versions
                    ),
                ));
            }
            let cached = self.cache.join(&actual_hash).join(library);
            // Held from the hash check until the library is mapped. On
            // Windows the share mode refuses writes, deletes and renames
            // meanwhile; elsewhere the cache must be trusted (SDK design §5).
            let _pinned =
                ensure_cached(&cached, &bytes, &actual_hash).map_err(|e| fail("cache", e))?;
            // A reused cache entry may have been placed by hand.
            #[cfg(target_os = "macos")]
            {
                reject_quarantined(&cached).map_err(|e| fail("quarantine", e))?;
                if let Some(team_ids) = &self.allowed_team_ids {
                    crate::macos::check_team_id(&cached, team_ids)
                        .map_err(|e| fail("code signature", e))?;
                }
            }
            let (handle, generation) =
                open_generation(&cached).map_err(|e| fail(platform::OPEN_STEP, e))?;
            // This is the plugin's newest build: names are looked up in it,
            // not in the earlier ones, whose blocks keep serving the values
            // they provided.
            rutis::internal::service::supersede(
                retained
                    .iter()
                    .filter(|entry| entry.id == *id && entry.generation != generation)
                    .map(|entry| entry.generation),
            );
            // Every successfully opened library remains mapped, even if entry fails.
            retained.push(Retained {
                id: id.clone(),
                version: version.clone(),
                hash: actual_hash.clone(),
                bytes: bytes.len() as u64,
                loaded_at: SystemTime::now(),
                module: None,
                generation,
                _handle: handle,
            });
            (handle, generation, retained.len() - 1)
        };
        let meta_fn: unsafe fn() -> PluginMeta =
            symbol(handle, b"rutis_plugin_meta\0").map_err(|e| fail("metadata", e))?;
        let meta = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| meta_fn()))
            .map_err(|_| fail("metadata", "metadata function panicked".into()))?;
        if meta.sdk_id != SDK_ID
            || meta.sdk_artifact_sha256 != self.sdk_artifact_sha256
            || meta.sdk_id != boot.sdk_id
            || meta.sdk_artifact_sha256 != boot.sdk_artifact
            || meta.id != id
            || meta.version != version
        {
            return Err(fail(
                "metadata",
                "runtime identity differs from boot metadata or manifest".into(),
            ));
        }
        let entry: unsafe fn() -> Result<Box<dyn PluginFactory<ConfigValue>>, Error> =
            symbol(handle, b"rutis_plugin_entry\0").map_err(|e| fail("entry", e))?;
        let factory = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| entry()))
            .map_err(|_| fail("entry", "factory entry panicked".into()))?
            .map_err(|e| fail("entry", e.to_string()))?;
        let (name, injects) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            (factory.name().to_string(), factory.injects().to_vec())
        }))
        .map_err(|_| fail("entry", "factory metadata panicked".into()))?;
        // Optional: plugins built before the symbol existed have no schema.
        let schema = match optional_symbol::<unsafe fn() -> Option<String>>(
            handle,
            b"rutis_plugin_config_schema\0",
        ) {
            None => None,
            Some(schema_fn) => {
                let text = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| schema_fn()))
                    .map_err(|_| fail("schema", "schema function panicked".into()))?;
                match text {
                    None => None,
                    Some(text) => Some(
                        rutis_sdk::serde_json::from_str(&text)
                            .map_err(|e| fail("schema", format!("invalid JSON: {e}")))?,
                    ),
                }
            }
        };
        let module = Arc::new(Module {
            id: id.clone(),
            version: version.clone(),
            library_sha256: actual_hash,
            name,
            injects,
            schema,
            factory,
            generation,
            _handle: handle,
        });
        retained[slot].module = Some(module.clone());
        Ok(module)
    }

    pub fn diagnostics(&self) -> Vec<ModuleDiagnostic> {
        self.retained
            .lock()
            .unwrap()
            .iter()
            .map(|entry| ModuleDiagnostic {
                id: entry.id.clone(),
                version: entry.version.clone(),
                library_sha256: entry.hash.clone(),
                mapped_bytes: entry.bytes,
                loaded_at: entry.loaded_at,
                strong_references: entry.module.as_ref().map(Arc::strong_count).unwrap_or(0),
                usable: entry.module.is_some(),
            })
            .collect()
    }

    pub fn spawn(
        &self,
        ctx: &Ctx,
        module: &Arc<Module>,
        value: ConfigValue,
    ) -> Result<FiberView, Error> {
        let factory = DylibFactory {
            id: module.id.clone(),
            name: module.name.clone(),
            injects: module.injects.clone(),
        };
        factory.validate_config(&DylibConfig::new(module.clone(), value.clone()))?;
        Ok(ctx.plugin_with(factory, DylibConfig::new(module.clone(), value)))
    }

    pub async fn swap(
        &self,
        view: &FiberView,
        module: &Arc<Module>,
        value: ConfigValue,
    ) -> Result<(), Arc<ErrorKind>> {
        let current = view.current_config::<DylibConfig>().ok_or_else(|| {
            Arc::new(ErrorKind::Validation {
                issues: vec!["fiber is not a dylib plugin".into()],
            })
        })?;
        let expected = DylibFactory {
            id: current.module.id.clone(),
            name: current.module.name.clone(),
            injects: current.module.injects.clone(),
        };
        expected
            .check_module(module)
            .map_err(|error| Arc::new(error.into_kind()))?;
        view.update(DylibConfig::new(module.clone(), value)).await
    }
}

pub struct Module {
    id: String,
    version: String,
    library_sha256: String,
    name: String,
    injects: Vec<TypeKey>,
    schema: Option<rutis_sdk::serde_json::Value>,
    factory: Box<dyn PluginFactory<ConfigValue>>,
    generation: Generation,
    _handle: Handle,
}
unsafe impl Send for Module {}
unsafe impl Sync for Module {}

impl Module {
    pub fn id(&self) -> &str {
        &self.id
    }
    pub fn version(&self) -> &str {
        &self.version
    }
    pub fn library_sha256(&self) -> &str {
        &self.library_sha256
    }
    /// The factory's display name.
    pub fn name(&self) -> &str {
        &self.name
    }
    pub fn injects(&self) -> Vec<TypeKey> {
        self.injects.to_vec()
    }
    /// The config's JSON Schema, when the plugin exported one.
    pub fn schema(&self) -> Option<&rutis_sdk::serde_json::Value> {
        self.schema.as_ref()
    }
    /// The plugin's factory over JSON config. Build plugins with
    /// [`Module::build`]: a plugin built here directly is not marked as
    /// this library's code, and what it provides of a `#[rutis::service]`
    /// type of the library is not served by name (only the program's own
    /// marked types are, for code of no library).
    pub fn factory(&self) -> &dyn PluginFactory<ConfigValue> {
        self.factory.as_ref()
    }
    /// The generation the library was loaded as (`rutis::service::loading`).
    pub fn generation(&self) -> Generation {
        self.generation
    }
    /// Build the plugin for `config`, its fiber marked as this library's
    /// code (`rutis::service::set_generation`): a `#[rutis::service]` value
    /// it provides is served with this library's blocks, even when another
    /// build of the same plugin, with the same `TypeId`s, is loaded too.
    pub fn build(&self, config: &ConfigValue) -> Result<Box<dyn DynPlugin>, Error> {
        Ok(Box::new(InGeneration {
            plugin: self.factory.build(config)?,
            generation: self.generation,
        }))
    }
}

/// A plugin of a loaded library, which marks its fiber as that library's
/// code when it is applied.
struct InGeneration {
    plugin: Box<dyn DynPlugin>,
    generation: Generation,
}

impl DynPlugin for InGeneration {
    fn name(&self) -> &str {
        self.plugin.name()
    }
    fn injects(&self) -> Vec<TypeKey> {
        self.plugin.injects()
    }
    fn validate(&self) -> Result<(), Error> {
        self.plugin.validate()
    }
    fn platform(&self) -> bool {
        self.plugin.platform()
    }
    fn apply<'a>(
        &'a self,
        ctx: &'a Ctx,
    ) -> rutis::host::BoxFuture<'a, Result<rutis::host::Effect, Error>> {
        rutis::internal::service::set_generation(ctx, self.generation);
        self.plugin.apply(ctx)
    }
}

#[derive(Clone)]
pub struct DylibConfig {
    module: Arc<Module>,
    value: ConfigValue,
}
impl DylibConfig {
    pub fn new(module: Arc<Module>, value: ConfigValue) -> Self {
        Self { module, value }
    }
    pub fn module(&self) -> &Arc<Module> {
        &self.module
    }
}

struct DylibFactory {
    id: String,
    name: String,
    injects: Vec<TypeKey>,
}
impl DylibFactory {
    fn check_module(&self, module: &Module) -> Result<(), Error> {
        if self.id != module.id || self.name != module.name || self.injects != module.injects {
            return Err(rutis::Error::from(ErrorKind::Validation { issues: vec!["plugin identity or dependency declaration changed; dispose and spawn a new fiber".into()] }));
        }
        Ok(())
    }
}
impl PluginFactory<DylibConfig> for DylibFactory {
    fn name(&self) -> &str {
        &self.name
    }
    fn injects(&self) -> Vec<TypeKey> {
        self.injects.to_vec()
    }
    fn validate_config(&self, config: &DylibConfig) -> Result<(), Error> {
        self.check_module(&config.module)?;
        config.module.factory.validate_config(&config.value)
    }
    fn build(&self, config: &DylibConfig) -> Result<Box<dyn DynPlugin>, Error> {
        self.check_module(&config.module)?;
        config.module.build(&config.value)
    }
}

// The SDK cannot depend on rutis-dylib-meta (that would change its identity),
// so the boot format is written down twice. Keep the two in step.
const _: () = {
    assert!(BOOT_SIZE == rutis_dylib_meta::BOOT_SIZE);
    assert!(BOOT_MAGIC.len() == rutis_dylib_meta::BOOT_MAGIC.len());
    let mut i = 0;
    while i < BOOT_MAGIC.len() {
        assert!(BOOT_MAGIC[i] == rutis_dylib_meta::BOOT_MAGIC[i]);
        i += 1;
    }
};

fn sha_bytes(bytes: &[u8]) -> String {
    format!("{:x}", Sha256::digest(bytes))
}

#[cfg(target_os = "macos")]
fn reject_quarantined(path: &Path) -> Result<(), String> {
    if crate::macos::quarantined(path)? {
        return Err(format!(
            "{} has the com.apple.quarantine attribute; loading it would wait for Gatekeeper. \
             If you trust it, run: xattr -d com.apple.quarantine {}",
            path.display(),
            path.display()
        ));
    }
    Ok(())
}

/// Places `bytes` at `path` unless a correct copy is already there, and
/// returns the file opened by `platform::open_pinned` after its hash was
/// checked through that handle.
fn ensure_cached(path: &Path, bytes: &[u8], hash: &str) -> Result<fs::File, String> {
    if let Ok(file) = open_matching(path, hash) {
        return Ok(file);
    }
    let dir = path.parent().ok_or("cache path has no parent")?;
    fs::create_dir_all(dir).map_err(|e| e.to_string())?;
    let mut staged = tempfile::NamedTempFile::new_in(dir).map_err(|e| e.to_string())?;
    staged.write_all(bytes).map_err(|e| e.to_string())?;
    staged.as_file().sync_all().map_err(|e| e.to_string())?;
    staged.persist(path).map_err(|e| e.to_string())?;
    open_matching(path, hash)
        .map_err(|e| format!("cached library SHA-256 mismatch after atomic replacement: {e}"))
}

fn open_matching(path: &Path, hash: &str) -> Result<fs::File, String> {
    let mut file = platform::open_pinned(path).map_err(|e| format!("{}: {e}", path.display()))?;
    let mut bytes = Vec::new();
    file.read_to_end(&mut bytes)
        .map_err(|e| format!("{}: {e}", path.display()))?;
    let actual = sha_bytes(&bytes);
    if actual != hash {
        return Err(format!("{}: SHA-256 is {actual}", path.display()));
    }
    Ok(file)
}

unsafe fn optional_symbol<T>(handle: Handle, name: &[u8]) -> Option<T> {
    platform::find_symbol(handle, name)
        .ok()
        .map(|ptr| std::mem::transmute_copy(&ptr))
}

unsafe fn symbol<T>(handle: Handle, name: &[u8]) -> Result<T, String> {
    debug_assert_eq!(
        std::mem::size_of::<T>(),
        std::mem::size_of::<*mut std::ffi::c_void>()
    );
    platform::find_symbol(handle, name).map(|ptr| std::mem::transmute_copy(&ptr))
}

#[cfg(test)]
mod generation_tests {
    use super::*;
    use std::ptr::NonNull;
    use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};

    /// Two loaders opening one file at once agree on the generation its
    /// initializers ran in: the first opening runs them (slowly here), the
    /// second gets the mapping already there.
    #[test]
    fn concurrent_openings_record_the_generation_the_initializers_ran_in() {
        static INITIALIZED: AtomicBool = AtomicBool::new(false);
        static RAN_IN: AtomicU64 = AtomicU64::new(0);
        let fake = NonNull::new(0x5eed_usize as *mut std::ffi::c_void).unwrap();
        let handle = fake.as_ptr() as usize;
        let open = move || -> Result<Handle, String> {
            if !INITIALIZED.swap(true, Ordering::SeqCst) {
                // The initializers: they register as the current generation.
                let generation =
                    rutis::internal::service::current_loading().expect("inside loading");
                std::thread::sleep(std::time::Duration::from_millis(100));
                RAN_IN.store(generation.id(), Ordering::SeqCst);
            }
            Ok(NonNull::new(handle as *mut std::ffi::c_void).unwrap())
        };
        let (a, b) = std::thread::scope(|scope| {
            let a = scope.spawn(|| open_generation_with(open).unwrap().1);
            std::thread::sleep(std::time::Duration::from_millis(20));
            let b = scope.spawn(|| open_generation_with(open).unwrap().1);
            (a.join().unwrap(), b.join().unwrap())
        });
        assert_eq!(a, b);
        assert_eq!(a.id(), RAN_IN.load(Ordering::SeqCst));
    }
}