chillffi 0.3.0

A simple isolated dynamic FFI framework for Rust
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
use crate::errnoPolicy::globalReadErrno;
use crate::ffi::types::Type;
use crate::ffi::types::primitive::{Arg, FfiArg, FfiPrimitive};
use crate::ffi::types::Value;
use crate::ffi::scope::currentScopeReadErrno;
use std::cell::RefMut;
use std::marker::PhantomData;
use parking_lot::RwLockReadGuard;
use parking_lot::RwLock;
use crate::ffi::errors::FFIError;
use fxhash::FxHashMap;
use crate::zygote::ZygoteState;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{OnceLock};
use crate::__ffiInternal::ClonedZygote;
use crate::zygote::{FFIRequest, FFIResponse, ZygoteStack};
// =================================================================================================

/// Counter for assigning unique identifiers to libraries.
static NextLibraryID: AtomicUsize = AtomicUsize::new(1);
/// Global registry of loaded libraries by their identifiers.
static RegisteredLibraries: OnceLock<RwLock<FxHashMap<usize, String>>> = OnceLock::new();

/// Returns the next unique library identifier.
#[inline(always)]
pub(super) fn nextLibraryId() -> usize
{
  NextLibraryID.fetch_add(1, Ordering::SeqCst)
}

/// Returns the global registry of registered libraries.
#[inline(always)]
fn getRegistry() -> &'static RwLock<FxHashMap<usize, String>>
{
  RegisteredLibraries.get_or_init(|| RwLock::new(FxHashMap::default()))
}

/// Adds a library to the registry by its identifier.
#[inline]
pub(super) fn registerLibrary(id: usize, path: &str) -> ()
{
  getRegistry().write().insert(id, path.to_string());
}

/// Removes a library from the registry by its identifier.
#[inline]
fn unregisterLibrary(id: usize) -> ()
{
  getRegistry().write().remove(&id);
}

// =================================================================================================

thread_local!{
  /// errno captured by the most recently completed request, if the request
  /// asked for it (see [`FFIRequest::Call`]/[`FFIRequest::CallPointer`]).
  /// Overwritten by every `sendRawRequest` call, including non-Call ones —
  /// so it always reflects "immediately after the last thing that ran",
  /// which is what a caller checking it right after a suspicious result wants.
  static LastErrno: std::cell::Cell<Option<i32>> = const {
    std::cell::Cell::new(None) 
  };
}

/// Reads the errno left behind by the most recent request on this thread.
/// See [`crate::ffi::scope::Scope::lastErrno`] — the public entry point.
pub(super) fn lastErrno() -> Option<i32>
{
  LastErrno.with(|e| e.get())
}

/// Resolves the effective errno-capture flag for a call: an explicit
/// per-call override wins, then the enclosing scope's override (see
/// [`Scope::setReadErrno`](crate::ffi::scope::Scope::setReadErrno)), then the
/// global default (see [`crate::errnoPolicy::setGlobalReadErrno`]) — same
/// most-specific-wins order as [`Scope::load`](crate::ffi::scope::Scope::load)'s
/// path resolution.
#[inline]
pub(super) fn resolveReadErrno(perCall: Option<bool>) -> bool
{
  perCall
    .unwrap_or_else(|| currentScopeReadErrno()
      .unwrap_or_else(globalReadErrno))
}

// =================================================================================================

/// Sends a raw FFI request to the active zygote clone in the current thread's stack.
pub(super) fn sendRawRequest(request: FFIRequest) -> Result<Value, FFIError>
{
  // Check whether the global zygote in ZygoteState has been initialized.
  if ZygoteState.get().is_none() {
    // todo For callById this will be a repeated check.
    //  But in callById it is better to check it immediately.
    return Err(FFIError::ZygoteNotInitialized);
  }

  // Retrieve the most recently pushed active zygote 
  // from the thread-local stack to execute the raw FFI request.
  ZygoteStack.with(|stack| {
    let mut mutStack: RefMut<Vec<ClonedZygote>> = stack.borrow_mut();
    let zygote: &mut ClonedZygote = mutStack.last_mut().ok_or(FFIError::NoActiveZygoteScope)?;

    match zygote.call(request) {
      Ok(FFIResponse::Ok(val, errno)) => {
        LastErrno.with(|e| e.set(errno));
        Ok(val)
      }
      Ok(FFIResponse::Err(err)) => Err(err),
      Err(err) => Err(FFIError::ZygoteCommunicationFailed(err))
    }
  })
}

