chillffi 0.4.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
//! macOS backend for [`super::Transport`].
//!
//! Uses `ipc-channel` for both planes (Mach ports under the hood — direct
//! `SCM_RIGHTS` would be racy under Darwin's process-port inheritance).
//!
//! - **Control plane** (Runtime ↔ Main Zygote): one `IpcOneShotServer` set up
//!   in the Runtime; Main Zygote connects with `IpcSender::connect(name)`,
//!   hands over its own `IpcSender<ZygoteCommand>` + `IpcReceiver<ZygoteReply>`,
//!   and the one-shot is dropped.
//!
//! - **Data plane** (Runtime ↔ Clone): per-clone `IpcOneShotServer` opened by
//!   Main Zygote just before `libc::fork()`; the clone creates a fresh
//!   `ipc::channel()` pair, sends the Runtime-facing ends back through the
//!   one-shot, keeps the opposite ends, and enters the request loop.
// =================================================================================================
use super::Transport as TransportTrait;
use super::{
  CloneSide as CloneSideTrait, FFIRequest, FFIResponse,
  RuntimeSide as RuntimeSideTrait, ZygoteHandleBase
};
use crate::platform::low;
use crate::worker::executeFFI;
use crate::worker::{takeLastErrno, takeLastOsError};
use crate::zygote::ZygoteFlag;
use fxhash::FxHashMap;
use ipc_channel::ipc::{self, IpcOneShotServer, IpcReceiver, IpcSender};
use libloading::Library;
use serde::{Deserialize, Serialize};
use std::env;
use std::io;
use std::path::PathBuf;
use std::process::{Child, Command, Stdio};
// =================================================================================================

/// Backend tag used in diagnostics.
const BackendName: &str = "macos-ipc-channel";

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

/// Commands Runtime → Main Zygote.
#[derive(Serialize, Deserialize)]
pub enum ZygoteCommand
{
  /// Ask Main Zygote to `fork` a clone and return IPC endpoints to it.
  SpawnClone
}

/// Replies Main Zygote → Runtime.
///
/// `IpcSender` / `IpcReceiver` are transferable over ipc-channel themselves
/// (no manual `sendmsg` / SCM_RIGHTS).
#[derive(Serialize, Deserialize)]
pub enum ZygoteReply
{
  /// Clone is ready: transferable ipc-channel ends.
  Clone {
    pid: u32,
    requestTx: IpcSender<FFIRequest>,
    responseRx: IpcReceiver<FFIResponse>
  },
  
  /// `ipc::channel()` or `fork()` failed inside Main Zygote.
  SpawnFailed
}

/// First message from Zygote after connecting to Runtime's [`IpcOneShotServer`].
#[derive(Serialize, Deserialize)]
struct BootstrapToRuntime
{
  /// Runtime → Main Zygote commands.
  commandTx: IpcSender<ZygoteCommand>,

  /// Main Zygote → Runtime replies.
  replyRx: IpcReceiver<ZygoteReply>
}

/// First message from a freshly forked clone → Main Zygote.
#[derive(Serialize, Deserialize)]
struct CloneBootstrap
{
  /// Runtime → Clone requests (sent back to Main Zygote).
  requestTx: IpcSender<FFIRequest>,

  /// Clone → Runtime responses (sent back to Main Zygote).
  responseRx: IpcReceiver<FFIResponse>
}

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

/// macOS Transport: ipc-channel.
pub struct Transport;

/// Runtime-side handle to the Main Zygote.
pub struct ZygoteHandle
{
  /// Common handle (process handle + Drop).
  pub base: ZygoteHandleBase,
  
  /// Runtime → Main Zygote commands.
  pub commandTx: IpcSender<ZygoteCommand>,
  
  /// Main Zygote → Runtime replies.
  pub replyRx: IpcReceiver<ZygoteReply>
}

/// Runtime-side data endpoint.
pub struct RuntimeSide
{
  /// Runtime → Clone requests.
  pub requestTx: IpcSender<FFIRequest>,
  
  /// Clone → Runtime responses.
  pub responseRx: IpcReceiver<FFIResponse>
}

/// Clone-side data endpoint.
pub struct CloneSide
{
  /// Runtime → Clone requests.
  pub requestRx: IpcReceiver<FFIRequest>,
  
  /// Clone → Runtime responses.
  pub responseTx: IpcSender<FFIResponse>
}

/// Clone spawn result: pid and Runtime-side data channel ends.
#[derive(Serialize, Deserialize)]
pub struct Bootstrap
{
  /// PID of the freshly created clone.
  pub pid: u32,

  /// Runtime → Clone requests.
  pub requestTx: IpcSender<FFIRequest>,

  /// Clone → Runtime responses.
  pub responseRx: IpcReceiver<FFIResponse>
}

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

