Skip to main content

litz_esp/
lib.rs

1//! ESP32-family chips.
2//!
3//! The adapter is generic over esp32sim's `Soc`: one `EspChip<S>` drives any chip
4//! that crate family models, so adding a chip is a type alias, a bus factory and
5//! a board manifest rather than a second copy of this file. ESP32-C3 is wired
6//! today; the Xtensa parts (ESP32, S3) and the remaining RISC-V parts (C6, P4,
7//! S31) follow the same shape.
8//!
9//! The mask ROM is not vendored here. Espressif publishes the ROM ELFs under
10//! Apache-2.0 at `espressif/esp-rom-elfs`; a chip loads one at runtime from a
11//! path or from an embedded blob the caller supplies, so the crate stays free
12//! of binaries and the licence question stays where Espressif put it.
13// The esp32sim backend is a `std` crate, so the no_std promise only holds
14// when that backend is off.
15#![cfg_attr(
16    not(any(
17        feature = "esp32",
18        feature = "esp32c3",
19        feature = "esp32c6",
20        feature = "esp32s3",
21        feature = "esp32p4",
22        feature = "esp32s31"
23    )),
24    no_std
25)]
26#![forbid(unsafe_code)]
27
28extern crate alloc;
29
30use litz_mcu::MemoryRegion;
31
32/// The simulated network behind an access point: DHCP/DNS/ICMP from esp32sim,
33/// TCP and UDP from Litz's own service table.
34#[cfg(any(
35    feature = "esp32",
36    feature = "esp32c3",
37    feature = "esp32c6",
38    feature = "esp32s3",
39    feature = "esp32p4",
40    feature = "esp32s31"
41))]
42pub mod router;
43
44// The debug surface, the display capture and the GDB stub are siblings of
45// `backend`: each needs the machine, which only the backend may hold, and each
46// gates itself on the chips it can serve.
47pub mod debug;
48pub mod gdb;
49pub mod screenshot;
50
51#[cfg(any(
52    feature = "esp32",
53    feature = "esp32c3",
54    feature = "esp32c6",
55    feature = "esp32s3",
56    feature = "esp32p4",
57    feature = "esp32s31"
58))]
59pub use litz_net::{NetworkConfig, Service};
60#[cfg(any(
61    feature = "esp32",
62    feature = "esp32c3",
63    feature = "esp32c6",
64    feature = "esp32s3",
65    feature = "esp32p4",
66    feature = "esp32s31"
67))]
68pub use router::EspRouter;
69
70/// Which chip a [`Config`] describes.
71#[derive(Clone, Copy, Debug, PartialEq, Eq)]
72pub enum Chip {
73    /// RV32IMC, 160 MHz, PLIC, no atomics.
74    Esp32C3,
75    /// RV32IMAC, 160 MHz, PLIC.
76    Esp32C6,
77    /// RV32IMAC, 96 MHz, PLIC, no radio.
78    Esp32H2,
79}
80
81/// External flash layout, in the order the ROM expects to find images.
82#[derive(Clone, Copy, Debug)]
83pub struct FlashLayout {
84    pub size: u32,
85    /// Offset of the second-stage bootloader.
86    pub bootloader_offset: u32,
87    /// Offset of the partition table.
88    pub partition_table_offset: u32,
89    /// Offset of the application image.
90    pub app_offset: u32,
91}
92
93impl Chip {
94    pub const fn memory_map(self) -> &'static [MemoryRegion] {
95        // Addresses are from the ESP32-C3/C6 technical reference manuals.
96        match self {
97            Chip::Esp32C3 | Chip::Esp32C6 | Chip::Esp32H2 => &PLIC_AND_RV_MAP,
98        }
99    }
100
101    pub const fn flash_layout(self) -> FlashLayout {
102        FlashLayout {
103            size: 4 * 1024 * 1024,
104            bootloader_offset: 0x0,
105            partition_table_offset: 0x8000,
106            app_offset: 0x1_0000,
107        }
108    }
109}
110
111/// Adapter over `esp32sim`'s ESP32-family machines.
112///
113/// This exists to answer one question with a build rather than an opinion:
114/// can a mature, MIT-licensed ESP32 emulator be driven as a library from
115/// outside its own repo? Everything above this module — diagrams, parts, the
116/// CI runner — only needs the [`litz_board::Chip`] calls, so the backend can be
117/// swapped for a vendored copy or an in-tree core later without touching them.
118#[cfg(any(
119    feature = "esp32",
120    feature = "esp32c3",
121    feature = "esp32c6",
122    feature = "esp32s3",
123    feature = "esp32p4",
124    feature = "esp32s31"
125))]
126pub mod backend {
127    use alloc::vec::Vec;
128    use core::cell::RefCell;
129    use std::cell::Cell;
130    use std::collections::BTreeMap;
131    use std::rc::Rc;
132
133    use esp_periph::i2c::I2cDevice as EspI2cDevice;
134    use esp_soc::ble::peer::Nearby;
135    use esp_soc::board::{BoardEdge, BoardModel, SpiPins};
136    use esp_soc::uart::{UartInput, UartRoute};
137    use esp_soc::{Machine, Soc, SocBus};
138    use litz_board::{Board as LitzBoard, Conflict};
139    use litz_core::{Drive, Level, PartState};
140
141    /// Builds a chip's bus with the Litz board already on it.
142    ///
143    /// Each esp32sim crate has its own `SocBus::new` signature — the S3 takes a
144    /// PSRAM size, the P4 a wafer revision, the S31 nothing — so the factory is
145    /// the one per-chip detail, and everything above it is generic. The cell
146    /// carries the GP-SPI clock the guest programmed, from an MMIO observer to
147    /// the board model that reconstructs the wires.
148    pub type BusFactory<S> = fn(
149        [u8; 6],
150        usize,
151        Option<Rc<RefCell<LitzBoard>>>,
152        u16,
153        Rc<Cell<[u32; 2]>>,
154    ) -> <S as Soc>::Bus;
155
156    /// An esp32sim machine attached to a Litz board.
157    pub struct EspChip<S: Soc> {
158        machine: Machine<S>,
159        board: Option<Rc<RefCell<LitzBoard>>>,
160        /// Kept so `with_board` can rebuild the machine; the bus owns the board
161        /// model and esp32sim has no setter after construction.
162        mac: [u8; 6],
163        flash: usize,
164        bus_for: BusFactory<S>,
165        /// A bootloader image was placed, so the machine starts from it
166        /// rather than from a direct `boot_app`.
167        bootloader_loaded: bool,
168        /// The analog values last written to the pads, so a run that changes
169        /// nothing does not reprogram the ADC every step.
170        analog: Vec<(u8, f32)>,
171        /// The firmware's ELF, when the project supplies one. esp32sim's HCI
172        /// Bluetooth controller is started by patching the guest's controller
173        /// task, so it needs the symbol table; the same symbols name addresses
174        /// in logs, disassembly and the debugger.
175        elf: Option<Vec<u8>>,
176        /// Serves a GDB client, when this chip's core is one the stub can
177        /// describe. The per-chip constructor installs it; the Xtensa parts
178        /// leave it empty, because their windowed register file needs a
179        /// different target description rather than a made-up one.
180        gdb: Option<GdbServeFn<S>>,
181        /// Calls a guest function on a core this adapter can drive, installed
182        /// by that chip's constructor: the flat RV32 register file, or a
183        /// windowed Xtensa `call8` with a saved core around it.
184        guest_call: Option<GuestCall<S>>,
185        /// Which development-board instance on the diagram these pads belong
186        /// to. A diagram with one board is board 0.
187        board_index: u16,
188        /// The chip's simulated time, shared with the network adapter so a
189        /// packet capture can timestamp the frames it records.
190        net_clock: Rc<Cell<u64>>,
191        /// The controller is on and its scan list came from the board, so a
192        /// runtime advertiser has to be mirrored on the next step.
193        ble_attached: bool,
194        /// The board's BLE generation the controller's scan list reflects.
195        ble_seen: u64,
196        /// The controller's scan list as this adapter last gave it, so a peer
197        /// added while the simulation runs can be appended to it.
198        ble_peers: Vec<litz_ble::Beacon>,
199        /// Whether the board supplies this chip. A chip with no board has no
200        /// switch to ask and is always powered.
201        powered: bool,
202        /// Simulated nanoseconds the board spent switched off. The machine's
203        /// clock does not run then, and the clock the runner watches must not
204        /// fall behind the board that is still on.
205        off_ns: u64,
206        /// Reads and writes the USB Serial/JTAG console on chips that have one.
207        /// A firmware built for USB CDC (CircuitPython, TinyUSB, HWCDC) prints
208        /// there and not on UART0, so the console has to follow both.
209        /// The GP-SPI clock registers a firmware write feeds to the board model.
210        spi_clock: Option<SpiClockSpec>,
211        /// The latest programmed rate per GP-SPI host (2 and 3), written by an
212        /// MMIO observer and read when a transfer reaches the board.
213        spi_rates: Rc<Cell<[u32; 2]>>,
214    }
215
216    /// Starts a GDB session over one chip.
217    pub type GdbServeFn<S> = fn(&mut EspChip<S>, u16) -> Result<(), String>;
218
219    /// Calls a guest function with no arguments and returns its result: `a0` on
220    /// RV32, and the windowed callee's `a2` on Xtensa (the caller's `a10` once
221    /// `retw` restores the register base).
222    pub type GuestCall<S> = fn(&mut EspChip<S>, u32) -> Result<u32, String>;
223
224    /// The entry a RISC-V chip's constructor installs. The stub is only compiled for the
225    /// RISC-V parts, so an Xtensa-only feature set must not reference it.
226    #[cfg(any(
227        feature = "esp32c3",
228        feature = "esp32c6",
229        feature = "esp32p4",
230        feature = "esp32s31"
231    ))]
232    fn serve_gdb<S: crate::debug::Rv32Chip>(
233        chip: &mut EspChip<S>,
234        port: u16,
235    ) -> Result<(), String> {
236        crate::gdb::serve(chip, port)
237    }
238
239    impl<S: Soc> EspChip<S> {
240        /// A chip with no board on it. Public to the crate's own constructors;
241        /// callers use the per-chip `new`.
242        fn bare(mac: [u8; 6], flash: usize, bus_for: BusFactory<S>) -> Self {
243            let spi_rates = Rc::new(Cell::new([0; 2]));
244            let machine = Self::build(mac, flash, bus_for, None, 0, Rc::clone(&spi_rates));
245            Self {
246                machine,
247                board: None,
248                mac,
249                flash,
250                bus_for,
251                bootloader_loaded: false,
252                analog: Vec::new(),
253                elf: None,
254                gdb: None,
255                guest_call: None,
256                board_index: 0,
257                powered: true,
258                off_ns: 0,
259                net_clock: Rc::new(Cell::new(0)),
260                ble_attached: false,
261                ble_seen: 0,
262                ble_peers: Vec::new(),
263                spi_clock: None,
264                spi_rates,
265            }
266        }
267
268        fn build(
269            mac: [u8; 6],
270            flash: usize,
271            bus_for: BusFactory<S>,
272            board: Option<Rc<RefCell<LitzBoard>>>,
273            index: u16,
274            spi_rates: Rc<Cell<[u32; 2]>>,
275        ) -> Machine<S> {
276            let mut machine = Machine::new(mac, bus_for(mac, flash, board, index, spi_rates));
277            // The scheduling batching knobs default from `ESP32SIM_VQ` /
278            // `ESP32SIM_BB` at construction; pin them to the plain one-quantum
279            // schedule, which is the bit-exact reference the batching is
280            // defined against. A simulator whose behaviour depends on the CI
281            // runner's environment cannot be a test gate, so the machine is
282            // built directly rather than through `esp32c3::machine`.
283            machine.vq_max = 1;
284            machine.bb_max = 1;
285            // The console prints to stdout unless captured; a library caller
286            // wants the bytes, not the side effect.
287            machine.console.capture = true;
288            machine
289        }
290
291        /// Attach a flattened board. Rebuilds the machine, so it must be called
292        /// before images are loaded (which is how every caller uses it).
293        pub fn with_board(self, board: LitzBoard) -> Self {
294            let shared = Rc::new(RefCell::new(board));
295            self.with_shared_board(shared, 0)
296        }
297
298        /// Attach a board another chip already shares, and say which board
299        /// instance these pads belong to.
300        ///
301        /// A diagram with more than one MCU has one [`LitzBoard`] and one chip
302        /// per development-board instance; the board is the same object, and
303        /// the index keeps two boards' GPIO 4 apart. The machine is rebuilt
304        /// here, which is why images are loaded after this call.
305        pub fn with_shared_board(mut self, board: Rc<RefCell<LitzBoard>>, index: u16) -> Self {
306            self.machine = Self::build(
307                self.mac,
308                self.flash,
309                self.bus_for,
310                Some(Rc::clone(&board)),
311                index,
312                Rc::clone(&self.spi_rates),
313            );
314            self.board = Some(board);
315            self.board_index = index;
316            // The rebuild replaces the machine, so the symbols and the clock
317            // observer go back on it. The bytes parsed when they were accepted,
318            // and parsing is pure.
319            if let Some(bytes) = &self.elf {
320                let _ = self.machine.add_symbols(bytes);
321            }
322            self.install_spi_observer();
323            self
324        }
325
326        /// Watch the GP-SPI clock registers, when this chip has them and a
327        /// board is attached.
328        ///
329        /// A firmware write is seen by an MMIO observer and stored in
330        /// `spi_rates`; the board model reports it at the transfer itself, so
331        /// the reconstructed wires use the divider the driver programmed
332        /// rather than the board's default. A chip with no board reconstructs
333        /// nothing, so it does not pay for an MMIO log. Installing twice is a
334        /// no-op.
335        fn install_spi_observer(&mut self) {
336            if self.board.is_none() {
337                return;
338            }
339            let Some(spec) = self.spi_clock else {
340                return;
341            };
342            if self.machine.has_observer("litz-spi-clock") {
343                return;
344            }
345            self.machine.add_observer(Box::new(SpiClockObserver {
346                rates: Rc::clone(&self.spi_rates),
347                spec,
348            }));
349        }
350
351        /// The machine, for the sibling modules that capture a display or
352        /// answer a debugger. Every esp32sim type still stays in this crate.
353        pub(crate) fn machine_ref(&self) -> &Machine<S> {
354            &self.machine
355        }
356
357        pub(crate) fn machine_mut(&mut self) -> &mut Machine<S> {
358            &mut self.machine
359        }
360
361        /// Serve one GDB client on `127.0.0.1:port`, returning when it
362        /// disconnects.
363        pub fn gdb_serve(&mut self, port: u16) -> Result<(), String> {
364            match self.gdb {
365                Some(serve) => serve(self, port),
366                None => Err(format!(
367                    "{} has no GDB target: only the RISC-V chips describe a register file",
368                    S::NAME
369                )),
370            }
371        }
372
373        /// Give the machine the firmware's symbol table.
374        ///
375        /// A project that has the ELF next to its image should always pass it:
376        /// the Bluetooth controller esp32sim runs is installed by patching the
377        /// guest's own controller task, which is only reachable by symbol, and
378        /// every log line, disassembly and breakpoint address benefits from
379        /// names. Call it after [`EspChip::with_board`], which rebuilds the
380        /// machine and would otherwise drop the symbols.
381        pub fn with_elf(mut self, bytes: &[u8]) -> Result<Self, String> {
382            self.machine.add_symbols(bytes)?;
383            self.elf = Some(bytes.to_vec());
384            Ok(self)
385        }
386
387        /// Whether a second-stage bootloader was loaded. With one, the boot
388        /// sequence is the bootloader's job and `boot` has nothing to start.
389        pub fn has_bootloader(&self) -> bool {
390            self.bootloader_loaded
391        }
392
393        pub fn board(&self) -> Option<&Rc<RefCell<LitzBoard>>> {
394            self.board.as_ref()
395        }
396
397        /// The esp32sim board callbacks, which route pins, SPI, UART and I2C
398        /// to the Litz board. A test can call the same entry points the chip
399        /// does without hand-programming a peripheral.
400        pub fn board_model(&mut self) -> &mut dyn BoardModel {
401            self.machine.bus.board()
402        }
403
404        pub fn state(&self, part: &str) -> Option<PartState> {
405            self.board.as_ref()?.borrow().state(part)
406        }
407
408        /// Press or release a named part. The board resolves it, so a LED
409        /// wired through the switch lights up as well; the chip only sees the
410        /// pin move if the circuit routes the switch to one.
411        pub fn press(&mut self, part: &str, pressed: bool) -> bool {
412            let Some(board) = self.board.as_ref() else {
413                return false;
414            };
415            let now = (self.machine.seconds() * 1e9) as u64;
416            board.borrow_mut().press(part, pressed, now)
417        }
418
419        /// Move a continuous control (a potentiometer's travel, in permille). The
420        /// board recomputes the wiper voltage; the pad is reprogrammed on the next
421        /// run, which is the first moment the firmware could read it anyway.
422        /// Make external PSRAM visible to the chip, in bytes.
423        pub fn set_psram_size(&mut self, bytes: usize) -> Result<(), String> {
424            self.machine.bus.set_psram_size(bytes)
425        }
426
427        pub fn set_control(&mut self, part: &str, permille: u16) -> bool {
428            let Some(board) = self.board.as_ref() else {
429                return false;
430            };
431            let now = (self.machine.seconds() * 1e9) as u64;
432            board.borrow_mut().set_control(part, permille, now)
433        }
434
435        /// Set a named control on a part, in the unit the scenario wrote.
436        pub fn set_named_control(&mut self, part: &str, name: &str, value: &str) -> bool {
437            let Some(board) = self.board.as_ref() else {
438                return false;
439            };
440            let now = (self.machine.seconds() * 1e9) as u64;
441            board.borrow_mut().set_named_control(part, name, value, now)
442        }
443
444        /// Bytes from the host into UART0's receive FIFO, as a terminal on the
445        /// chip's RX pin would send them.
446        pub fn write_serial(&mut self, bytes: &[u8]) {
447            self.machine.bus.uart_input(0, bytes);
448            *self.machine.bus.irq_dirty() = true;
449        }
450
451        /// Analog voltages the board holds on chip pins, for tests and a UI.
452        pub fn analog_inputs(&self) -> Vec<(u8, f32)> {
453            self.board
454                .as_ref()
455                .map(|b| b.borrow().analog_inputs_on(self.board_index))
456                .unwrap_or_default()
457        }
458
459        /// Push the board's analog levels to the pads that changed since the
460        /// last push.
461        ///
462        /// `Board::analog_inputs` is the one preference point: when the board's
463        /// analog co-simulation is on it returns the solved node voltage for an
464        /// analog pin, and when it is off it returns the part's static
465        /// `Part::analog` value exactly as before. The adapter therefore has no
466        /// second, chip-specific path to keep in sync.
467        fn publish_analog(&mut self) {
468            let Some(board) = self.board.as_ref() else {
469                return;
470            };
471            let now = board.borrow().analog_inputs();
472            for &(gpio, volts) in &now {
473                let unchanged = self
474                    .analog
475                    .iter()
476                    .any(|&(pin, v)| pin == gpio && v == volts);
477                if !unchanged {
478                    self.machine
479                        .bus
480                        .analog_set(gpio, esp_periph::AnalogSource::Const(volts));
481                }
482            }
483            self.analog = now;
484        }
485
486        /// The level on one pin of a named part. With no pin name, the level
487        /// the chip sees on the pin the part is wired to.
488        pub fn part_pin_level(&self, part: &str, pin: Option<&str>) -> Option<Level> {
489            let board = self.board.as_ref()?.borrow();
490            match pin {
491                Some(pin) => board.part_pin_level(part, pin),
492                None => board.chip_pin_level_on(self.board_index, part),
493            }
494        }
495
496        /// The level on one of this chip's own pads, by GPIO number.
497        pub fn gpio_level(&self, gpio: u8) -> Option<Level> {
498            let board = self.board.as_ref()?.borrow();
499            board.chip_level_on(self.board_index, gpio)
500        }
501
502        pub fn conflicts(&self) -> Vec<Conflict> {
503            self.board
504                .as_ref()
505                .map(|b| b.borrow().conflicts().to_vec())
506                .unwrap_or_default()
507        }
508
509        /// Load the mask ROM ELF (Apache-2.0, from `espressif/esp-rom-elfs`).
510        pub fn load_rom(&mut self, rom_elf: &[u8]) -> Result<(), String> {
511            self.machine.load_rom(rom_elf)
512        }
513
514        /// Write bytes at a flash offset (bootloader at 0x0, partition table at
515        /// 0x8000, application at 0x10000, matching the ESP-IDF layout).
516        pub fn write_flash(&mut self, offset: usize, data: &[u8]) -> Result<(), String> {
517            self.machine.write_flash(offset, data)
518        }
519
520        /// The flash array as the firmware left it, for a host that keeps what
521        /// the guest wrote (a settings partition, a filesystem, a boot count).
522        pub fn flash_image(&self) -> Option<&[u8]> {
523            self.machine.bus.flash_image()
524        }
525
526        /// Start the application at `app_off` the way the second-stage
527        /// bootloader would, for images that ship without a bootloader.
528        pub fn boot_app(&mut self, app_off: usize) -> Result<u32, String> {
529            self.machine.boot_app(app_off)
530        }
531
532        /// Schedule host actions (pressing a named pin, writing to a UART) at
533        /// simulated times. Times are seconds; the format is esp32sim's.
534        pub fn load_script(&mut self, text: &str) -> Result<(), String> {
535            self.machine.load_script(text)
536        }
537
538        /// Load an ELF's symbols so a fault or a trace names a function instead of
539        /// an address. The ROM ELF and the firmware ELF both work.
540        pub fn add_symbols(&mut self, elf: &[u8]) -> Result<(), String> {
541            self.machine.add_symbols(elf)
542        }
543
544        /// Stop the next run when the program counter reaches `pc`.
545        pub fn break_at(&mut self, pc: u32) {
546            self.machine
547                .add_observer(Box::new(esp_soc::observers::Breakpoints { pcs: vec![pc] }));
548        }
549
550        /// Registers of every core, as the debugger prints them.
551        pub fn registers(&self) -> String {
552            self.machine.dump_regs()
553        }
554
555        /// Record which code blocks execute, so a test can show what it
556        /// actually covered. Enabling twice is a no-op.
557        pub fn enable_coverage(&mut self) {
558            if !self.machine.has_observer("coverage") {
559                self.machine
560                    .add_observer(Box::new(esp_soc::observers::Coverage::new(None)));
561            }
562        }
563
564        /// The enabled observers' end-of-run reports, one line each.
565        pub fn reports(&mut self) -> Vec<String> {
566            self.machine.reports().lines().map(str::to_string).collect()
567        }
568
569        /// Disassemble `count` instructions at `addr`.
570        /// The address the firmware's symbol table gives `name`, when the
571        /// project supplied an ELF.
572        pub fn symbol_addr(&self, name: &str) -> Option<u32> {
573            self.machine.sym_addr(name)
574        }
575
576        /// Call a guest function with no arguments and return its result: `a0`
577        /// on RV32, and the windowed callee's `a2` on Xtensa (read from the
578        /// caller's `a10` after `retw` rotates the register window back).
579        ///
580        /// The call is transparent to the firmware: the core state and program
581        /// counter are saved and restored, and the function returns to the
582        /// instruction that was about to execute. The call is bounded, so a
583        /// function that never returns comes back as an error instead of hanging
584        /// the run.
585        pub fn call_guest(&mut self, address: u32) -> Result<u32, String> {
586            match self.guest_call {
587                Some(call) => call(self, address),
588                None => Err(format!(
589                    "{} does not install a guest-call trampoline",
590                    S::NAME
591                )),
592            }
593        }
594
595        /// The free heap the running firmware reports, by calling its own
596        /// `esp_get_free_heap_size` (or another IDF getter).
597        ///
598        /// This is a real sample: the function reads the guest's allocator.
599        /// It needs the ELF's symbols and a stopped or idle core.
600        pub fn sample_heap(&mut self) -> Result<u32, String> {
601            let names = [
602                "esp_get_free_heap_size",
603                "heap_caps_get_free_size",
604                "xPortGetFreeHeapSize",
605            ];
606            let (name, address) = names
607                .iter()
608                .find_map(|name| self.symbol_addr(name).map(|address| (*name, address)))
609                .ok_or_else(|| {
610                    "no heap getter symbol in the ELF (esp_get_free_heap_size, \
611                     heap_caps_get_free_size or xPortGetFreeHeapSize); supply `elf` in the project"
612                        .to_string()
613                })?;
614            self.call_guest(address)
615                .map_err(|error| format!("{name}: {error}"))
616        }
617
618        pub fn disassemble(&mut self, addr: u32, count: usize) -> String {
619            self.machine.disasm(addr, count)
620        }
621
622        /// Put a virtual access point on the air the chip's radio hears.
623        ///
624        /// `spec` is esp32sim's AP syntax (`ssid=...,psk=...,channel=...`). The
625        /// network behind it is the deterministic virtual one (DHCP, ARP, DNS,
626        /// NTP); no host socket is involved, so a test that uses Wi-Fi stays
627        /// repeatable. NAT to the host is deliberately not wired here.
628        pub fn attach_wifi(&mut self, spec: &str) -> Result<(), String> {
629            let ap = esp_soc::wifi::ApConfig::parse(spec)?;
630            self.machine.bus.attach_wifi(ap, None)
631        }
632
633        /// Put a whole simulated network on the air: the joinable access points,
634        /// the networks a scan should see, and a router that answers TCP and UDP
635        /// without a host socket.
636        ///
637        /// The router is installed as esp32sim's NAT transport, so the guest's
638        /// DHCP lease, gateway, DNS server and default route are the ones a real
639        /// access point hands out; only the far side of the gateway is Litz's,
640        /// and that side is `litz-net`, not anything ESP-specific.
641        pub fn attach_network(&mut self, config: &crate::NetworkConfig) -> Result<(), String> {
642            let specs: Vec<String> = config.access_points.iter().map(ap_spec).collect();
643            let aps = esp_soc::wifi::ApConfig::parse_all(&specs)?;
644            let nat = esp_soc::nat::Nat::with_transport(
645                false,
646                Box::new(crate::EspRouter::with_clock(
647                    config,
648                    Rc::clone(&self.net_clock),
649                )),
650            );
651            self.machine.bus.attach_wifi(aps[0].clone(), Some(nat))?;
652            for ap in &aps[1..] {
653                self.machine.bus.add_wifi_ap(ap.clone())?;
654            }
655            if !config.nearby.is_empty() {
656                let specs: Vec<String> = config.nearby.iter().map(nearby_spec).collect();
657                let beacons = esp_soc::wifi::BeaconAp::parse_all(&specs)?;
658                let left_out = self.machine.bus.wifi_nearby(beacons)?;
659                if let Some((beacon, why)) = left_out.first() {
660                    return Err(format!(
661                        "the network '{}' cannot be beside the access point: it shares {why}",
662                        beacon.ssid
663                    ));
664                }
665            }
666            Ok(())
667        }
668
669        /// Replace the simulated far side of the Wi-Fi gateway with host
670        /// sockets, so the guest reaches the real internet through the host.
671        ///
672        /// The access point and the DHCP lease stay the simulated ones; only
673        /// what is behind the gateway changes. This is opt-in and has no
674        /// deterministic bytes: a run that uses it depends on the host network.
675        #[cfg(not(target_arch = "wasm32"))]
676        pub fn attach_host_nat(&mut self, local_ntp: bool) -> Result<(), String> {
677            self.machine
678                .bus
679                .attach_nat(Some(esp_soc::nat::Nat::new(false)), local_ntp)
680        }
681
682        /// Put host sockets behind the gateway and forward these host ports
683        /// into the guest: `tcp:[host:]port-[guest:]port`, the same syntax
684        /// esp32sim uses. Returns one line per forward describing where it
685        /// listens.
686        #[cfg(not(target_arch = "wasm32"))]
687        pub fn attach_host_forwards(
688            &mut self,
689            forwards: &[String],
690            local_ntp: bool,
691        ) -> Result<Vec<String>, String> {
692            let mut transport = esp_soc::nat::StdTransport::new();
693            let mut lines = Vec::new();
694            for spec in forwards {
695                let forward = esp_soc::nat::HostFwdSpec::parse(spec)?;
696                let at = transport
697                    .listen(&forward)
698                    .map_err(|e| format!("host forward {spec:?}: {e}"))?;
699                lines.push(format!("{spec} -> {at}"));
700            }
701            let mut nat = esp_soc::nat::Nat::with_transport(false, Box::new(transport));
702            nat.hostfwd = forwards.len() as u64;
703            self.machine.bus.attach_nat(Some(nat), local_ntp)?;
704            Ok(lines)
705        }
706
707        /// Record the Ethernet frames the station's MAC carries, both ways,
708        /// for a pcap. Independent of the virtual network's own capture.
709        pub fn set_net_tap(&mut self, tap: esp_soc::netcap::NetTap) -> Result<(), String> {
710            self.machine.bus.set_net_tap(tap)
711        }
712
713        /// Record every 802.11 frame the air carries into a pcap with link
714        /// type 105, written as the run goes.
715        pub fn start_air_capture(&mut self, path: &std::path::Path) -> Result<(), String> {
716            let file =
717                std::fs::File::create(path).map_err(|e| format!("{}: {e}", path.display()))?;
718            let capture =
719                std::sync::Arc::new(std::sync::Mutex::new(esp_soc::netcap::AirCapture::default()));
720            capture
721                .lock()
722                .map_err(|_| "the air capture lock is poisoned".to_string())?
723                .set_pcap(Box::new(file))
724                .map_err(|e| format!("{}: {e}", path.display()))?;
725            self.machine
726                .bus
727                .set_air_tap(Some(capture))
728                .map_err(|e| format!("802.11 capture: {e}"))
729        }
730
731        /// Record the Ethernet frames the station's MAC actually carried into
732        /// a pcap with link type 1, written as the run goes.
733        pub fn start_ethernet_capture(&mut self, path: &std::path::Path) -> Result<(), String> {
734            let file =
735                std::fs::File::create(path).map_err(|e| format!("{}: {e}", path.display()))?;
736            let capture =
737                std::sync::Arc::new(std::sync::Mutex::new(esp_soc::netcap::NetCapture::default()));
738            capture
739                .lock()
740                .map_err(|_| "the Ethernet capture lock is poisoned".to_string())?
741                .set_pcap(Box::new(file))
742                .map_err(|e| format!("{}: {e}", path.display()))?;
743            self.machine
744                .bus
745                .set_net_tap(capture)
746                .map_err(|e| format!("Ethernet capture: {e}"))
747        }
748
749        /// Replace the simulated network with a raw Ethernet seam: the guest's
750        /// frames come out of [`take_ethernet_frames`](Self::take_ethernet_frames)
751        /// and the host's go back in through
752        /// [`receive_ethernet_frame`](Self::receive_ethernet_frame).
753        pub fn set_ethernet_relay(&mut self, enabled: bool) -> Result<(), String> {
754            self.machine.bus.set_ethernet_relay(enabled)
755        }
756
757        /// Complete Ethernet frames (no FCS) in transmit order since the last
758        /// call. Empty outside relay mode.
759        pub fn take_ethernet_frames(&mut self) -> Vec<Vec<u8>> {
760            self.machine.bus.take_ethernet_frames()
761        }
762
763        /// Queue one 14..=1518-byte Ethernet frame (no FCS) for the guest.
764        pub fn receive_ethernet_frame(&mut self, frame: &[u8]) -> Result<(), String> {
765            self.machine.bus.receive_ethernet_frame(frame)
766        }
767
768        /// Put the circuit's Bluetooth advertisers on the air the chip's LE
769        /// controller hears.
770        ///
771        /// The ESP32-C3's link controller is derived from its mask ROM, so it
772        /// needs no ELF and can be installed here with `enable_ble_full(false)`.
773        /// The S3, C6 and classic ESP32 controllers are package images carried
774        /// inside the firmware ELF; Litz has no ELF plumbing for them, so those
775        /// chips answer with an error naming themselves rather than start a
776        /// controller that cannot scan.
777        ///
778        /// The beacons are translated straight into esp32sim's `Nearby` structs:
779        /// the part attributes have already been validated by the board, so the
780        /// string syntax `--ble-nearby` uses would only parse them a second time.
781        pub fn attach_ble(&mut self, config: &litz_ble::BleConfig) -> Result<(), String> {
782            if config.is_empty() {
783                return Ok(());
784            }
785            // The list the controller hears is the circuit's, and it is not
786            // fixed for the run: a runtime advertiser changes it. Remember the
787            // generation the controller was given so a step can notice.
788            self.ble_seen = self
789                .board
790                .as_ref()
791                .map(|board| board.borrow().ble_generation())
792                .unwrap_or(0);
793            self.ble_attached = false;
794            // The advertisers reach a scanning guest through esp32sim's HCI
795            // controller, which is started by patching the guest's own
796            // controller task — an entry the machine can only find by symbol.
797            // The ROM-derived controller (`enable_ble_full`) is a different
798            // object and deliberately refuses the connection: sending the
799            // beacons to it would look like success and put nothing on the
800            // air, so the missing ELF is reported instead.
801            let Some(bytes) = self.elf.clone() else {
802                return Err(format!(
803                    "{} needs the firmware ELF to scan for a beacon: set [sim] elf, \
804                     because the Bluetooth controller is started through the guest's \
805                     symbol table",
806                    S::NAME
807                ));
808            };
809            let elf = esp_soc::elf::parse(&bytes)?;
810            self.machine
811                .bus
812                .enable_ble(&elf)
813                .map_err(|why| format!("{} cannot carry BLE beacons: {why}", S::NAME))?;
814            let beacons = nearby_list(&config.beacons);
815            self.machine.bus.ble_nearby(beacons)?;
816            self.ble_peers = config.beacons.clone();
817            self.ble_attached = true;
818            Ok(())
819        }
820
821        /// Replace the devices the controller's scan reports while it runs.
822        ///
823        /// esp32sim hands the list to the controller, and a scan in progress
824        /// hears the new one at once, so this is the runtime half of
825        /// [`EspChip::attach_ble`]. Litz calls it from `run` whenever a custom
826        /// chip starts or stops advertising, which is what makes a runtime
827        /// advertiser visible to a native ESP32 rather than only to another
828        /// wasm chip.
829        pub fn set_ble_nearby(&mut self, config: &litz_ble::BleConfig) -> Result<(), String> {
830            if !self.ble_attached {
831                return Err("BLE is not enabled on this chip".into());
832            }
833            self.machine.bus.ble_nearby(nearby_list(&config.beacons))?;
834            self.ble_peers = config.beacons.clone();
835            self.ble_seen = self
836                .board
837                .as_ref()
838                .map(|board| board.borrow().ble_generation())
839                .unwrap_or(0);
840            Ok(())
841        }
842
843        /// Add one advertiser to the controller's scan list while it runs.
844        ///
845        /// esp32sim replaces its peer list wholesale, and a scan in progress
846        /// reports the new list at once, so the list this adapter was given is
847        /// the thing to append to. The method is inherent rather than on
848        /// [`litz_board::Chip`]: that trait is the runner's seam and has no
849        /// per-advertiser BLE entry point.
850        pub fn add_ble_peer(&mut self, beacon: &litz_ble::Beacon) -> Result<(), String> {
851            if !self.ble_attached {
852                return Err("BLE is not enabled on this chip".into());
853            }
854            self.ble_peers.push(beacon.clone());
855            let peers = nearby_list(&self.ble_peers);
856            if let Err(error) = self.machine.bus.ble_nearby(peers) {
857                self.ble_peers.pop();
858                return Err(error);
859            }
860            self.ble_seen = self
861                .board
862                .as_ref()
863                .map(|board| board.borrow().ble_generation())
864                .unwrap_or(0);
865            Ok(())
866        }
867
868        /// Drive the virtual central the controller's peer link exposes:
869        /// `connect`, `discover`, `read <handle>`, `write <handle> <hex>`,
870        /// `disconnect` or `central-stop`.
871        ///
872        /// The commands are the ones a phone would send to the guest's
873        /// peripheral, so a test can exercise the guest's GATT server and its
874        /// connection events without a second chip. The full link controller
875        /// (C3) models the 30 ms connection interval, channel hopping and ATT
876        /// transactions; the ROM-derived HCI controller answers with the
877        /// smaller command set and says so.
878        pub fn ble_command(&mut self, command: &str) -> Result<(), String> {
879            self.machine.bus.ble_command(command)
880        }
881
882        /// How many virtual-central commands have not completed yet.
883        pub fn ble_pending_commands(&self) -> usize {
884            self.machine.bus.ble_pending_commands()
885        }
886
887        /// The oldest kept `[ble]` line, without its prefix.
888        pub fn ble_log(&mut self) -> Option<String> {
889            self.machine.bus.ble_log_take()
890        }
891
892        /// Start the full C3 link controller, which models connection events,
893        /// the 30 ms interval and gap timing rather than only advertising and
894        /// scanning. `observe` keeps its `[ble-*]` lines for [`EspChip::ble_log`].
895        pub fn enable_full_ble(&mut self, observe: bool) -> Result<(), String> {
896            self.machine.bus.enable_ble_full(observe)
897        }
898
899        /// Simulated seconds since reset, including time spent switched off.
900        pub fn seconds(&self) -> f64 {
901            self.machine.seconds() + self.off_ns as f64 / 1e9
902        }
903
904        /// Whether the board supplies this chip.
905        pub fn board_power(&self) -> bool {
906            match &self.board {
907                Some(board) => board.borrow().board_powered(self.board_index),
908                None => true,
909            }
910        }
911
912        /// Start the firmware the way a power-on does: the bootloader path
913        /// re-enters the ROM, a direct image is entered at its app offset.
914        fn boot_after_power(&mut self) -> Result<u32, String> {
915            if self.bootloader_loaded {
916                self.machine.reboot();
917                Ok(0)
918            } else {
919                let app = litz_board::Chip::info(self).flash.app as usize;
920                self.boot_app(app)
921            }
922        }
923
924        /// The chip lost power: stop driving the board's lines.
925        fn power_off(&mut self) {
926            self.powered = false;
927            if let Some(board) = &self.board {
928                let now = (self.seconds() * 1e9) as u64;
929                board
930                    .borrow_mut()
931                    .release_chip_outputs(self.board_index, now);
932            }
933        }
934
935        /// Run at most `steps` scheduling steps; the stop condition says why it ended.
936        pub fn run(&mut self, steps: u64) -> esp_soc::Stop {
937            // An ADC conversion inside the run must see the voltage the knob
938            // holds now, so the pads are refreshed before any instruction runs.
939            self.publish_analog();
940            // A capture timestamps network answers with the board's clock.
941            if let Some(board) = &self.board {
942                let now = board.borrow().now();
943                self.net_clock.set(now);
944                // A wasm chip on the same board may have started or stopped
945                // advertising since the last step. Mirror the air only when it
946                // changed: the list reaches a scan in progress at once.
947                if self.ble_attached {
948                    let (generation, air) = {
949                        let board = board.borrow();
950                        (board.ble_generation(), board.ble_air(self.board_index))
951                    };
952                    if generation != self.ble_seen {
953                        self.ble_seen = generation;
954                        let _ = self.machine.bus.ble_nearby(nearby_list(&air));
955                        self.ble_peers = air;
956                    }
957                }
958            }
959            self.machine.run(steps)
960        }
961
962        pub fn uart0(&self) -> &[u8] {
963            &self.machine.console.uart0
964        }
965
966        pub fn take_uart0(&mut self) -> Vec<u8> {
967            core::mem::take(&mut self.machine.console.uart0)
968        }
969    }
970
971    /// esp32sim's access-point syntax, built from the chip-independent
972    /// description so the parsing, validation and BSSID derivation stay in one
973    /// place (esp32sim's own).
974    fn ap_spec(ap: &litz_net::AccessPoint) -> String {
975        let mut spec = format!("ssid={},channel={}", ap.ssid, ap.channel);
976        if let Some(psk) = &ap.psk {
977            spec.push_str(&format!(",psk={psk}"));
978        }
979        if let Some(bssid) = ap.bssid {
980            spec.push_str(&format!(
981                ",bssid={}",
982                bssid
983                    .iter()
984                    .map(|b| format!("{b:02x}"))
985                    .collect::<Vec<_>>()
986                    .join(":")
987            ));
988        }
989        if let Some(epoch) = ap.epoch_s {
990            spec.push_str(&format!(",epoch={epoch}"));
991        }
992        spec
993    }
994
995    /// The controller's view of a set of advertisers, including the GATT
996    /// table a central discovers after connecting.
997    fn nearby_list(beacons: &[litz_ble::Beacon]) -> Vec<Nearby> {
998        beacons
999            .iter()
1000            .map(|beacon| Nearby {
1001                addr: beacon.address,
1002                addr_type: beacon.address_type(),
1003                rssi: beacon.rssi,
1004                adv: beacon.adv.clone(),
1005                scan_response: beacon.scan_response.clone(),
1006                gatt: beacon
1007                    .gatt
1008                    .iter()
1009                    .map(|service| esp_soc::ble::peer::GattService {
1010                        uuid: service.uuid,
1011                        characteristics: service
1012                            .characteristics
1013                            .iter()
1014                            .map(|characteristic| esp_soc::ble::peer::GattCharacteristic {
1015                                uuid: characteristic.uuid,
1016                                flags: characteristic.flags,
1017                                value: characteristic.value.clone(),
1018                            })
1019                            .collect(),
1020                    })
1021                    .collect(),
1022            })
1023            .collect()
1024    }
1025
1026    fn nearby_spec(network: &litz_net::NearbyNetwork) -> String {
1027        format!(
1028            "ssid={},channel={},rssi={},secure={}",
1029            network.ssid,
1030            network.channel,
1031            network.rssi,
1032            u8::from(network.secure)
1033        )
1034    }
1035
1036    /// The ESP32-C3. Kept as a named alias so callers keep writing `C3`.
1037    #[cfg(feature = "esp32c3")]
1038    pub type C3 = EspChip<esp32c3::C3>;
1039
1040    #[cfg(feature = "esp32c3")]
1041    impl EspChip<esp32c3::C3> {
1042        pub fn new(mac: [u8; 6], flash_size: usize) -> Self {
1043            let mut chip = Self::bare(mac, flash_size, c3_bus);
1044            chip.gdb = Some(serve_gdb::<esp32c3::C3>);
1045            chip.guest_call = Some(crate::debug::rv32_call_guest::<esp32c3::C3>);
1046            chip
1047        }
1048    }
1049
1050    #[cfg(feature = "esp32c3")]
1051    fn c3_bus(
1052        mac: [u8; 6],
1053        flash: usize,
1054        board: Option<Rc<RefCell<LitzBoard>>>,
1055        index: u16,
1056        spi_rates: Rc<Cell<[u32; 2]>>,
1057    ) -> esp32c3::bus::SocBus {
1058        const CPU_HZ: u64 = esp32c3::periph::CPU_HZ;
1059        let mut bus = esp32c3::bus::SocBus::new(flash, mac);
1060        if let Some(board) = board {
1061            bus.board = Box::new(LitzModel::new(board, CPU_HZ, index, spi_rates));
1062            // The bus caches which callbacks the board wants and reconnects the
1063            // board's current input levels; both happen here.
1064            bus.attach_board_devices();
1065        }
1066        bus
1067    }
1068
1069    /// The ESP32-C6: the same adapter over the second RISC-V chip.
1070    #[cfg(feature = "esp32c6")]
1071    pub type C6 = EspChip<esp32c6::C6>;
1072
1073    #[cfg(feature = "esp32c6")]
1074    impl EspChip<esp32c6::C6> {
1075        pub fn new(mac: [u8; 6], flash_size: usize) -> Self {
1076            let mut chip = Self::bare(mac, flash_size, c6_bus);
1077            chip.gdb = Some(serve_gdb::<esp32c6::C6>);
1078            chip.guest_call = Some(crate::debug::rv32_call_guest::<esp32c6::C6>);
1079            chip
1080        }
1081    }
1082
1083    #[cfg(feature = "esp32c6")]
1084    fn c6_bus(
1085        mac: [u8; 6],
1086        flash: usize,
1087        board: Option<Rc<RefCell<LitzBoard>>>,
1088        index: u16,
1089        spi_rates: Rc<Cell<[u32; 2]>>,
1090    ) -> esp32c6::bus::SocBus {
1091        const CPU_HZ: u64 = esp32c6::periph::CPU_HZ;
1092        let mut bus = esp32c6::bus::SocBus::new(flash, mac);
1093        if let Some(board) = board {
1094            bus.board = Box::new(LitzModel::new(board, CPU_HZ, index, spi_rates));
1095            bus.attach_board_devices();
1096        }
1097        bus
1098    }
1099
1100    /// The classic ESP32 (Xtensa LX6, two cores).
1101    #[cfg(feature = "esp32")]
1102    pub type Esp32 = EspChip<esp32::Esp32>;
1103
1104    #[cfg(feature = "esp32")]
1105    impl EspChip<esp32::Esp32> {
1106        pub fn new(mac: [u8; 6], flash_size: usize) -> Self {
1107            let mut chip = Self::bare(mac, flash_size, esp32_bus);
1108            chip.guest_call = Some(crate::debug::XtensaChip::call_guest);
1109            chip.spi_clock = Some(ESP32_SPI_CLOCKS);
1110            chip
1111        }
1112    }
1113
1114    #[cfg(feature = "esp32")]
1115    fn esp32_bus(
1116        mac: [u8; 6],
1117        flash: usize,
1118        board: Option<Rc<RefCell<LitzBoard>>>,
1119        index: u16,
1120        spi_rates: Rc<Cell<[u32; 2]>>,
1121    ) -> esp32::bus::SocBus {
1122        const CPU_HZ: u64 = esp32::periph::CPU_HZ;
1123        let mut bus = esp32::bus::SocBus::new(flash, mac);
1124        if let Some(board) = board {
1125            bus.board = Box::new(LitzModel::new(board, CPU_HZ, index, spi_rates));
1126            bus.attach_board_devices();
1127        }
1128        bus
1129    }
1130
1131    /// PSRAM the S3 adapter hands the bus. A board manifest does not carry a
1132    /// PSRAM size yet; the DevKitC-1 has 2 MiB and the chips tolerate more.
1133    #[cfg(feature = "esp32s3")]
1134    const S3_PSRAM: usize = 2 << 20;
1135
1136    /// The ESP32-S3 (Xtensa LX7).
1137    #[cfg(feature = "esp32s3")]
1138    pub type S3 = EspChip<esp32s3::S3>;
1139
1140    #[cfg(feature = "esp32s3")]
1141    impl EspChip<esp32s3::S3> {
1142        pub fn new(mac: [u8; 6], flash_size: usize) -> Self {
1143            let mut chip = Self::bare(mac, flash_size, s3_bus);
1144            chip.guest_call = Some(crate::debug::XtensaChip::call_guest);
1145            chip.spi_clock = Some(S3_SPI_CLOCKS);
1146            chip
1147        }
1148    }
1149
1150    #[cfg(feature = "esp32s3")]
1151    fn s3_bus(
1152        mac: [u8; 6],
1153        flash: usize,
1154        board: Option<Rc<RefCell<LitzBoard>>>,
1155        index: u16,
1156        spi_rates: Rc<Cell<[u32; 2]>>,
1157    ) -> esp32s3::bus::SocBus {
1158        const CPU_HZ: u64 = esp32s3::periph::CPU_HZ;
1159        let mut bus = esp32s3::bus::SocBus::new(flash, S3_PSRAM, mac);
1160        if let Some(board) = board {
1161            bus.board = Box::new(LitzModel::new(board, CPU_HZ, index, spi_rates));
1162            bus.attach_board_devices();
1163        }
1164        bus
1165    }
1166
1167    /// The ESP32-P4 in its pre-rev-3 wafer, which is what `esp32p4::machine`
1168    /// builds. A rev-3 board can add a sibling alias over `P4Rev3`.
1169    #[cfg(feature = "esp32p4")]
1170    pub type P4 = EspChip<esp32p4::P4>;
1171
1172    #[cfg(feature = "esp32p4")]
1173    impl EspChip<esp32p4::P4> {
1174        pub fn new(mac: [u8; 6], flash_size: usize) -> Self {
1175            let mut chip = Self::bare(mac, flash_size, p4_bus);
1176            chip.gdb = Some(serve_gdb::<esp32p4::P4>);
1177            chip.guest_call = Some(crate::debug::rv32_call_guest::<esp32p4::P4>);
1178            chip
1179        }
1180    }
1181
1182    #[cfg(feature = "esp32p4")]
1183    fn p4_bus(
1184        mac: [u8; 6],
1185        flash: usize,
1186        board: Option<Rc<RefCell<LitzBoard>>>,
1187        index: u16,
1188        spi_rates: Rc<Cell<[u32; 2]>>,
1189    ) -> esp32p4::bus::SocBus {
1190        const CPU_HZ: u64 = esp32p4::periph::CPU_HZ;
1191        let wafer = <esp32p4::RevLt3 as esp32p4::Revision>::WAFER;
1192        let mut bus = esp32p4::bus::SocBus::new(flash, mac, wafer);
1193        if let Some(board) = board {
1194            bus.board = Box::new(LitzModel::new(board, CPU_HZ, index, spi_rates));
1195            bus.attach_board_devices();
1196        }
1197        bus
1198    }
1199
1200    /// The ESP32-S31.
1201    #[cfg(feature = "esp32s31")]
1202    pub type S31 = EspChip<esp32s31::S31>;
1203
1204    #[cfg(feature = "esp32s31")]
1205    impl EspChip<esp32s31::S31> {
1206        pub fn new(mac: [u8; 6], flash_size: usize) -> Self {
1207            let mut chip = Self::bare(mac, flash_size, s31_bus);
1208            chip.gdb = Some(serve_gdb::<esp32s31::S31>);
1209            chip.guest_call = Some(crate::debug::rv32_call_guest::<esp32s31::S31>);
1210            chip
1211        }
1212    }
1213
1214    #[cfg(feature = "esp32s31")]
1215    fn s31_bus(
1216        mac: [u8; 6],
1217        flash: usize,
1218        board: Option<Rc<RefCell<LitzBoard>>>,
1219        index: u16,
1220        spi_rates: Rc<Cell<[u32; 2]>>,
1221    ) -> esp32s31::SocBus {
1222        const CPU_HZ: u64 = esp32s31::periph::CPU_HZ;
1223        let mut bus = esp32s31::SocBus::new(flash, mac);
1224        if let Some(board) = board {
1225            bus.board = Box::new(LitzModel::new(board, CPU_HZ, index, spi_rates));
1226            bus.attach_board_devices();
1227        }
1228        bus
1229    }
1230
1231    /// One I2C target, as esp32sim's controller sees it.
1232    ///
1233    /// The device itself stays in `Board::buses`; this handle holds the shared
1234    /// board and an address, so handing it to esp32sim does not move the
1235    /// device out of the board and the board stays usable by tests and the
1236    /// host. Every callback borrows the board for the length of one byte.
1237    struct BoardI2cDevice {
1238        board: Rc<RefCell<LitzBoard>>,
1239        /// The board instance whose controller this is; two boards' `i2c0`
1240        /// are different buses.
1241        board_index: u16,
1242        controller: u8,
1243        address: u8,
1244        /// The phases of the transaction in flight, so the pins can be
1245        /// reconstructed when the STOP arrives. `esp32sim` reports one byte
1246        /// at a time and has no timestamp of its own.
1247        written: Vec<u8>,
1248        received: Vec<u8>,
1249        reading: bool,
1250        open: bool,
1251        /// Where the last observed transaction ended, so back-to-back
1252        /// transactions do not stack at one tick when the board never settled
1253        /// a pin between them.
1254        last_at: u64,
1255        /// When the firmware's controller started this transaction. The
1256        /// elapsed time is the configured SCL rate, which is what the
1257        /// reconstructed edges use.
1258        started_at: u64,
1259    }
1260
1261    impl EspI2cDevice for BoardI2cDevice {
1262        fn address(&self, _configured: u8) -> u8 {
1263            self.address
1264        }
1265
1266        fn start(&mut self, read: bool) -> bool {
1267            if !self.open {
1268                self.written.clear();
1269                self.received.clear();
1270                self.open = true;
1271                self.started_at = self.board.borrow().now();
1272            }
1273            self.reading = read;
1274            let mut board = self.board.borrow_mut();
1275            let Some(bus) = board
1276                .buses_mut()
1277                .i2c
1278                .get_mut(&(self.board_index, self.controller))
1279            else {
1280                return false;
1281            };
1282            let Some(device) = bus.device_mut(self.address) else {
1283                return false;
1284            };
1285            device.connect(read);
1286            true
1287        }
1288
1289        fn write(&mut self, byte: u8) -> bool {
1290            if !self.reading {
1291                self.written.push(byte);
1292            }
1293            let mut board = self.board.borrow_mut();
1294            let Some(bus) = board
1295                .buses_mut()
1296                .i2c
1297                .get_mut(&(self.board_index, self.controller))
1298            else {
1299                return false;
1300            };
1301            let Some(device) = bus.device_mut(self.address) else {
1302                return false;
1303            };
1304            device.write(byte)
1305        }
1306
1307        fn read(&mut self) -> u8 {
1308            let byte = {
1309                let mut board = self.board.borrow_mut();
1310                let Some(bus) = board
1311                    .buses_mut()
1312                    .i2c
1313                    .get_mut(&(self.board_index, self.controller))
1314                else {
1315                    return 0xff;
1316                };
1317                let Some(device) = bus.device_mut(self.address) else {
1318                    return 0xff;
1319                };
1320                device.read()
1321            };
1322            self.received.push(byte);
1323            byte
1324        }
1325
1326        fn stop(&mut self) {
1327            {
1328                let mut board = self.board.borrow_mut();
1329                let Some(bus) = board
1330                    .buses_mut()
1331                    .i2c
1332                    .get_mut(&(self.board_index, self.controller))
1333                else {
1334                    return;
1335                };
1336                if let Some(device) = bus.device_mut(self.address) {
1337                    device.stop();
1338                }
1339            }
1340            if self.open {
1341                let mut board = self.board.borrow_mut();
1342                let end = board.now();
1343                let at = self.started_at.max(self.last_at);
1344                let phases = 1
1345                    + self.written.len()
1346                    + if self.received.is_empty() {
1347                        0
1348                    } else {
1349                        1 + self.received.len()
1350                    };
1351                // The controller clocks each phase at the divider the firmware
1352                // programmed, so the transaction's own duration is the SCL
1353                // rate. Falling back to the last known rate keeps a
1354                // zero-duration model (a callback-only device) usable.
1355                let elapsed = end.saturating_sub(self.started_at);
1356                let hz = if elapsed > 0 {
1357                    (phases as u128 * 9 * 1_000_000_000 / u128::from(elapsed))
1358                        .clamp(1_000, 5_000_000) as u32
1359                } else {
1360                    board.i2c_hz(self.board_index, self.controller)
1361                };
1362                board.set_i2c_hz(self.board_index, self.controller, hz);
1363                board.observe_i2c(
1364                    self.board_index,
1365                    self.controller,
1366                    self.address,
1367                    &self.written,
1368                    &self.received,
1369                    at,
1370                );
1371                let period = 1_000_000_000 / u64::from(hz);
1372                self.last_at = (at + phases as u64 * 9 * period).max(end);
1373            }
1374            self.open = false;
1375            self.reading = false;
1376        }
1377    }
1378
1379    /// Where one chip keeps its GP-SPI clock dividers.
1380    ///
1381    /// The two Xtensa parts encode the same `APB / ((pre+1) * (n+1))` divider
1382    /// at the same bit positions, but the register offset and the width of the
1383    /// pre-divider differ: the classic ESP32 has 0x18 and 13 bits, the S3 0xC
1384    /// and 4 bits.
1385    #[derive(Clone, Copy)]
1386    struct SpiClockSpec {
1387        /// `(clock register, pre-divider shift, pre-divider mask)` for hosts 2 and 3.
1388        ports: [(u32, u32, u32); 2],
1389    }
1390
1391    #[cfg(feature = "esp32")]
1392    const ESP32_SPI_CLOCKS: SpiClockSpec = SpiClockSpec {
1393        ports: [(0x3ff6_4018, 18, 0x1fff), (0x3ff6_5018, 18, 0x1fff)],
1394    };
1395
1396    #[cfg(feature = "esp32s3")]
1397    const S3_SPI_CLOCKS: SpiClockSpec = SpiClockSpec {
1398        ports: [(0x6002_400c, 18, 0xf), (0x6002_500c, 18, 0xf)],
1399    };
1400
1401    /// Turns a firmware's GP-SPI clock-register write into the rate the board
1402    /// model reports for the next transfer.
1403    ///
1404    /// esp32sim's `spi_transfer` callback carries bytes, not a clock, so the
1405    /// programmed divider has to travel beside it. Watching MMIO is exact and
1406    /// cheap: only a register write ever changes the rate.
1407    struct SpiClockObserver {
1408        rates: Rc<Cell<[u32; 2]>>,
1409        spec: SpiClockSpec,
1410    }
1411
1412    impl<S: Soc> esp_soc::Observer<S> for SpiClockObserver {
1413        fn name(&self) -> &'static str {
1414            "litz-spi-clock"
1415        }
1416
1417        fn wants(&self) -> esp_soc::Wants {
1418            esp_soc::Wants::MMIO
1419        }
1420
1421        fn on_mmio(&mut self, _cx: &esp_soc::Ctx, _pc: u32, addr: u32, value: u32, write: bool) {
1422            if !write {
1423                return;
1424            }
1425            let Some(slot) = self.spec.ports.iter().position(|&(reg, ..)| reg == addr) else {
1426                return;
1427            };
1428            let (_, shift, mask) = self.spec.ports[slot];
1429            // SPI_CLK_EQU_SYSCLK bypasses both dividers; otherwise CLKCNT_N is
1430            // bits 17:12 and CLKDIV_PRE sits above it.
1431            let divider = if value & (1 << 31) != 0 {
1432                1
1433            } else {
1434                (((value >> shift) & mask) + 1) * (((value >> 12) & 0x3f) + 1)
1435            };
1436            let mut rates = self.rates.get();
1437            rates[slot] = (esp_periph::APB_HZ / u64::from(divider)) as u32;
1438            self.rates.set(rates);
1439        }
1440    }
1441
1442    /// `esp_soc::BoardModel` over a flattened Litz board.
1443    ///
1444    /// The bus reports the GPIO output latch and its enable mask; only enabled
1445    /// bits are strong drivers, everything else is high-impedance. Edges the
1446    /// board resolves back onto a chip pin leave through `take_edges`.
1447    struct LitzModel {
1448        board: Rc<RefCell<LitzBoard>>,
1449        /// The board instance whose pads this bus drives.
1450        index: u16,
1451        enabled: u64,
1452        output: u64,
1453        cycle: u64,
1454        releases: Vec<u8>,
1455        /// The chip's clock, to turn esp32sim's bus cycles into the nanoseconds
1456        /// the board's parts and the waveform measure time in.
1457        cpu_hz: u64,
1458        /// Each UART port's receive pin and baud, learned from the route on
1459        /// the chip's last transmitted byte. A board peer answers on the pin
1460        /// the chip listens to, and that is what an input has to name.
1461        uart_routes: BTreeMap<u8, (u8, u32)>,
1462        /// The GP-SPI rates the firmware programmed, shared with the MMIO
1463        /// observer. A chip without GP-SPI registers leaves it all zero.
1464        spi_rates: Rc<Cell<[u32; 2]>>,
1465    }
1466
1467    impl LitzModel {
1468        fn new(
1469            board: Rc<RefCell<LitzBoard>>,
1470            cpu_hz: u64,
1471            index: u16,
1472            spi_rates: Rc<Cell<[u32; 2]>>,
1473        ) -> Self {
1474            Self {
1475                board,
1476                index,
1477                enabled: 0,
1478                output: 0,
1479                cycle: 0,
1480                releases: Vec::new(),
1481                cpu_hz,
1482                uart_routes: BTreeMap::new(),
1483                spi_rates,
1484            }
1485        }
1486
1487        /// The rate the guest programmed for GP-SPI `host`, if it wrote one.
1488        fn spi_rate(&self, host: u8) -> Option<u32> {
1489            let slot = usize::from(host.checked_sub(2)?);
1490            let hz = *self.spi_rates.get().get(slot)?;
1491            (hz > 0).then_some(hz)
1492        }
1493
1494        fn ns(&self, cycle: u64) -> u64 {
1495            (u128::from(cycle) * 1_000_000_000 / u128::from(self.cpu_hz)) as u64
1496        }
1497
1498        /// The first bus cycle at or after `ns`, so a deadline is never
1499        /// rounded down into the past.
1500        fn cycles_for(&self, ns: u64) -> u64 {
1501            let cycles = u128::from(ns) * u128::from(self.cpu_hz);
1502            (cycles.div_ceil(1_000_000_000)) as u64
1503        }
1504    }
1505
1506    /// SSD1306 GDDRAM is page-major, LSB-first within a byte; a host PNG
1507    /// wants one RGB565 word per pixel.
1508    fn expand_monochrome(bytes: &[u8], width: u32, height: u32) -> Vec<u16> {
1509        let mut pixels = vec![0u16; (width * height) as usize];
1510        for page in 0..height.div_ceil(8) {
1511            for column in 0..width {
1512                let Some(byte) = bytes.get((page * width + column) as usize) else {
1513                    continue;
1514                };
1515                for bit in 0..8u32 {
1516                    let y = page * 8 + bit;
1517                    if y >= height {
1518                        break;
1519                    }
1520                    if byte & (1 << bit) != 0 {
1521                        pixels[(y * width + column) as usize] = 0xffff;
1522                    }
1523                }
1524            }
1525        }
1526        pixels
1527    }
1528
1529    /// The board fabric's frame type is the same data as the chip's wire frame, with the
1530    /// board's own fixed-size array and frame kind. Convert once at the boundary.
1531    fn board_can_frame(frame: &esp_soc::board::CanFrame) -> litz_board::bus::CanFrame {
1532        // The chip carries a classic CAN wire frame: eight data bytes at most.
1533        let mut data = [0u8; litz_board::bus::CAN_MAX_DATA];
1534        let len = usize::from(frame.len).min(frame.data.len());
1535        data[..len].copy_from_slice(&frame.data[..len]);
1536        litz_board::bus::CanFrame {
1537            id: frame.id,
1538            extended: frame.extended,
1539            rtr: frame.rtr,
1540            len: frame.len,
1541            data,
1542            kind: if frame.rtr {
1543                litz_board::bus::CanFrameKind::Remote
1544            } else {
1545                litz_board::bus::CanFrameKind::Classic
1546            },
1547        }
1548    }
1549
1550    impl BoardModel for LitzModel {
1551        fn name(&self) -> &'static str {
1552            "litz"
1553        }
1554
1555        fn gpio_output_at(
1556            &mut self,
1557            cycle: u64,
1558            changes: &[(u8, bool)],
1559            enabled: u64,
1560            output: u64,
1561        ) {
1562            // The callback's cycle is relative to the current quantum on some chips;
1563            // `advance_to` carries the absolute bus cycle. Take whichever is later
1564            // so a toggle is never dated before the run reached it.
1565            self.cycle = self.cycle.max(cycle);
1566            let now = self.ns(self.cycle);
1567            if std::env::var("LITZ_TRACE_DEBUG").is_ok() {
1568                eprintln!("DBG cycle={} now={}", self.cycle, now);
1569            }
1570            // An enable-only transition is not in `changes`, and it matters:
1571            // releasing an output must stop driving the net.
1572            let mut mask = (enabled ^ self.enabled) | (output ^ self.output);
1573            for &(pin, _) in changes {
1574                mask |= 1u64 << pin;
1575            }
1576            let mut board = self.board.borrow_mut();
1577            while mask != 0 {
1578                let pin = mask.trailing_zeros() as u8;
1579                mask &= mask - 1;
1580                let bit = 1u64 << pin;
1581                let drive = if enabled & bit != 0 {
1582                    if output & bit != 0 {
1583                        Drive::strong(Level::High)
1584                    } else {
1585                        Drive::strong(Level::Low)
1586                    }
1587                } else {
1588                    Drive::HIGH_Z
1589                };
1590                board.set_chip_output_on(self.index, pin, drive, now);
1591            }
1592            self.enabled = enabled;
1593            self.output = output;
1594        }
1595
1596        /// The first display on this board's buses, as RGB565. A colour TFT
1597        /// hands over its own buffer; a monochrome OLED is expanded one bit
1598        /// per pixel. The change counter comes from the panel, so a host can
1599        /// skip a frame that did not move.
1600        fn display(&self) -> Option<(u32, u32, Vec<u16>, u64)> {
1601            let board = self.board.borrow();
1602            let buses = board.buses();
1603            for (&(owner, _), i2c) in &buses.i2c {
1604                if owner != self.index {
1605                    continue;
1606                }
1607                for address in i2c.addresses() {
1608                    if let Some(oled) = i2c.device_as::<litz_board::Ssd1306>(address) {
1609                        let (bytes, width, height) = oled.framebuffer();
1610                        return Some((
1611                            width,
1612                            height,
1613                            expand_monochrome(bytes, width, height),
1614                            oled.frame_version(),
1615                        ));
1616                    }
1617                }
1618            }
1619            for (&(owner, _), spi) in &buses.spi {
1620                if owner != self.index {
1621                    continue;
1622                }
1623                for select in spi.chip_selects() {
1624                    if let Some(tft) = spi.device_as::<litz_board::Ili9341>(select) {
1625                        let (pixels, width, height) = tft.framebuffer();
1626                        return Some((width, height, pixels.to_vec(), tft.frame_version()));
1627                    }
1628                }
1629            }
1630            None
1631        }
1632
1633        /// Host touch from the browser or a scenario reaches the board's
1634        /// controller part; a board without one ignores it, exactly as a
1635        /// finger on a panel that is not there would.
1636        fn touch(&mut self, x: u16, y: u16, down: bool) {
1637            let _ = self.board.borrow_mut().touch_panel(x, y, down);
1638        }
1639
1640        fn display_version(&self) -> u64 {
1641            let board = self.board.borrow();
1642            let buses = board.buses();
1643            for (&(owner, _), i2c) in &buses.i2c {
1644                if owner != self.index {
1645                    continue;
1646                }
1647                for address in i2c.addresses() {
1648                    if let Some(oled) = i2c.device_as::<litz_board::Ssd1306>(address) {
1649                        return oled.frame_version();
1650                    }
1651                }
1652            }
1653            for (&(owner, _), spi) in &buses.spi {
1654                if owner != self.index {
1655                    continue;
1656                }
1657                for select in spi.chip_selects() {
1658                    if let Some(tft) = spi.device_as::<litz_board::Ili9341>(select) {
1659                        return tft.frame_version();
1660                    }
1661                }
1662            }
1663            0
1664        }
1665
1666        fn advance_to(&mut self, cycle: u64) {
1667            self.cycle = cycle;
1668            // A part that schedules its own edges (a rangefinder's ECHO, a
1669            // sensor's frame) has to be moved on the chip's clock, not the
1670            // board's wall clock. The board settles after every event, so the
1671            // edges this produces are already waiting in `take_edges`.
1672            let now = self.ns(cycle);
1673            self.board.borrow_mut().advance_to(now);
1674        }
1675
1676        fn next_deadline(&self) -> Option<u64> {
1677            // Pending inputs must reach the chip now, not at its next poll. A
1678            // part's next event is nanoseconds; the bus counts cycles.
1679            let board = self.board.borrow();
1680            let now = board.has_pending_inputs_on(self.index).then_some(0);
1681            let event = board.next_event().map(|at| self.cycles_for(at));
1682            match (now, event) {
1683                (Some(a), Some(b)) => Some(a.min(b)),
1684                (a, b) => a.or(b),
1685            }
1686        }
1687
1688        fn take_edges(&mut self) -> Vec<BoardEdge> {
1689            let cycle = self.cycle;
1690            let drained = self.board.borrow_mut().take_chip_inputs_on(self.index);
1691            // One board attach can queue a pin twice: the first settle leaves
1692            // it floating and the next drive, in the same batch, holds it. The
1693            // last level is the one the pad has, so a pin that ends driven is
1694            // not also released — releasing it after `set_input` would put the
1695            // pad back on its pull and lose the level that just arrived.
1696            let mut levels: BTreeMap<u8, Level> = BTreeMap::new();
1697            for (pin, level) in drained {
1698                levels.insert(pin, level);
1699            }
1700            let mut edges = Vec::new();
1701            for (pin, level) in levels {
1702                match level {
1703                    Level::High => edges.push(BoardEdge {
1704                        cycle,
1705                        pin,
1706                        level: true,
1707                    }),
1708                    Level::Low => edges.push(BoardEdge {
1709                        cycle,
1710                        pin,
1711                        level: false,
1712                    }),
1713                    Level::HighZ => self.releases.push(pin),
1714                }
1715            }
1716            edges
1717        }
1718
1719        fn released_inputs(&mut self) -> Vec<u8> {
1720            core::mem::take(&mut self.releases)
1721        }
1722
1723        fn input_levels(&self) -> Vec<(u8, bool)> {
1724            self.board
1725                .borrow()
1726                .input_levels_on(self.index)
1727                .into_iter()
1728                .filter_map(|(pin, level)| match level {
1729                    Level::High => Some((pin, true)),
1730                    Level::Low => Some((pin, false)),
1731                    Level::HighZ => None,
1732                })
1733                .collect()
1734        }
1735
1736        fn named_pin(&self, name: &str) -> Option<u8> {
1737            let board = self.board.borrow();
1738            let (index, pin) = board.named_pin_on(name)?;
1739            (index == self.index).then_some(pin)
1740        }
1741
1742        /// Every I2C target the board holds, as `(controller, address, device)`.
1743        ///
1744        /// The device boxes share the board rather than taking a device out of
1745        /// it, so `Board` remains the owner and stays usable after attach.
1746        fn i2c_devices(&mut self) -> Vec<(u8, u8, Box<dyn EspI2cDevice>)> {
1747            let board = self.board.borrow();
1748            let mut devices: Vec<(u8, u8)> = Vec::new();
1749            for (&(owner, controller), bus) in &board.buses().i2c {
1750                if owner != self.index {
1751                    continue;
1752                }
1753                for address in bus.addresses() {
1754                    devices.push((controller, address));
1755                }
1756            }
1757            drop(board);
1758            devices
1759                .into_iter()
1760                .map(|(controller, address)| {
1761                    let device: Box<dyn EspI2cDevice> = Box::new(BoardI2cDevice {
1762                        board: Rc::clone(&self.board),
1763                        board_index: self.index,
1764                        controller,
1765                        address,
1766                        written: Vec::new(),
1767                        received: Vec::new(),
1768                        reading: false,
1769                        open: false,
1770                        last_at: 0,
1771                        started_at: 0,
1772                    });
1773                    (controller, address, device)
1774                })
1775                .collect()
1776        }
1777
1778        fn uses_spi_pins(&self) -> bool {
1779            self.board
1780                .borrow()
1781                .buses()
1782                .spi
1783                .keys()
1784                .any(|&(owner, _)| owner == self.index)
1785        }
1786
1787        /// A transaction with no pin route: use the only device on the chip's
1788        /// controller, or the board's only device when the controller numbering
1789        /// differs between the board and the chip (a board names `spi0`, the
1790        /// C3 calls its GP-SPI host 2). No device or an ambiguous one floats.
1791        fn spi_transfer(&mut self, host: u8, tx: &[u8], rx_len: usize) -> Vec<u8> {
1792            let rate = self.spi_rate(host);
1793            let mut board = self.board.borrow_mut();
1794            let selected = board
1795                .buses()
1796                .spi_sole(self.index, host)
1797                .or_else(|| board.buses().spi_only_device(self.index));
1798            match selected {
1799                Some((controller, chip_select)) => {
1800                    // The waveform is reconstructed here, so the rate has to
1801                    // reach the board before the transaction does.
1802                    if let Some(hz) = rate {
1803                        board.set_spi_hz(self.index, controller, hz);
1804                    }
1805                    board.spi_transfer(self.index, controller, chip_select, tx, rx_len)
1806                }
1807                None => vec![0xff; rx_len],
1808            }
1809        }
1810
1811        /// A routed transaction: the asserted chip-select lines select the
1812        /// device, exactly as they do on the board.
1813        fn spi_transfer_pins(
1814            &mut self,
1815            host: u8,
1816            pins: SpiPins,
1817            tx: &[u8],
1818            rx_len: usize,
1819        ) -> Vec<u8> {
1820            let rate = self.spi_rate(host);
1821            let mut board = self.board.borrow_mut();
1822            match board.buses().spi_selected(self.index, pins.cs) {
1823                Some((controller, chip_select)) => {
1824                    if let Some(hz) = rate {
1825                        board.set_spi_hz(self.index, controller, hz);
1826                    }
1827                    board.spi_transfer(self.index, controller, chip_select, tx, rx_len)
1828                }
1829                None => vec![0xff; rx_len],
1830            }
1831        }
1832
1833        fn uses_uart_pins(&self) -> bool {
1834            let board = self.board.borrow();
1835            if board
1836                .buses()
1837                .uart
1838                .keys()
1839                .any(|&(owner, _)| owner == self.index)
1840            {
1841                return true;
1842            }
1843            // A pad wired straight to another chip is a UART link with no
1844            // part on the bus, so the ports have to be watched too.
1845            board.flat().has_chip_to_chip_wire(self.index)
1846        }
1847
1848        /// A byte the chip transmitted reaches the peer on `route.port`. The
1849        /// route names the chip's receive pin, so remember it for `uart_rx`.
1850        fn uart_tx(&mut self, cycle: u64, route: UartRoute, byte: u8) {
1851            let now = self.ns(cycle);
1852            let port = route.port as u8;
1853            let baud = route
1854                .baud
1855                .unwrap_or(litz_board::runtime::OBSERVED_UART_BAUD);
1856            let mut board = self.board.borrow_mut();
1857            board.set_uart_baud(self.index, port, baud);
1858            // The pads are what a wire to another chip is found through.
1859            board.set_uart_pins(self.index, port, route.tx_pins, route.rx_pin);
1860            board.uart_receive(self.index, port, now, &[byte]);
1861            drop(board);
1862            if let Some(pin) = route.rx_pin {
1863                self.uart_routes
1864                    .insert(port, (pin, route.baud.unwrap_or(115_200)));
1865            }
1866        }
1867
1868        /// Bytes the board's UART peers have ready, one input per port. The
1869        /// chip's last route supplies the pin and baud; before the chip has
1870        /// transmitted, the board's resolved wiring names the receive pin and
1871        /// the usual 115 200 baud is assumed. A port with neither is skipped.
1872        fn uart_rx(&mut self, cycle: u64) -> Vec<UartInput> {
1873            let now = self.ns(cycle);
1874            let mut board = self.board.borrow_mut();
1875            for (&port, &(_, baud)) in &self.uart_routes {
1876                board.set_uart_baud(self.index, port, baud);
1877            }
1878            // A port wired to another chip has no bus entry, so the chip's own
1879            // routes are the starting set; a bus-only port is added beside it.
1880            let mut ports: BTreeMap<u8, Option<(u8, u32)>> = self
1881                .uart_routes
1882                .iter()
1883                .map(|(&port, &route)| (port, Some(route)))
1884                .collect();
1885            for &(owner, port) in board.buses().uart.keys() {
1886                if owner != self.index {
1887                    continue;
1888                }
1889                ports.entry(port).or_insert_with(|| {
1890                    board
1891                        .flat()
1892                        .buses
1893                        .uart
1894                        .get(&(self.index, port))
1895                        .map(|bus| (bus.chip_rx, 115_200))
1896                });
1897            }
1898            let mut inputs = Vec::new();
1899            for (port, route) in ports {
1900                let Some((pin, baud)) = route else { continue };
1901                let data = board.uart_poll(self.index, port, now);
1902                if !data.is_empty() {
1903                    inputs.push(UartInput::new(pin, baud, data));
1904                }
1905            }
1906            inputs
1907        }
1908
1909        /// The chip completed a TWAI transmission: put it on the board's shared CAN wire.
1910        /// The node is the board index, so two MCUs on one diagram are distinct endpoints.
1911        fn can_tx(&mut self, _host: u8, frame: &[u8]) {
1912            let Some(frame) = esp_soc::board::CanFrame::decode(frame) else {
1913                return;
1914            };
1915            let mut board = self.board.borrow_mut();
1916            let can = board.buses_mut().can_mut();
1917            can.attach(self.index);
1918            let _ = can.transmit(self.index, board_can_frame(&frame));
1919        }
1920
1921        /// The chip's TWAI receive buffer is empty: hand it the next frame addressed to this
1922        /// board's node. Attaching lazily keeps a CAN-free diagram unchanged; nothing is
1923        /// queued for a board that never drives TWAI.
1924        fn can_take(&mut self, _host: u8) -> Option<Vec<u8>> {
1925            let mut board = self.board.borrow_mut();
1926            let can = board.buses_mut().can_mut();
1927            can.attach(self.index);
1928            let frame = can.take(self.index)?;
1929            // The chip's wire frame holds only the eight classic CAN bytes.
1930            let mut data = [0u8; esp_soc::board::CAN_MAX_DATA];
1931            let len = usize::from(frame.len).min(data.len());
1932            data[..len].copy_from_slice(&frame.data[..len]);
1933            Some(
1934                esp_soc::board::CanFrame {
1935                    id: frame.id,
1936                    extended: frame.extended,
1937                    rtr: frame.rtr || frame.kind == litz_board::bus::CanFrameKind::Remote,
1938                    len: frame.len,
1939                    data,
1940                }
1941                .encode()
1942                .to_vec(),
1943            )
1944        }
1945    }
1946
1947    /// The [`litz_board::Chip`] view of this adapter: what a runner needs, with
1948    /// nothing esp32sim-specific in the signature.
1949    impl<S: Soc> litz_board::Chip for EspChip<S> {
1950        fn info(&self) -> litz_board::ChipInfo {
1951            litz_board::ChipInfo {
1952                name: S::NAME.into(),
1953                cpu_hz: S::CPU_HZ,
1954                flash: litz_board::FlashLayout {
1955                    size: self.flash as u64,
1956                    bootloader: S::BOOTLOADER_OFFSET as u64,
1957                    partition_table: 0x8000,
1958                    app: 0x1_0000,
1959                },
1960            }
1961        }
1962
1963        fn load_image(
1964            &mut self,
1965            kind: litz_board::ImageKind,
1966            offset: u64,
1967            bytes: &[u8],
1968        ) -> Result<(), String> {
1969            match kind {
1970                litz_board::ImageKind::Rom => self.load_rom(bytes),
1971                litz_board::ImageKind::Bootloader => {
1972                    self.bootloader_loaded = true;
1973                    self.write_flash(offset as usize, bytes)
1974                }
1975                _ => self.write_flash(offset as usize, bytes),
1976            }
1977        }
1978
1979        fn set_psram_size(&mut self, bytes: usize) -> Result<(), String> {
1980            EspChip::set_psram_size(self, bytes)
1981        }
1982
1983        fn flash_image(&self) -> Option<Vec<u8>> {
1984            EspChip::flash_image(self).map(<[u8]>::to_vec)
1985        }
1986
1987        fn boot(&mut self) -> Result<u32, String> {
1988            self.powered = self.board_power();
1989            if !self.powered {
1990                // The board is off: the firmware waits for its power pin. The
1991                // images are loaded, so the first powered run boots them.
1992                return Ok(0);
1993            }
1994            if self.bootloader_loaded {
1995                // The bootloader finds the application itself; starting the app
1996                // directly would skip it.
1997                return Ok(0);
1998            }
1999            let app = self.info().flash.app as usize;
2000            self.boot_app(app)
2001        }
2002
2003        fn schedule(&mut self, inputs: Vec<litz_board::Input>) -> Result<(), String> {
2004            let mut text = String::new();
2005            for input in inputs {
2006                match input {
2007                    litz_board::Input::Gpio { at_ns, pin, level } => {
2008                        let seconds = at_ns as f64 / 1e9;
2009                        let bit = u8::from(level == Level::High);
2010                        text.push_str(&format!("{seconds:.6} gpio {pin} {bit}\n"));
2011                    }
2012                    litz_board::Input::Uart { at_ns, bytes } => {
2013                        let seconds = at_ns as f64 / 1e9;
2014                        let text_in = String::from_utf8_lossy(&bytes);
2015                        // The script format appends the newline itself.
2016                        text.push_str(&format!(
2017                            "{seconds:.6} uart0 {}\n",
2018                            text_in.trim_end_matches('\n')
2019                        ));
2020                    }
2021                }
2022            }
2023            if text.is_empty() {
2024                Ok(())
2025            } else {
2026                self.load_script(&text)
2027            }
2028        }
2029
2030        fn run(&mut self, budget_cycles: u64) -> litz_board::RunResult {
2031            if !EspChip::board_power(self) {
2032                if self.powered {
2033                    self.power_off();
2034                }
2035                // Time passes while the board is off; the machine's own clock
2036                // stands still, so account for it here.
2037                let cycles = u128::from(budget_cycles) * 1_000_000_000;
2038                let cpu_hz = u128::from(litz_board::Chip::info(self).cpu_hz.max(1));
2039                self.off_ns = self.off_ns.saturating_add((cycles / cpu_hz) as u64);
2040                return litz_board::RunResult {
2041                    cycles: budget_cycles,
2042                    stop: litz_board::Stop::Idle,
2043                };
2044            }
2045            if !self.powered {
2046                // Power arrived: start the firmware from its reset vector.
2047                if self.boot_after_power().is_err() {
2048                    return litz_board::RunResult {
2049                        cycles: 0,
2050                        stop: litz_board::Stop::Trap,
2051                    };
2052                }
2053                self.powered = true;
2054            }
2055            let stop = match EspChip::run(self, budget_cycles) {
2056                esp_soc::Stop::MaxInsns => litz_board::Stop::Budget,
2057                esp_soc::Stop::Halted => litz_board::Stop::Halted,
2058                esp_soc::Stop::SwReset => litz_board::Stop::Reset,
2059                esp_soc::Stop::Breakpoint(pc) => litz_board::Stop::Breakpoint(pc),
2060                _ => litz_board::Stop::Idle,
2061            };
2062            litz_board::RunResult {
2063                cycles: budget_cycles,
2064                stop,
2065            }
2066        }
2067
2068        fn seconds(&self) -> f64 {
2069            EspChip::seconds(self)
2070        }
2071
2072        fn write_console(&mut self, bytes: &[u8]) {
2073            // Both interpreters the runner speaks to read their console from
2074            // UART0. Mirroring the bytes onto the USB block as well splits one
2075            // paste across two input paths and the guest sees it twice.
2076            self.write_serial(bytes);
2077        }
2078
2079        fn take_console(&mut self) -> Vec<u8> {
2080            let mut bytes = self.take_uart0();
2081            // The machine's own drain already moved USB output into this
2082            // backlog; a chip without a USB peripheral leaves it empty. A
2083            // build that logs to both consoles sends the same bytes down each,
2084            // so an identical copy is the same console message, not a second
2085            // one.
2086            let usb = core::mem::take(&mut self.machine.console.usb);
2087            if usb != bytes {
2088                bytes.extend(usb);
2089            }
2090            bytes
2091        }
2092
2093        fn state(&self, part: &str) -> Option<PartState> {
2094            EspChip::state(self, part)
2095        }
2096
2097        fn press(&mut self, part: &str, pressed: bool) -> bool {
2098            EspChip::press(self, part, pressed)
2099        }
2100
2101        fn set_control(&mut self, part: &str, value: u16) -> bool {
2102            EspChip::set_control(self, part, value)
2103        }
2104
2105        fn set_named_control(&mut self, part: &str, name: &str, value: &str) -> bool {
2106            EspChip::set_named_control(self, part, name, value)
2107        }
2108
2109        fn part_pin_level(&self, part: &str, pin: Option<&str>) -> Option<Level> {
2110            EspChip::part_pin_level(self, part, pin)
2111        }
2112
2113        fn gpio_level(&self, gpio: u8) -> Option<Level> {
2114            EspChip::gpio_level(self, gpio)
2115        }
2116
2117        fn conflicts(&self) -> Vec<Conflict> {
2118            EspChip::conflicts(self)
2119        }
2120
2121        fn start_trace(&mut self) {
2122            if let Some(board) = self.board.as_ref() {
2123                board.borrow_mut().start_trace();
2124            }
2125        }
2126
2127        fn vcd(&self) -> String {
2128            self.board
2129                .as_ref()
2130                .map(|board| board.borrow().vcd())
2131                .unwrap_or_default()
2132        }
2133
2134        fn break_at(&mut self, pc: u32) {
2135            EspChip::break_at(self, pc);
2136        }
2137
2138        fn registers(&self) -> String {
2139            self.machine.dump_regs()
2140        }
2141
2142        fn report(&mut self) -> Vec<String> {
2143            EspChip::reports(self)
2144        }
2145
2146        fn enable_coverage(&mut self) {
2147            EspChip::enable_coverage(self);
2148        }
2149
2150        fn display(&mut self) -> Option<(u32, u32, Vec<u16>, u64)> {
2151            self.machine.bus.board().display()
2152        }
2153
2154        fn display_version(&mut self) -> u64 {
2155            self.machine.bus.board().display_version()
2156        }
2157
2158        fn save_display(&mut self, path: &std::path::Path) -> Result<(), String> {
2159            crate::screenshot::capture(self, path)
2160        }
2161
2162        fn save_part_display(&mut self, part: &str, path: &std::path::Path) -> Result<(), String> {
2163            let Some(board) = &self.board else {
2164                return Err("this chip is not attached to a board".into());
2165            };
2166            let image = board
2167                .borrow()
2168                .part_framebuffer(part)
2169                .ok_or_else(|| format!("part {part:?} is not a display with a framebuffer"))?;
2170            std::fs::write(path, image.to_png()).map_err(|e| format!("{}: {e}", path.display()))
2171        }
2172
2173        fn sample_heap(&mut self) -> Result<u32, String> {
2174            EspChip::sample_heap(self)
2175        }
2176
2177        fn touch(&mut self, x: u16, y: u16, down: bool) -> Result<(), String> {
2178            let Some(board) = &self.board else {
2179                return Err("this chip is not attached to a board".into());
2180            };
2181            board.borrow_mut().touch_panel(x, y, down)
2182        }
2183
2184        fn start_air_capture(&mut self, path: &std::path::Path) -> Result<(), String> {
2185            EspChip::start_air_capture(self, path)
2186        }
2187
2188        fn start_ethernet_capture(&mut self, path: &std::path::Path) -> Result<(), String> {
2189            EspChip::start_ethernet_capture(self, path)
2190        }
2191
2192        fn attach_host_gateway(&mut self, forwards: &[String]) -> Result<Vec<String>, String> {
2193            #[cfg(not(target_arch = "wasm32"))]
2194            {
2195                if forwards.is_empty() {
2196                    EspChip::attach_host_nat(self, false).map(|()| Vec::new())
2197                } else {
2198                    EspChip::attach_host_forwards(self, forwards, false)
2199                }
2200            }
2201            #[cfg(target_arch = "wasm32")]
2202            {
2203                let _ = forwards;
2204                Err("the browser build has no host sockets".into())
2205            }
2206        }
2207
2208        fn debug_available(&self) -> bool {
2209            use emu_core::Core;
2210            self.machine_ref()
2211                .cores
2212                .first()
2213                .map(|core| {
2214                    let mut names = Vec::new();
2215                    core.regs(&mut names);
2216                    names.iter().any(|(name, _)| *name == "ra")
2217                        && names.iter().any(|(name, _)| *name == "sp")
2218                })
2219                .unwrap_or(false)
2220        }
2221
2222        fn debug_pc(&self) -> Option<u32> {
2223            use emu_core::Core;
2224            self.machine_ref().cores.first().map(|core| core.pc())
2225        }
2226
2227        fn debug_register_file(&self) -> Option<[u32; 33]> {
2228            use emu_core::Core;
2229            let core = self.machine_ref().cores.first()?;
2230            let mut names = Vec::new();
2231            core.regs(&mut names);
2232            if !names.iter().any(|(name, _)| *name == "ra") {
2233                return None;
2234            }
2235            const RV: [&str; 32] = [
2236                "zero", "ra", "sp", "gp", "tp", "t0", "t1", "t2", "s0", "s1", "a0", "a1", "a2",
2237                "a3", "a4", "a5", "a6", "a7", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9",
2238                "s10", "s11", "t3", "t4", "t5", "t6",
2239            ];
2240            let mut file = [0u32; 33];
2241            for (index, want) in RV.iter().enumerate() {
2242                if let Some((_, value)) = names.iter().find(|(name, _)| name == want) {
2243                    file[index] = *value;
2244                }
2245            }
2246            file[32] = core.pc();
2247            Some(file)
2248        }
2249
2250        fn debug_read_memory(&mut self, addr: u32, len: usize) -> Vec<u8> {
2251            if len == 0 {
2252                return Vec::new();
2253            }
2254            let start = addr & !3;
2255            let skip = (addr - start) as usize;
2256            let words = (skip + len).div_ceil(4);
2257            let text = self.machine_mut().peek(start, words);
2258            let mut bytes = Vec::with_capacity(words * 4);
2259            for line in text.lines() {
2260                let Some((_, word)) = line.split_once(": ") else {
2261                    break;
2262                };
2263                let Ok(word) = u32::from_str_radix(word.trim(), 16) else {
2264                    break;
2265                };
2266                bytes.extend_from_slice(&word.to_le_bytes());
2267            }
2268            if bytes.len() < skip {
2269                return Vec::new();
2270            }
2271            let end = (skip + len).min(bytes.len());
2272            bytes[skip..end].to_vec()
2273        }
2274
2275        fn debug_disassemble(&mut self, addr: u32, count: usize) -> String {
2276            self.disassemble(addr, count)
2277        }
2278
2279        fn debug_set_breakpoints(&mut self, pcs: &[u32]) {
2280            self.machine_mut().set_breakpoints(pcs.to_vec());
2281        }
2282
2283        fn debug_step(&mut self) -> Option<litz_board::Stop> {
2284            Some(match self.machine_mut().step_one() {
2285                esp_soc::Stop::MaxInsns => litz_board::Stop::Budget,
2286                esp_soc::Stop::Halted => litz_board::Stop::Halted,
2287                esp_soc::Stop::SwReset => litz_board::Stop::Reset,
2288                esp_soc::Stop::Breakpoint(pc) => litz_board::Stop::Breakpoint(pc),
2289                _ => litz_board::Stop::Idle,
2290            })
2291        }
2292
2293        fn debug(&mut self) -> Option<&mut dyn litz_board::ChipDebug> {
2294            Some(self)
2295        }
2296    }
2297
2298    impl<S: Soc> litz_board::ChipDebug for EspChip<S> {
2299        fn serve(&mut self, port: u16) -> Result<(), String> {
2300            self.gdb_serve(port)
2301        }
2302
2303        fn report(&mut self) -> String {
2304            self.machine.dump_regs()
2305        }
2306    }
2307
2308    #[cfg(all(test, feature = "esp32c3"))]
2309    mod ble_peers {
2310        use super::*;
2311
2312        fn beacon() -> litz_ble::Beacon {
2313            litz_ble::Beacon {
2314                name: Some("late".into()),
2315                services: Vec::new(),
2316                address: [0x04, 0x03, 0x02, 0x01, 0xaa, 0xc4],
2317                rssi: -42,
2318                adv: vec![2, 1, 6, 6, 9, b'l', b'a', b't', b'e'],
2319                scan_response: Vec::new(),
2320                gatt: Vec::new(),
2321            }
2322        }
2323
2324        /// A scan enabled before the peer arrives hears it on the next report.
2325        /// The controller is stood up just far enough for `ble_nearby` to
2326        /// accept a list: firmware assets are not needed to test the list.
2327        #[test]
2328        fn a_peer_added_at_runtime_reaches_a_live_scan() {
2329            let mut chip = C3::new([0x24, 0x0a, 0xc4, 0x00, 0x01, 0x10], 4 << 20);
2330            assert_eq!(
2331                chip.add_ble_peer(&beacon()).unwrap_err(),
2332                "BLE is not enabled on this chip"
2333            );
2334            chip.machine_mut().bus.ble.hooks.push(0);
2335            chip.machine_mut().bus.ble.lines.keep();
2336            chip.ble_attached = true;
2337
2338            // LE Set Scan Enable: enabled, passive.
2339            chip.machine_mut()
2340                .bus
2341                .ble
2342                .session
2343                .send(&[1, 0x0c, 0x20, 2, 1, 0]);
2344            chip.machine_mut().bus.ble.session.drain_log();
2345
2346            chip.add_ble_peer(&beacon())
2347                .expect("the scan accepts the list");
2348            assert_eq!(chip.ble_peers.len(), 1);
2349            let line = chip.ble_log().expect("the controller logged a report");
2350            assert!(line.contains("scan report"), "{line}");
2351            assert!(line.contains("c4:aa:01:02:03:04"), "{line}");
2352        }
2353    }
2354}
2355
2356const PLIC_AND_RV_MAP: [MemoryRegion; 6] = [
2357    MemoryRegion::new("irom", 0x4200_0000, 0x0040_0000),
2358    MemoryRegion::new("drom", 0x3C00_0000, 0x0040_0000),
2359    MemoryRegion::new("dram", 0x3FC8_0000, 0x0004_0000),
2360    MemoryRegion::new("irom-dram", 0x4037_C000, 0x0000_8000),
2361    MemoryRegion::new("peripherals", 0x6000_0000, 0x0010_0000),
2362    MemoryRegion::new("rtc", 0x5000_0000, 0x0001_0000),
2363];