/// Performs an FFI function call by the identifier of the registered library.
fn callById(
  libraryId: usize,
  libraryPath: &str,
  functionName: &str,
  args: Vec<Value>,
  resultType: Type,
  readErrno: bool
) -> Result<Value, FFIError>
{
  // Check whether the global zygote in ZygoteState has been initialized.
  if ZygoteState.get().is_none() {
    return Err(FFIError::ZygoteNotInitialized);
  }

  // Retrieve the path to the library from the registry and construct an FFIRequest.
  let registry: RwLockReadGuard<FxHashMap<usize, String>> = getRegistry().read();
  if !registry.contains_key(&libraryId) {
    return Err(FFIError::LibraryNotFound{ libraryPath: libraryPath.to_string() });
  }
  drop(registry);

  sendRawRequest(FFIRequest::Call {
    libraryPath: libraryPath.to_string(),
    functionName: functionName.to_string(),
    args,
    resultType,
    readErrno
  })
}

// =================================================================================================

/// Handle of a loaded library, bound to the [`Scope<'g>`] it was loaded through —
/// same model as [`AllocatedMemory<'g>`](crate::ffi::allocatedMemory::AllocatedMemory).
///
/// `Library<'g>` cannot outlive the scope that created it: there is no way to
/// construct one except via [`Scope::load`](crate::ffi::scope::Scope::load),
/// which requires a live `Scope<'g>` in the first place. This replaces the old
/// `__Library<const Allowed: bool>` gate — the lifetime *is* the gate now.
pub struct Library<'g>
{
  /// Library identifier.
  libraryId: usize,
  /// Path to the loaded library.
  libraryPath: String,
  /// Phantom lifetime marker tying the handle to the scope it was loaded through.
  _scope: PhantomData<&'g ()>
}

impl<'g> Library<'g>
{
  /// Creates a handle for an already-registered library. Only callable from
  /// [`Scope::load`](crate::ffi::scope::Scope::load) — `libraryId` must come
  /// from [`nextLibraryId`] and already be registered via [`registerLibrary`].
  #[inline(always)]
  pub(super) const fn new(libraryId: usize, libraryPath: String) -> Self
  {
    Self { libraryId, libraryPath, _scope: PhantomData }
  }

  /// Returns the library identifier.
  #[inline(always)]
  pub const fn id(&self) -> usize
  {
    self.libraryId
  }

  /// Returns the resolved path the library was loaded from.
  #[inline(always)]
  pub fn path(&self) -> &str
  {
    &self.libraryPath
  }
}

impl<'g> Drop for Library<'g>
{
  /// Manual or automatic deletion.
  fn drop(&mut self) {
    unregisterLibrary(self.libraryId)
  }
}

// =================================================================================================

/// Builder for fluent FFI calls.
#[doc(hidden)]
pub struct CallBuilder<'a, 'g>
{
  /// The library against which the call is issued.
  lib: &'a Library<'g>,

  /// Name of the function to look up and call.
  name: String,

  /// Arguments collected for the call, in order.
  args: Vec<Value>,

  /// Per-call override of errno capture. `None` falls through to the
  /// enclosing scope's setting, then the global default — see [`resolveReadErrno`].
  readErrno: Option<bool>
}

impl<'a, 'g> CallBuilder<'a, 'g>
{
  #[inline]
  pub fn new(lib: &'a Library<'g>, name: &str) -> Self
  {
    Self {
      lib,
      name: name.to_string(),
      args: Vec::new(),
      readErrno: None,
    }
  }