impl TransportTrait for Transport
{
  type RuntimeSide = RuntimeSide;
  type CloneSide = CloneSide;
  type Bootstrap = Bootstrap;
  type ZygoteHandle = ZygoteHandle;

  /// Short backend tag for diagnostics. Dispatched through the trait, so
  /// Clippy sees it as "never used" — silenced here.
  #[allow(dead_code)]
  fn name() -> &'static str
  {
    BackendName
  }

  /// Spawns the Main Zygote and bootstraps the control channel.
  fn spawnZygote() -> io::Result<Self::ZygoteHandle>
  {
    let (server, serverName): (
      IpcOneShotServer<BootstrapToRuntime>,
      String
    ) = IpcOneShotServer::new().map_err(io::Error::other)?;

    //
    let currentExe: PathBuf = env::current_exe()?;
    // todo Might fail if the path to the executable file
    //  is too long or there are no permissions?
    let process: Child = Command::new(currentExe)
      .arg(ZygoteFlag)
      .arg(&serverName)
      .stdin(Stdio::null())
      .stdout(Stdio::inherit())
      .stderr(Stdio::inherit())
      .spawn()?;

    // Zygote connects, sends BootstrapToRuntime { commandTx, replyRx }.
    let (_rx, bootstrap): (
      IpcReceiver<BootstrapToRuntime>,
      BootstrapToRuntime
    ) = server.accept().map_err(|e| {
      io::Error::other(format!("zygote bootstrap accept: {e}"))
    })?;

    Ok(ZygoteHandle {
      base: ZygoteHandleBase { process },
      commandTx: bootstrap.commandTx,
      replyRx: bootstrap.replyRx
    })
  }

  /// Runtime asks Main Zygote to fork a clone.
  fn sendSpawnClone(handle: &Self::ZygoteHandle) -> io::Result<Self::Bootstrap>
  {
    handle
      .commandTx
      .send(ZygoteCommand::SpawnClone)
      .map_err(|e| {
        io::Error::new(
          io::ErrorKind::BrokenPipe,
          format!("SpawnClone send failed: {e}")
        )
      })?;

    let reply: ZygoteReply = handle.replyRx.recv().map_err(|e| {
      io::Error::new(
        io::ErrorKind::BrokenPipe,
        format!("SpawnClone reply failed: {e}")
      )
    })?;

    match reply
    {
      ZygoteReply::Clone { pid, requestTx, responseRx } => Ok(Bootstrap {
        pid,
        requestTx,
        responseRx
      }),
      ZygoteReply::SpawnFailed => Err(io::Error::other(
        "Main zygote failed to create a clone (channel/fork failed)"
      ))
    }
  }

  /// PID stored in the bootstrap message.
  fn bootstrapPid(bootstrap: &Self::Bootstrap) -> u32
  {
    bootstrap.pid
  }

  /// Enters the Main Zygote command loop.
  ///
  /// `flag`: the `IpcOneShotServer` name passed as `argv[2]`.
  fn zygoteControlLoop(flag: Option<String>) -> !
  {
    let serverName: String =
      flag.expect("macos::zygoteControlLoop: missing IpcOneShotServer name");
    zygoteLoop(serverName)
  }

  /// In a freshly cloned process: prepares the data endpoint. Dispatched
  /// through the trait, so Clippy sees it as "never used" — silenced here.
  #[allow(dead_code)]
  fn cloneEnter(flag: Option<String>) -> io::Result<(Self::CloneSide, Self::Bootstrap)>
  {
    let serverName: String =
      flag.expect("macos::cloneEnter: missing IpcOneShotServer name");
    cloneBootstrapLoop(serverName)
  }

  /// Turns a bootstrap message into a Runtime-side data endpoint.
  fn runtimeConnect(bootstrap: Self::Bootstrap) -> io::Result<Self::RuntimeSide>
  {
    Ok(RuntimeSide {
      requestTx: bootstrap.requestTx,
      responseRx: bootstrap.responseRx
    })
  }
}

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

impl RuntimeSideTrait for RuntimeSide
{
  /// Sends an FFI request to the clone.
  fn send(&self, request: &FFIRequest) -> Result<(), String>
  {
    self
      .requestTx
      .send(request.clone())
      .map_err(|e| format!("Zygote clone IPC failed while sending request: {e}"))
  }

  /// Receives an FFI response from the clone.
  fn recv(&self) -> Result<FFIResponse, String>
  {
    self
      .responseRx
      .recv()
      .map_err(|e| format!("Zygote clone IPC failed while reading response: {e}"))
  }
}

