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