  /// Append one argument. Chainable.
  #[inline]
  pub fn arg<T: FfiArg>(mut self, arg: T) -> Self
  {
    self.args.push(arg.intoFfiValue().0);
    self
  }

  /// Forces errno capture for this call specifically, regardless of the
  /// scope's or global default. Read it back afterward via
  /// [`Scope::lastErrno`](crate::ffi::scope::Scope::lastErrno).
  #[inline]
  pub const fn errno(mut self) -> Self
  {
    self.readErrno = Some(true);
    self
  }

  /// Forces errno capture *off* for this call, overriding a scope/global
  /// default that would otherwise have enabled it.
  #[inline]
  pub const fn noErrno(mut self) -> Self
  {
    self.readErrno = Some(false);
    self
  }

  /// Finalize: execute and return a typed result.
  #[inline]
  pub fn result<T: FfiPrimitive>(self) -> Result<T, FFIError>
  {
    let readErrno: bool = resolveReadErrno(self.readErrno);
    self.lib.__call(&self.name, self.args, readErrno)
  }

  /// Finalize: execute and discard the result (void / fire-and-forget).
  #[inline]
  pub fn void(self) -> Result<(), FFIError>
  {
    let readErrno: bool = resolveReadErrno(self.readErrno);
    self.lib.__call::<()>(&self.name, self.args, readErrno).map(|_| ())
  }
}

// =================================================================================================

impl<'g> Library<'g>
{
  /// Starts a fluent call builder.
  #[inline]
  pub fn call(&self, name: &str) -> CallBuilder<'_, 'g>
  {
    CallBuilder::new(self, name)
  }

  /// Executes a function call from the loaded library.
  ///
  /// todo It should be completely hidden and not work directly
  #[inline]
  #[doc(hidden)]
  pub(crate) fn __call<T: FfiPrimitive>(
    &self,
    functionName: &str,
    args: Vec<Value>,
    readErrno: bool
  ) -> Result<T, FFIError>
  {
    let raw: Value = callById(
      self.libraryId, 
      &self.libraryPath, 
      functionName, args, 
      T::TypeTag, 
      readErrno
    )?;
    T::fromFfiValue(Arg(raw))
  }

  /// Fire-and-forget variant: a call without waiting for or typing the result.
  ///
  /// todo It should be completely hidden and not work directly
  #[inline]
  #[doc(hidden)]
  pub(crate) fn __callv(
    &self,
    functionName: &str,
    args: Vec<Value>
  ) -> Result<(), FFIError>
  {
    self.__call::<()>(functionName, args, resolveReadErrno(None))
  }

  // There is no variant with `let a = call(`. Because you either expect void, or specify the type.
  // It would be rough to require a different type specification if you can do it directly in `let a:`.

  /// Unloads the library and removes it from the registry;
  ///
  /// Here self instead of &self is used so that after removal it is not possible
  /// to use the library further. The compiler sees this.
  pub fn unload(self) -> Result<(), FFIError>
  {
    // Do nothing: at the end of the function self will be dropped,
    // and the Drop implementation will be triggered, 
    // which will call unregisterLibrary() itself.
    Ok(())
  }
}

// =================================================================================================

#[cfg(test)]
mod tests
{
  use crate::ffi;
  use crate::ffi::library::getRegistry;
  use crate::ffi::scope::Scope;
  // ===============================================================================================

  /// Checks that `.errno()` makes a failed call's errno observable via
  /// `Scope::lastErrno()` — `open()` on a path that can't exist sets ENOENT.
  #[test]
  fn errnoCapturedWhenRequested() -> ()
  {
    let errno: Option<i32> = ffi!(|scope| {
      let libc: Library = scope.load("libc.so.6")?;
      let fd: i32 =
        libc.call("open")
          .arg(c"/no/such/chillffi/test/path")
          .arg::<i32>(0 /* O_RDONLY */)
          .errno()
          .result()?;
      assert_eq!(fd, -1, "open() on a nonexistent path should fail");
      Ok(Scope::lastErrno())
    }).expect("errno capture test failed");

    assert_eq!(errno, Some(libc::ENOENT));
  }

