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            let opening = !self.open;
1302            if opening {
1303                self.written.clear();
1304                self.received.clear();
1305                self.open = true;
1306                self.started_at = self.board.borrow().now();
1307            }
1308            self.reading = read;
1309            let mut board = self.board.borrow_mut();
1310            if opening {
1311                board.i2c_begin(self.board_index, self.controller, self.address);
1312            }
1313            let Some(bus) = board
1314                .buses_mut()
1315                .i2c
1316                .get_mut(&(self.board_index, self.controller))
1317            else {
1318                return false;
1319            };
1320            let Some(device) = bus.device_mut(self.address) else {
1321                return false;
1322            };
1323            device.connect(read);
1324            true
1325        }
1326
1327        fn write(&mut self, byte: u8) -> bool {
1328            if !self.reading {
1329                self.written.push(byte);
1330            }
1331            let mut board = self.board.borrow_mut();
1332            let Some(bus) = board
1333                .buses_mut()
1334                .i2c
1335                .get_mut(&(self.board_index, self.controller))
1336            else {
1337                return false;
1338            };
1339            let Some(device) = bus.device_mut(self.address) else {
1340                return false;
1341            };
1342            device.write(byte)
1343        }
1344
1345        fn read(&mut self) -> u8 {
1346            let byte = {
1347                let mut board = self.board.borrow_mut();
1348                let Some(bus) = board
1349                    .buses_mut()
1350                    .i2c
1351                    .get_mut(&(self.board_index, self.controller))
1352                else {
1353                    return 0xff;
1354                };
1355                let Some(device) = bus.device_mut(self.address) else {
1356                    return 0xff;
1357                };
1358                device.read()
1359            };
1360            self.received.push(byte);
1361            byte
1362        }
1363
1364        fn stop(&mut self) {
1365            {
1366                let mut board = self.board.borrow_mut();
1367                let Some(bus) = board
1368                    .buses_mut()
1369                    .i2c
1370                    .get_mut(&(self.board_index, self.controller))
1371                else {
1372                    return;
1373                };
1374                if let Some(device) = bus.device_mut(self.address) {
1375                    device.stop();
1376                }
1377            }
1378            if self.open {
1379                let mut board = self.board.borrow_mut();
1380                board.i2c_end(self.board_index, self.controller, self.address);
1381                let end = board.now();
1382                let at = self.started_at.max(self.last_at);
1383                let phases = 1
1384                    + self.written.len()
1385                    + if self.received.is_empty() {
1386                        0
1387                    } else {
1388                        1 + self.received.len()
1389                    };
1390                // The controller clocks each phase at the divider the firmware
1391                // programmed, so the transaction's own duration is the SCL
1392                // rate. Falling back to the last known rate keeps a
1393                // zero-duration model (a callback-only device) usable.
1394                let elapsed = end.saturating_sub(self.started_at);
1395                let hz = if elapsed > 0 {
1396                    (phases as u128 * 9 * 1_000_000_000 / u128::from(elapsed))
1397                        .clamp(1_000, 5_000_000) as u32
1398                } else {
1399                    board.i2c_hz(self.board_index, self.controller)
1400                };
1401                board.set_i2c_hz(self.board_index, self.controller, hz);
1402                board.observe_i2c(
1403                    self.board_index,
1404                    self.controller,
1405                    self.address,
1406                    &self.written,
1407                    &self.received,
1408                    at,
1409                );
1410                let period = 1_000_000_000 / u64::from(hz);
1411                self.last_at = (at + phases as u64 * 9 * period).max(end);
1412            }
1413            self.open = false;
1414            self.reading = false;
1415        }
1416    }
1417
1418    /// Where one chip keeps its GP-SPI clock dividers.
1419    ///
1420    /// The two Xtensa parts encode the same `APB / ((pre+1) * (n+1))` divider
1421    /// at the same bit positions, but the register offset and the width of the
1422    /// pre-divider differ: the classic ESP32 has 0x18 and 13 bits, the S3 0xC
1423    /// and 4 bits.
1424    #[derive(Clone, Copy)]
1425    struct SpiClockSpec {
1426        /// `(clock register, pre-divider shift, pre-divider mask)` for hosts 2 and 3.
1427        ports: [(u32, u32, u32); 2],
1428    }
1429
1430    #[cfg(feature = "esp32")]
1431    const ESP32_SPI_CLOCKS: SpiClockSpec = SpiClockSpec {
1432        ports: [(0x3ff6_4018, 18, 0x1fff), (0x3ff6_5018, 18, 0x1fff)],
1433    };
1434
1435    #[cfg(feature = "esp32s3")]
1436    const S3_SPI_CLOCKS: SpiClockSpec = SpiClockSpec {
1437        ports: [(0x6002_400c, 18, 0xf), (0x6002_500c, 18, 0xf)],
1438    };
1439
1440    /// Turns a firmware's GP-SPI clock-register write into the rate the board
1441    /// model reports for the next transfer.
1442    ///
1443    /// esp32sim's `spi_transfer` callback carries bytes, not a clock, so the
1444    /// programmed divider has to travel beside it. Watching MMIO is exact and
1445    /// cheap: only a register write ever changes the rate.
1446    struct SpiClockObserver {
1447        rates: Rc<Cell<[u32; 2]>>,
1448        spec: SpiClockSpec,
1449    }
1450
1451    impl<S: Soc> esp_soc::Observer<S> for SpiClockObserver {
1452        fn name(&self) -> &'static str {
1453            "litz-spi-clock"
1454        }
1455
1456        fn wants(&self) -> esp_soc::Wants {
1457            esp_soc::Wants::MMIO
1458        }
1459
1460        fn on_mmio(&mut self, _cx: &esp_soc::Ctx, _pc: u32, addr: u32, value: u32, write: bool) {
1461            if !write {
1462                return;
1463            }
1464            let Some(slot) = self.spec.ports.iter().position(|&(reg, ..)| reg == addr) else {
1465                return;
1466            };
1467            let (_, shift, mask) = self.spec.ports[slot];
1468            // SPI_CLK_EQU_SYSCLK bypasses both dividers; otherwise CLKCNT_N is
1469            // bits 17:12 and CLKDIV_PRE sits above it.
1470            let divider = if value & (1 << 31) != 0 {
1471                1
1472            } else {
1473                (((value >> shift) & mask) + 1) * (((value >> 12) & 0x3f) + 1)
1474            };
1475            let mut rates = self.rates.get();
1476            rates[slot] = (esp_periph::APB_HZ / u64::from(divider)) as u32;
1477            self.rates.set(rates);
1478        }
1479    }
1480
1481    /// `esp_soc::BoardModel` over a flattened Litz board.
1482    ///
1483    /// The bus reports the GPIO output latch and its enable mask; only enabled
1484    /// bits are strong drivers, everything else is high-impedance. Edges the
1485    /// board resolves back onto a chip pin leave through `take_edges`.
1486    struct LitzModel {
1487        board: Rc<RefCell<LitzBoard>>,
1488        /// The board instance whose pads this bus drives.
1489        index: u16,
1490        enabled: u64,
1491        output: u64,
1492        cycle: u64,
1493        releases: Vec<u8>,
1494        /// The chip's clock, to turn esp32sim's bus cycles into the nanoseconds
1495        /// the board's parts and the waveform measure time in.
1496        cpu_hz: u64,
1497        /// Each UART port's receive pin and baud, learned from the route on
1498        /// the chip's last transmitted byte. A board peer answers on the pin
1499        /// the chip listens to, and that is what an input has to name.
1500        uart_routes: BTreeMap<u8, (u8, u32)>,
1501        /// The GP-SPI rates the firmware programmed, shared with the MMIO
1502        /// observer. A chip without GP-SPI registers leaves it all zero.
1503        spi_rates: Rc<Cell<[u32; 2]>>,
1504    }
1505
1506    impl LitzModel {
1507        fn new(
1508            board: Rc<RefCell<LitzBoard>>,
1509            cpu_hz: u64,
1510            index: u16,
1511            spi_rates: Rc<Cell<[u32; 2]>>,
1512        ) -> Self {
1513            Self {
1514                board,
1515                index,
1516                enabled: 0,
1517                output: 0,
1518                cycle: 0,
1519                releases: Vec::new(),
1520                cpu_hz,
1521                uart_routes: BTreeMap::new(),
1522                spi_rates,
1523            }
1524        }
1525
1526        /// The rate the guest programmed for GP-SPI `host`, if it wrote one.
1527        fn spi_rate(&self, host: u8) -> Option<u32> {
1528            let slot = usize::from(host.checked_sub(2)?);
1529            let hz = *self.spi_rates.get().get(slot)?;
1530            (hz > 0).then_some(hz)
1531        }
1532
1533        fn ns(&self, cycle: u64) -> u64 {
1534            (u128::from(cycle) * 1_000_000_000 / u128::from(self.cpu_hz)) as u64
1535        }
1536
1537        /// The first bus cycle at or after `ns`, so a deadline is never
1538        /// rounded down into the past.
1539        fn cycles_for(&self, ns: u64) -> u64 {
1540            let cycles = u128::from(ns) * u128::from(self.cpu_hz);
1541            (cycles.div_ceil(1_000_000_000)) as u64
1542        }
1543    }
1544
1545    /// SSD1306 GDDRAM is page-major, LSB-first within a byte; a host PNG
1546    /// wants one RGB565 word per pixel.
1547    fn expand_monochrome(bytes: &[u8], width: u32, height: u32) -> Vec<u16> {
1548        let mut pixels = vec![0u16; (width * height) as usize];
1549        for page in 0..height.div_ceil(8) {
1550            for column in 0..width {
1551                let Some(byte) = bytes.get((page * width + column) as usize) else {
1552                    continue;
1553                };
1554                for bit in 0..8u32 {
1555                    let y = page * 8 + bit;
1556                    if y >= height {
1557                        break;
1558                    }
1559                    if byte & (1 << bit) != 0 {
1560                        pixels[(y * width + column) as usize] = 0xffff;
1561                    }
1562                }
1563            }
1564        }
1565        pixels
1566    }
1567
1568    /// The board fabric's frame type is the same data as the chip's wire frame, with the
1569    /// board's own fixed-size array and frame kind. Convert once at the boundary.
1570    fn board_can_frame(frame: &esp_soc::board::CanFrame) -> litz_board::bus::CanFrame {
1571        // The chip carries a classic CAN wire frame: eight data bytes at most.
1572        let mut data = [0u8; litz_board::bus::CAN_MAX_DATA];
1573        let len = usize::from(frame.len).min(frame.data.len());
1574        data[..len].copy_from_slice(&frame.data[..len]);
1575        litz_board::bus::CanFrame {
1576            id: frame.id,
1577            extended: frame.extended,
1578            rtr: frame.rtr,
1579            len: frame.len,
1580            data,
1581            kind: if frame.rtr {
1582                litz_board::bus::CanFrameKind::Remote
1583            } else {
1584                litz_board::bus::CanFrameKind::Classic
1585            },
1586        }
1587    }
1588
1589    impl BoardModel for LitzModel {
1590        fn name(&self) -> &'static str {
1591            "litz"
1592        }
1593
1594        fn gpio_output_at(
1595            &mut self,
1596            cycle: u64,
1597            changes: &[(u8, bool)],
1598            enabled: u64,
1599            output: u64,
1600        ) {
1601            // The callback's cycle is relative to the current quantum on some chips;
1602            // `advance_to` carries the absolute bus cycle. Take whichever is later
1603            // so a toggle is never dated before the run reached it.
1604            self.cycle = self.cycle.max(cycle);
1605            let now = self.ns(self.cycle);
1606            if std::env::var("LITZ_TRACE_DEBUG").is_ok() {
1607                eprintln!("DBG cycle={} now={}", self.cycle, now);
1608            }
1609            // An enable-only transition is not in `changes`, and it matters:
1610            // releasing an output must stop driving the net.
1611            let mut mask = (enabled ^ self.enabled) | (output ^ self.output);
1612            for &(pin, _) in changes {
1613                mask |= 1u64 << pin;
1614            }
1615            let mut board = self.board.borrow_mut();
1616            while mask != 0 {
1617                let pin = mask.trailing_zeros() as u8;
1618                mask &= mask - 1;
1619                let bit = 1u64 << pin;
1620                let drive = if enabled & bit != 0 {
1621                    if output & bit != 0 {
1622                        Drive::strong(Level::High)
1623                    } else {
1624                        Drive::strong(Level::Low)
1625                    }
1626                } else {
1627                    Drive::HIGH_Z
1628                };
1629                board.set_chip_output_on(self.index, pin, drive, now);
1630            }
1631            self.enabled = enabled;
1632            self.output = output;
1633        }
1634
1635        /// The first display on this board's buses, as RGB565. A colour TFT
1636        /// hands over its own buffer; a monochrome OLED is expanded one bit
1637        /// per pixel. The change counter comes from the panel, so a host can
1638        /// skip a frame that did not move.
1639        fn display(&self) -> Option<(u32, u32, Vec<u16>, u64)> {
1640            let board = self.board.borrow();
1641            let buses = board.buses();
1642            for (&(owner, _), i2c) in &buses.i2c {
1643                if owner != self.index {
1644                    continue;
1645                }
1646                for address in i2c.addresses() {
1647                    if let Some(oled) = i2c.device_as::<litz_board::Ssd1306>(address) {
1648                        let (bytes, width, height) = oled.framebuffer();
1649                        return Some((
1650                            width,
1651                            height,
1652                            expand_monochrome(bytes, width, height),
1653                            oled.frame_version(),
1654                        ));
1655                    }
1656                }
1657            }
1658            for (&(owner, _), spi) in &buses.spi {
1659                if owner != self.index {
1660                    continue;
1661                }
1662                for select in spi.chip_selects() {
1663                    if let Some(tft) = spi.device_as::<litz_board::Ili9341>(select) {
1664                        let (pixels, width, height) = tft.framebuffer();
1665                        return Some((width, height, pixels.to_vec(), tft.frame_version()));
1666                    }
1667                }
1668            }
1669            None
1670        }
1671
1672        /// Host touch from the browser or a scenario reaches the board's
1673        /// controller part; a board without one ignores it, exactly as a
1674        /// finger on a panel that is not there would.
1675        fn touch(&mut self, x: u16, y: u16, down: bool) {
1676            let _ = self.board.borrow_mut().touch_panel(x, y, down);
1677        }
1678
1679        fn display_version(&self) -> u64 {
1680            let board = self.board.borrow();
1681            let buses = board.buses();
1682            for (&(owner, _), i2c) in &buses.i2c {
1683                if owner != self.index {
1684                    continue;
1685                }
1686                for address in i2c.addresses() {
1687                    if let Some(oled) = i2c.device_as::<litz_board::Ssd1306>(address) {
1688                        return oled.frame_version();
1689                    }
1690                }
1691            }
1692            for (&(owner, _), spi) in &buses.spi {
1693                if owner != self.index {
1694                    continue;
1695                }
1696                for select in spi.chip_selects() {
1697                    if let Some(tft) = spi.device_as::<litz_board::Ili9341>(select) {
1698                        return tft.frame_version();
1699                    }
1700                }
1701            }
1702            0
1703        }
1704
1705        fn advance_to(&mut self, cycle: u64) {
1706            self.cycle = cycle;
1707            // A part that schedules its own edges (a rangefinder's ECHO, a
1708            // sensor's frame) has to be moved on the chip's clock, not the
1709            // board's wall clock. The board settles after every event, so the
1710            // edges this produces are already waiting in `take_edges`.
1711            let now = self.ns(cycle);
1712            self.board.borrow_mut().advance_to(now);
1713        }
1714
1715        fn next_deadline(&self) -> Option<u64> {
1716            // Pending inputs must reach the chip now, not at its next poll. A
1717            // part's next event is nanoseconds; the bus counts cycles.
1718            let board = self.board.borrow();
1719            let now = board.has_pending_inputs_on(self.index).then_some(0);
1720            let event = board.next_event().map(|at| self.cycles_for(at));
1721            match (now, event) {
1722                (Some(a), Some(b)) => Some(a.min(b)),
1723                (a, b) => a.or(b),
1724            }
1725        }
1726
1727        fn take_edges(&mut self) -> Vec<BoardEdge> {
1728            let cycle = self.cycle;
1729            let drained = self.board.borrow_mut().take_chip_inputs_on(self.index);
1730            // One board attach can queue a pin twice: the first settle leaves
1731            // it floating and the next drive, in the same batch, holds it. The
1732            // last level is the one the pad has, so a pin that ends driven is
1733            // not also released — releasing it after `set_input` would put the
1734            // pad back on its pull and lose the level that just arrived.
1735            let mut levels: BTreeMap<u8, Level> = BTreeMap::new();
1736            for (pin, level) in drained {
1737                levels.insert(pin, level);
1738            }
1739            let mut edges = Vec::new();
1740            for (pin, level) in levels {
1741                match level {
1742                    Level::High => edges.push(BoardEdge {
1743                        cycle,
1744                        pin,
1745                        level: true,
1746                    }),
1747                    Level::Low => edges.push(BoardEdge {
1748                        cycle,
1749                        pin,
1750                        level: false,
1751                    }),
1752                    Level::HighZ => self.releases.push(pin),
1753                }
1754            }
1755            edges
1756        }
1757
1758        fn released_inputs(&mut self) -> Vec<u8> {
1759            core::mem::take(&mut self.releases)
1760        }
1761
1762        fn input_levels(&self) -> Vec<(u8, bool)> {
1763            self.board
1764                .borrow()
1765                .input_levels_on(self.index)
1766                .into_iter()
1767                .filter_map(|(pin, level)| match level {
1768                    Level::High => Some((pin, true)),
1769                    Level::Low => Some((pin, false)),
1770                    Level::HighZ => None,
1771                })
1772                .collect()
1773        }
1774
1775        fn named_pin(&self, name: &str) -> Option<u8> {
1776            let board = self.board.borrow();
1777            let (index, pin) = board.named_pin_on(name)?;
1778            (index == self.index).then_some(pin)
1779        }
1780
1781        /// Every I2C target the board holds, as `(controller, address, device)`.
1782        ///
1783        /// The device boxes share the board rather than taking a device out of
1784        /// it, so `Board` remains the owner and stays usable after attach.
1785        fn i2c_devices(&mut self) -> Vec<(u8, u8, Box<dyn EspI2cDevice>)> {
1786            let board = self.board.borrow();
1787            let mut devices: Vec<(u8, u8)> = Vec::new();
1788            for (&(owner, controller), bus) in &board.buses().i2c {
1789                if owner != self.index {
1790                    continue;
1791                }
1792                for address in bus.addresses() {
1793                    devices.push((controller, address));
1794                }
1795            }
1796            drop(board);
1797            devices
1798                .into_iter()
1799                .map(|(controller, address)| {
1800                    let device: Box<dyn EspI2cDevice> = Box::new(BoardI2cDevice {
1801                        board: Rc::clone(&self.board),
1802                        board_index: self.index,
1803                        controller,
1804                        address,
1805                        written: Vec::new(),
1806                        received: Vec::new(),
1807                        reading: false,
1808                        open: false,
1809                        last_at: 0,
1810                        started_at: 0,
1811                    });
1812                    (controller, address, device)
1813                })
1814                .collect()
1815        }
1816
1817        fn uses_spi_pins(&self) -> bool {
1818            self.board
1819                .borrow()
1820                .buses()
1821                .spi
1822                .keys()
1823                .any(|&(owner, _)| owner == self.index)
1824        }
1825
1826        /// A transaction with no pin route: use the only device on the chip's
1827        /// controller, or the board's only device when the controller numbering
1828        /// differs between the board and the chip (a board names `spi0`, the
1829        /// C3 calls its GP-SPI host 2). No device or an ambiguous one floats.
1830        fn spi_transfer(&mut self, host: u8, tx: &[u8], rx_len: usize) -> Vec<u8> {
1831            let rate = self.spi_rate(host);
1832            let mut board = self.board.borrow_mut();
1833            let selected = board
1834                .buses()
1835                .spi_sole(self.index, host)
1836                .or_else(|| board.buses().spi_only_device(self.index));
1837            match selected {
1838                Some((controller, chip_select)) => {
1839                    // The waveform is reconstructed here, so the rate has to
1840                    // reach the board before the transaction does.
1841                    if let Some(hz) = rate {
1842                        board.set_spi_hz(self.index, controller, hz);
1843                    }
1844                    board.spi_transfer(self.index, controller, chip_select, tx, rx_len)
1845                }
1846                None => vec![0xff; rx_len],
1847            }
1848        }
1849
1850        /// A routed transaction: the asserted chip-select lines select the
1851        /// device, exactly as they do on the board.
1852        fn spi_transfer_pins(
1853            &mut self,
1854            host: u8,
1855            pins: SpiPins,
1856            tx: &[u8],
1857            rx_len: usize,
1858        ) -> Vec<u8> {
1859            let rate = self.spi_rate(host);
1860            let mut board = self.board.borrow_mut();
1861            match board.buses().spi_selected(self.index, pins.cs) {
1862                Some((controller, chip_select)) => {
1863                    if let Some(hz) = rate {
1864                        board.set_spi_hz(self.index, controller, hz);
1865                    }
1866                    board.spi_transfer(self.index, controller, chip_select, tx, rx_len)
1867                }
1868                None => vec![0xff; rx_len],
1869            }
1870        }
1871
1872        fn uses_uart_pins(&self) -> bool {
1873            let board = self.board.borrow();
1874            if board
1875                .buses()
1876                .uart
1877                .keys()
1878                .any(|&(owner, _)| owner == self.index)
1879            {
1880                return true;
1881            }
1882            // A pad wired straight to another chip is a UART link with no
1883            // part on the bus, so the ports have to be watched too.
1884            board.flat().has_chip_to_chip_wire(self.index)
1885        }
1886
1887        /// A byte the chip transmitted reaches the peer on `route.port`. The
1888        /// route names the chip's receive pin, so remember it for `uart_rx`.
1889        fn uart_tx(&mut self, cycle: u64, route: UartRoute, byte: u8) {
1890            let now = self.ns(cycle);
1891            let port = route.port as u8;
1892            let baud = route
1893                .baud
1894                .unwrap_or(litz_board::runtime::OBSERVED_UART_BAUD);
1895            let mut board = self.board.borrow_mut();
1896            board.set_uart_baud(self.index, port, baud);
1897            // The pads are what a wire to another chip is found through.
1898            board.set_uart_pins(self.index, port, route.tx_pins, route.rx_pin);
1899            board.uart_receive(self.index, port, now, &[byte]);
1900            drop(board);
1901            if let Some(pin) = route.rx_pin {
1902                self.uart_routes
1903                    .insert(port, (pin, route.baud.unwrap_or(115_200)));
1904            }
1905        }
1906
1907        /// Bytes the board's UART peers have ready, one input per port. The
1908        /// chip's last route supplies the pin and baud; before the chip has
1909        /// transmitted, the board's resolved wiring names the receive pin and
1910        /// the usual 115 200 baud is assumed. A port with neither is skipped.
1911        fn uart_rx(&mut self, cycle: u64) -> Vec<UartInput> {
1912            let now = self.ns(cycle);
1913            let mut board = self.board.borrow_mut();
1914            for (&port, &(_, baud)) in &self.uart_routes {
1915                board.set_uart_baud(self.index, port, baud);
1916            }
1917            // A port wired to another chip has no bus entry, so the chip's own
1918            // routes are the starting set; a bus-only port is added beside it.
1919            let mut ports: BTreeMap<u8, Option<(u8, u32)>> = self
1920                .uart_routes
1921                .iter()
1922                .map(|(&port, &route)| (port, Some(route)))
1923                .collect();
1924            for &(owner, port) in board.buses().uart.keys() {
1925                if owner != self.index {
1926                    continue;
1927                }
1928                ports.entry(port).or_insert_with(|| {
1929                    board
1930                        .flat()
1931                        .buses
1932                        .uart
1933                        .get(&(self.index, port))
1934                        .map(|bus| (bus.chip_rx, 115_200))
1935                });
1936            }
1937            let mut inputs = Vec::new();
1938            for (port, route) in ports {
1939                let Some((pin, baud)) = route else { continue };
1940                let data = board.uart_poll(self.index, port, now);
1941                if !data.is_empty() {
1942                    inputs.push(UartInput::new(pin, baud, data));
1943                }
1944            }
1945            inputs
1946        }
1947
1948        /// The chip completed a TWAI transmission: put it on the board's shared CAN wire.
1949        /// The node is the board index, so two MCUs on one diagram are distinct endpoints.
1950        fn can_tx(&mut self, _host: u8, frame: &[u8]) {
1951            let Some(frame) = esp_soc::board::CanFrame::decode(frame) else {
1952                return;
1953            };
1954            let mut board = self.board.borrow_mut();
1955            let can = board.buses_mut().can_mut();
1956            can.attach(self.index);
1957            let _ = can.transmit(self.index, board_can_frame(&frame));
1958        }
1959
1960        /// The chip's TWAI receive buffer is empty: hand it the next frame addressed to this
1961        /// board's node. Attaching lazily keeps a CAN-free diagram unchanged; nothing is
1962        /// queued for a board that never drives TWAI.
1963        fn can_take(&mut self, _host: u8) -> Option<Vec<u8>> {
1964            let mut board = self.board.borrow_mut();
1965            let can = board.buses_mut().can_mut();
1966            can.attach(self.index);
1967            let frame = can.take(self.index)?;
1968            // The chip's wire frame holds only the eight classic CAN bytes.
1969            let mut data = [0u8; esp_soc::board::CAN_MAX_DATA];
1970            let len = usize::from(frame.len).min(data.len());
1971            data[..len].copy_from_slice(&frame.data[..len]);
1972            Some(
1973                esp_soc::board::CanFrame {
1974                    id: frame.id,
1975                    extended: frame.extended,
1976                    rtr: frame.rtr || frame.kind == litz_board::bus::CanFrameKind::Remote,
1977                    len: frame.len,
1978                    data,
1979                }
1980                .encode()
1981                .to_vec(),
1982            )
1983        }
1984    }
1985
1986    /// The [`litz_board::Chip`] view of this adapter: what a runner needs, with
1987    /// nothing esp32sim-specific in the signature.
1988    impl<S: Soc> litz_board::Chip for EspChip<S> {
1989        fn info(&self) -> litz_board::ChipInfo {
1990            litz_board::ChipInfo {
1991                name: S::NAME.into(),
1992                cpu_hz: S::CPU_HZ,
1993                flash: litz_board::FlashLayout {
1994                    size: self.flash as u64,
1995                    bootloader: S::BOOTLOADER_OFFSET as u64,
1996                    partition_table: 0x8000,
1997                    app: 0x1_0000,
1998                },
1999            }
2000        }
2001
2002        fn load_image(
2003            &mut self,
2004            kind: litz_board::ImageKind,
2005            offset: u64,
2006            bytes: &[u8],
2007        ) -> Result<(), String> {
2008            match kind {
2009                litz_board::ImageKind::Rom => self.load_rom(bytes),
2010                litz_board::ImageKind::Bootloader => {
2011                    self.bootloader_loaded = true;
2012                    self.write_flash(offset as usize, bytes)
2013                }
2014                _ => self.write_flash(offset as usize, bytes),
2015            }
2016        }
2017
2018        fn set_psram_size(&mut self, bytes: usize) -> Result<(), String> {
2019            EspChip::set_psram_size(self, bytes)
2020        }
2021
2022        fn flash_image(&self) -> Option<Vec<u8>> {
2023            EspChip::flash_image(self).map(<[u8]>::to_vec)
2024        }
2025
2026        fn boot(&mut self) -> Result<u32, String> {
2027            self.powered = self.board_power();
2028            if !self.powered {
2029                // The board is off: the firmware waits for its power pin. The
2030                // images are loaded, so the first powered run boots them.
2031                return Ok(0);
2032            }
2033            if self.bootloader_loaded {
2034                // The bootloader finds the application itself; starting the app
2035                // directly would skip it.
2036                return Ok(0);
2037            }
2038            let app = self.info().flash.app as usize;
2039            self.boot_app(app)
2040        }
2041
2042        fn schedule(&mut self, inputs: Vec<litz_board::Input>) -> Result<(), String> {
2043            let mut text = String::new();
2044            for input in inputs {
2045                match input {
2046                    litz_board::Input::Gpio { at_ns, pin, level } => {
2047                        let seconds = at_ns as f64 / 1e9;
2048                        let bit = u8::from(level == Level::High);
2049                        text.push_str(&format!("{seconds:.6} gpio {pin} {bit}\n"));
2050                    }
2051                    litz_board::Input::Uart { at_ns, bytes } => {
2052                        let seconds = at_ns as f64 / 1e9;
2053                        let text_in = String::from_utf8_lossy(&bytes);
2054                        // The script format appends the newline itself.
2055                        text.push_str(&format!(
2056                            "{seconds:.6} uart0 {}\n",
2057                            text_in.trim_end_matches('\n')
2058                        ));
2059                    }
2060                }
2061            }
2062            if text.is_empty() {
2063                Ok(())
2064            } else {
2065                self.load_script(&text)
2066            }
2067        }
2068
2069        fn run(&mut self, budget_cycles: u64) -> litz_board::RunResult {
2070            if !EspChip::board_power(self) {
2071                if self.powered {
2072                    self.power_off();
2073                }
2074                // Time passes while the board is off; the machine's own clock
2075                // stands still, so account for it here.
2076                let cycles = u128::from(budget_cycles) * 1_000_000_000;
2077                let cpu_hz = u128::from(litz_board::Chip::info(self).cpu_hz.max(1));
2078                self.off_ns = self.off_ns.saturating_add((cycles / cpu_hz) as u64);
2079                return litz_board::RunResult {
2080                    cycles: budget_cycles,
2081                    stop: litz_board::Stop::Idle,
2082                };
2083            }
2084            if !self.powered {
2085                // Power arrived: start the firmware from its reset vector.
2086                if self.boot_after_power().is_err() {
2087                    return litz_board::RunResult {
2088                        cycles: 0,
2089                        stop: litz_board::Stop::Trap,
2090                    };
2091                }
2092                self.powered = true;
2093            }
2094            let stop = match EspChip::run(self, budget_cycles) {
2095                esp_soc::Stop::MaxInsns => litz_board::Stop::Budget,
2096                esp_soc::Stop::Halted => litz_board::Stop::Halted,
2097                esp_soc::Stop::SwReset => litz_board::Stop::Reset,
2098                esp_soc::Stop::Breakpoint(pc) => litz_board::Stop::Breakpoint(pc),
2099                _ => litz_board::Stop::Idle,
2100            };
2101            self.publish_pwm();
2102            litz_board::RunResult {
2103                cycles: budget_cycles,
2104                stop,
2105            }
2106        }
2107
2108        fn seconds(&self) -> f64 {
2109            EspChip::seconds(self)
2110        }
2111
2112        fn write_console(&mut self, bytes: &[u8]) {
2113            // Both interpreters the runner speaks to read their console from
2114            // UART0. Mirroring the bytes onto the USB block as well splits one
2115            // paste across two input paths and the guest sees it twice.
2116            self.write_serial(bytes);
2117        }
2118
2119        fn take_console(&mut self) -> Vec<u8> {
2120            let mut bytes = self.take_uart0();
2121            // The machine's own drain already moved USB output into this
2122            // backlog; a chip without a USB peripheral leaves it empty. A
2123            // build that logs to both consoles sends the same bytes down each,
2124            // so an identical copy is the same console message, not a second
2125            // one.
2126            let usb = core::mem::take(&mut self.machine.console.usb);
2127            if usb != bytes {
2128                bytes.extend(usb);
2129            }
2130            bytes
2131        }
2132
2133        fn state(&self, part: &str) -> Option<PartState> {
2134            EspChip::state(self, part)
2135        }
2136
2137        fn press(&mut self, part: &str, pressed: bool) -> bool {
2138            EspChip::press(self, part, pressed)
2139        }
2140
2141        fn set_control(&mut self, part: &str, value: u16) -> bool {
2142            EspChip::set_control(self, part, value)
2143        }
2144
2145        fn set_named_control(&mut self, part: &str, name: &str, value: &str) -> bool {
2146            EspChip::set_named_control(self, part, name, value)
2147        }
2148
2149        fn part_pin_level(&self, part: &str, pin: Option<&str>) -> Option<Level> {
2150            EspChip::part_pin_level(self, part, pin)
2151        }
2152
2153        fn gpio_level(&self, gpio: u8) -> Option<Level> {
2154            EspChip::gpio_level(self, gpio)
2155        }
2156
2157        fn conflicts(&self) -> Vec<Conflict> {
2158            EspChip::conflicts(self)
2159        }
2160
2161        fn start_trace(&mut self) {
2162            if let Some(board) = self.board.as_ref() {
2163                board.borrow_mut().start_trace();
2164            }
2165        }
2166
2167        fn vcd(&self) -> String {
2168            self.board
2169                .as_ref()
2170                .map(|board| board.borrow().vcd())
2171                .unwrap_or_default()
2172        }
2173
2174        fn break_at(&mut self, pc: u32) {
2175            EspChip::break_at(self, pc);
2176        }
2177
2178        fn registers(&self) -> String {
2179            self.machine.dump_regs()
2180        }
2181
2182        fn report(&mut self) -> Vec<String> {
2183            EspChip::reports(self)
2184        }
2185
2186        fn enable_coverage(&mut self) {
2187            EspChip::enable_coverage(self);
2188        }
2189
2190        fn display(&mut self) -> Option<(u32, u32, Vec<u16>, u64)> {
2191            self.machine.bus.board().display()
2192        }
2193
2194        fn display_version(&mut self) -> u64 {
2195            self.machine.bus.board().display_version()
2196        }
2197
2198        fn save_display(&mut self, path: &std::path::Path) -> Result<(), String> {
2199            crate::screenshot::capture(self, path)
2200        }
2201
2202        fn save_part_display(&mut self, part: &str, path: &std::path::Path) -> Result<(), String> {
2203            let Some(board) = &self.board else {
2204                return Err("this chip is not attached to a board".into());
2205            };
2206            let image = board
2207                .borrow()
2208                .part_framebuffer(part)
2209                .ok_or_else(|| format!("part {part:?} is not a display with a framebuffer"))?;
2210            std::fs::write(path, image.to_png()).map_err(|e| format!("{}: {e}", path.display()))
2211        }
2212
2213        fn sample_heap(&mut self) -> Result<u32, String> {
2214            EspChip::sample_heap(self)
2215        }
2216
2217        fn touch(&mut self, x: u16, y: u16, down: bool) -> Result<(), String> {
2218            let Some(board) = &self.board else {
2219                return Err("this chip is not attached to a board".into());
2220            };
2221            board.borrow_mut().touch_panel(x, y, down)
2222        }
2223
2224        fn start_air_capture(&mut self, path: &std::path::Path) -> Result<(), String> {
2225            EspChip::start_air_capture(self, path)
2226        }
2227
2228        fn start_ethernet_capture(&mut self, path: &std::path::Path) -> Result<(), String> {
2229            EspChip::start_ethernet_capture(self, path)
2230        }
2231
2232        fn attach_host_gateway(&mut self, forwards: &[String]) -> Result<Vec<String>, String> {
2233            #[cfg(not(target_arch = "wasm32"))]
2234            {
2235                if forwards.is_empty() {
2236                    EspChip::attach_host_nat(self, false).map(|()| Vec::new())
2237                } else {
2238                    EspChip::attach_host_forwards(self, forwards, false)
2239                }
2240            }
2241            #[cfg(target_arch = "wasm32")]
2242            {
2243                let _ = forwards;
2244                Err("the browser build has no host sockets".into())
2245            }
2246        }
2247
2248        fn debug_available(&self) -> bool {
2249            use emu_core::Core;
2250            self.machine_ref()
2251                .cores
2252                .first()
2253                .map(|core| {
2254                    let mut names = Vec::new();
2255                    core.regs(&mut names);
2256                    names.iter().any(|(name, _)| *name == "ra")
2257                        && names.iter().any(|(name, _)| *name == "sp")
2258                })
2259                .unwrap_or(false)
2260        }
2261
2262        fn debug_pc(&self) -> Option<u32> {
2263            use emu_core::Core;
2264            self.machine_ref().cores.first().map(|core| core.pc())
2265        }
2266
2267        fn debug_register_file(&self) -> Option<[u32; 33]> {
2268            use emu_core::Core;
2269            let core = self.machine_ref().cores.first()?;
2270            let mut names = Vec::new();
2271            core.regs(&mut names);
2272            if !names.iter().any(|(name, _)| *name == "ra") {
2273                return None;
2274            }
2275            const RV: [&str; 32] = [
2276                "zero", "ra", "sp", "gp", "tp", "t0", "t1", "t2", "s0", "s1", "a0", "a1", "a2",
2277                "a3", "a4", "a5", "a6", "a7", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9",
2278                "s10", "s11", "t3", "t4", "t5", "t6",
2279            ];
2280            let mut file = [0u32; 33];
2281            for (index, want) in RV.iter().enumerate() {
2282                if let Some((_, value)) = names.iter().find(|(name, _)| name == want) {
2283                    file[index] = *value;
2284                }
2285            }
2286            file[32] = core.pc();
2287            Some(file)
2288        }
2289
2290        fn debug_read_memory(&mut self, addr: u32, len: usize) -> Vec<u8> {
2291            if len == 0 {
2292                return Vec::new();
2293            }
2294            let start = addr & !3;
2295            let skip = (addr - start) as usize;
2296            let words = (skip + len).div_ceil(4);
2297            let text = self.machine_mut().peek(start, words);
2298            let mut bytes = Vec::with_capacity(words * 4);
2299            for line in text.lines() {
2300                let Some((_, word)) = line.split_once(": ") else {
2301                    break;
2302                };
2303                let Ok(word) = u32::from_str_radix(word.trim(), 16) else {
2304                    break;
2305                };
2306                bytes.extend_from_slice(&word.to_le_bytes());
2307            }
2308            if bytes.len() < skip {
2309                return Vec::new();
2310            }
2311            let end = (skip + len).min(bytes.len());
2312            bytes[skip..end].to_vec()
2313        }
2314
2315        fn debug_disassemble(&mut self, addr: u32, count: usize) -> String {
2316            self.disassemble(addr, count)
2317        }
2318
2319        fn debug_set_breakpoints(&mut self, pcs: &[u32]) {
2320            self.machine_mut().set_breakpoints(pcs.to_vec());
2321        }
2322
2323        fn debug_step(&mut self) -> Option<litz_board::Stop> {
2324            Some(match self.machine_mut().step_one() {
2325                esp_soc::Stop::MaxInsns => litz_board::Stop::Budget,
2326                esp_soc::Stop::Halted => litz_board::Stop::Halted,
2327                esp_soc::Stop::SwReset => litz_board::Stop::Reset,
2328                esp_soc::Stop::Breakpoint(pc) => litz_board::Stop::Breakpoint(pc),
2329                _ => litz_board::Stop::Idle,
2330            })
2331        }
2332
2333        fn debug(&mut self) -> Option<&mut dyn litz_board::ChipDebug> {
2334            Some(self)
2335        }
2336    }
2337
2338    impl<S: Soc> litz_board::ChipDebug for EspChip<S> {
2339        fn serve(&mut self, port: u16) -> Result<(), String> {
2340            self.gdb_serve(port)
2341        }
2342
2343        fn report(&mut self) -> String {
2344            self.machine.dump_regs()
2345        }
2346    }
2347
2348    #[cfg(all(test, feature = "esp32c3"))]
2349    mod ble_peers {
2350        use super::*;
2351
2352        fn beacon() -> litz_ble::Beacon {
2353            litz_ble::Beacon {
2354                name: Some("late".into()),
2355                services: Vec::new(),
2356                address: [0x04, 0x03, 0x02, 0x01, 0xaa, 0xc4],
2357                rssi: -42,
2358                adv: vec![2, 1, 6, 6, 9, b'l', b'a', b't', b'e'],
2359                scan_response: Vec::new(),
2360                gatt: Vec::new(),
2361            }
2362        }
2363
2364        /// A scan enabled before the peer arrives hears it on the next report.
2365        /// The controller is stood up just far enough for `ble_nearby` to
2366        /// accept a list: firmware assets are not needed to test the list.
2367        #[test]
2368        fn a_peer_added_at_runtime_reaches_a_live_scan() {
2369            let mut chip = C3::new([0x24, 0x0a, 0xc4, 0x00, 0x01, 0x10], 4 << 20);
2370            assert_eq!(
2371                chip.add_ble_peer(&beacon()).unwrap_err(),
2372                "BLE is not enabled on this chip"
2373            );
2374            chip.machine_mut().bus.ble.hooks.push(0);
2375            chip.machine_mut().bus.ble.lines.keep();
2376            chip.ble_attached = true;
2377
2378            // LE Set Scan Enable: enabled, passive.
2379            chip.machine_mut()
2380                .bus
2381                .ble
2382                .session
2383                .send(&[1, 0x0c, 0x20, 2, 1, 0]);
2384            chip.machine_mut().bus.ble.session.drain_log();
2385
2386            chip.add_ble_peer(&beacon())
2387                .expect("the scan accepts the list");
2388            assert_eq!(chip.ble_peers.len(), 1);
2389            let line = chip.ble_log().expect("the controller logged a report");
2390            assert!(line.contains("scan report"), "{line}");
2391            assert!(line.contains("c4:aa:01:02:03:04"), "{line}");
2392        }
2393    }
2394}
2395
2396const PLIC_AND_RV_MAP: [MemoryRegion; 6] = [
2397    MemoryRegion::new("irom", 0x4200_0000, 0x0040_0000),
2398    MemoryRegion::new("drom", 0x3C00_0000, 0x0040_0000),
2399    MemoryRegion::new("dram", 0x3FC8_0000, 0x0004_0000),
2400    MemoryRegion::new("irom-dram", 0x4037_C000, 0x0000_8000),
2401    MemoryRegion::new("peripherals", 0x6000_0000, 0x0010_0000),
2402    MemoryRegion::new("rtc", 0x5000_0000, 0x0001_0000),
2403];