impl CloneSideTrait for CloneSide
{
  /// Dispatched through the trait, so Clippy sees it as "never used" —
  /// silenced here.
  #[allow(dead_code)]
  fn run(self, cache: &mut FxHashMap<String, Library>) -> !
  {
    let Self { requestRx, responseTx } = self;
    let mut libraryCache: FxHashMap<String, Library> = std::mem::take(cache);

    loop
    {
      let request: FFIRequest = match requestRx.recv()
      {
        Ok(r) => r,
        Err(_) => std::process::exit(0)
      };

      let response: FFIResponse = handleRequest(request, &mut libraryCache);

      if responseTx.send(response).is_err() {
        std::process::exit(0);
      }
    }
  }
}

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

/// Handles an incoming request and performs an FFI operation using the library cache.
fn handleRequest(request: FFIRequest, cache: &mut FxHashMap<String, Library>) -> FFIResponse
{
  match executeFFI(request, cache)
  {
    Ok(v) => FFIResponse::Ok(v, takeLastErrno(), takeLastOsError()),
    Err(e) => FFIResponse::Err(e)
  }
}

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

/// Main zygote loop.
fn zygoteLoop(serverName: String) -> !
{
  low::ignoreChildExits();

  // Control channels: Runtime holds commandTx + replyRx;
  // Main Zygote holds commandRx + replyTx.
  let (commandTx, commandRx): (
    IpcSender<ZygoteCommand>,
    IpcReceiver<ZygoteCommand>
  ) = match ipc::channel::<ZygoteCommand>() {
    Ok(p) => p,
    Err(_) => std::process::exit(1)
  };
  let (replyTx, replyRx): (IpcSender<ZygoteReply>, IpcReceiver<ZygoteReply>) =
    match ipc::channel::<ZygoteReply>() {
      Ok(p) => p,
      Err(_) => std::process::exit(1)
    };

  // Connect to Runtime's one-shot server and hand over the ends Runtime needs.
  let bootstrapTx: IpcSender<BootstrapToRuntime> =
    match IpcSender::connect(serverName) {
      Ok(tx) => tx,
      Err(_) => std::process::exit(1)
    };
  if bootstrapTx
    .send(BootstrapToRuntime { commandTx, replyRx })
    .is_err()
  {
    std::process::exit(1);
  }
  drop(bootstrapTx);

  loop
  {
    let cmd: ZygoteCommand = match commandRx.recv() {
      Ok(c) => c,
      Err(_) => std::process::exit(0) // Runtime / control channel died
    };

    match cmd
    {
      ZygoteCommand::SpawnClone =>
      {
        let (cloneServer, cloneServerName): (
          IpcOneShotServer<CloneBootstrap>,
          String
        ) = match IpcOneShotServer::new() {
          Ok(s) => s,
          Err(_) => {
            let _ = replyTx.send(ZygoteReply::SpawnFailed);
            continue;
          }
        };

        let spawned: Option<u32> = match unsafe{ libc::fork() } {
          -1 => None,
          0 => {
            std::mem::forget(cloneServer);
            std::mem::forget(commandRx);
            std::mem::forget(replyTx);
            cloneBootstrapLoop(cloneServerName)
          }
          pid => Some(pid as u32)
        };

        let Some(pid) = spawned else {
          let _ = replyTx.send(ZygoteReply::SpawnFailed);
          continue;
        };

        let (_rx, bootstrap): (
          IpcReceiver<CloneBootstrap>,
          CloneBootstrap
        ) = match cloneServer.accept() {
          Ok(v) => v,
          Err(_) => {
            low::killProcess(pid);
            let _ = replyTx.send(ZygoteReply::SpawnFailed);
            continue;
          }
        };

        let _ = replyTx.send(ZygoteReply::Clone {
          pid,
          requestTx: bootstrap.requestTx,
          responseRx: bootstrap.responseRx
        });
      }
    }
  }
}

/// Bootstrap loop in a freshly forked clone.
fn cloneBootstrapLoop(serverName: String) -> !
{
  let (requestTx, requestRx): (
    IpcSender<FFIRequest>,
    IpcReceiver<FFIRequest>
  ) = match ipc::channel::<FFIRequest>() {
    Ok(p) => p,
    Err(_) => std::process::exit(1)
  };
  let (responseTx, responseRx): (
    IpcSender<FFIResponse>,
    IpcReceiver<FFIResponse>
  ) = match ipc::channel::<FFIResponse>() {
    Ok(p) => p,
    Err(_) => std::process::exit(1)
  };

  let bootstrapTx: IpcSender<CloneBootstrap> =
    match IpcSender::connect(serverName) {
      Ok(tx) => tx,
      Err(_) => std::process::exit(1)
    };
  if bootstrapTx
    .send(CloneBootstrap { requestTx, responseRx })
    .is_err()
  {
    std::process::exit(1);
  }
  drop(bootstrapTx);

  let cache: &mut FxHashMap<String, Library> =
    Box::leak(Box::new(FxHashMap::default()));
  CloneSide { requestRx, responseTx }.run(cache);
}

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