  /// Checks that without `.errno()` (and no scope/global override), errno is
  /// not captured — `Scope::lastErrno()` stays `None` even after a call that
  /// itself set errno.
  #[test]
  fn errnoNoneWhenNotRequested() -> ()
  {
    let errno: Option<i32> = ffi!(|scope| {
      let libc: Library = scope.load("libc.so.6")?;
      let fd: i32 =
        libc.call("open")
          .arg(c"/no/such/chillffi/test/path2")
          .arg::<i32>(0)
          .result()?; // no .errno()
      assert_eq!(fd, -1);
      Ok(Scope::lastErrno())
    }).expect("errno-off test failed");

    assert_eq!(errno, None);
  }

  // ===============================================================================================

  /// Checks that library is removed from registry when explicitly dropped.
  #[test]
  fn libraryDrop() -> ()
  {
    let id: usize = ffi!(|scope| {
      let libm: Library = scope.load("libm.so.6")?;
      let id: usize = libm.id();
      drop(libm);
      Ok(id)
    }).expect("ffi block failed");

    assert!(!getRegistry().read().contains_key(&id));
  }

  /// Checks that library is removed from registry 
  /// when automatically dropped on scope exit.
  #[test]
  fn libraryAutoDrop() -> ()
  {
    let id: usize = ffi!(|scope| {
      let libm: Library = scope.load("libm.so.6")?;
      let id: usize = libm.id();
      Ok(id)
    }).expect("ffi block failed");

    assert!(!getRegistry().read().contains_key(&id));
  }

  /// Checks that library is removed from registry 
  /// when unloaded via [`unload()`].
  #[test]
  fn libraryUnload() -> ()
  {
    let id: usize = ffi!(|scope| {
      let libm: Library = scope.load("libm.so.6")?;
      let id: usize = libm.id();
      libm.unload()?;
      Ok(id)
    }).expect("ffi block failed");

    assert!(!getRegistry().read().contains_key(&id));
  }

  // ===============================================================================================

  /// Checks calling the sqrt function from the libm library.
  #[test]
  fn sqrt() -> ()
  {
    let result: f64 = ffi!(|scope| {
      let libm: Library = scope.load("libm.so.6")?;
      Ok( libm.call("sqrt").arg::<f64>(4.0).result()? )
    }).expect("FFI call failed");

    assert!((result - 2.0).abs() < f64::EPSILON);
  }

  /// Checks calling the abs function from the libm library.
  #[test]
  fn abs() -> ()
  {
    let result: i32 = ffi!(|scope| {
      let libm: Library = scope.load("libm.so.6")?;
      Ok( libm.call("abs").arg::<i32>(-5).result()? )
    }).expect("FFI call failed");

    assert_eq!(result, 5);
  }

  // ===============================================================================================

  /// Checks repeated calls inside a single [`ffi!`] - uses cached dlopen.
  #[test]
  fn multipleCallsInSingleLibrary() -> ()
  {
    let results: Vec<f64> = ffi!(|scope| {
      let mut outputs: Vec<f64> = Vec::with_capacity(10);
      let libm: Library = scope.load("libm.so.6")?;
  
      // 10 consecutive calls with a single loaded library
      for i in 1..=10 
      {
        let input: f64 = (i * i) as f64;
        let res: f64 = libm.call("sqrt").arg(input).result()?;
        outputs.push(res);
      }
  
      Ok(outputs)
    }).expect("Batch FFI call failed");

    assert_eq!(results.len(), 10);

    for (i, val) in results.into_iter().enumerate()
    {
      let expected: f64 = (i + 1) as f64;
      assert!((val - expected).abs() < f64::EPSILON, "Expected {}, got {}", expected, val);
    }
  }

  // ===============================================================================================
}

// =================================================================================================