Skip to main content

litz_engine/
machine.rs

1//! Booting a diagram and a set of flash images, with no project directory.
2//!
3//! [`runner`](crate::runner) reads a project's files; a host that already has
4//! the diagram and the images in memory — the browser simulator is one — wants
5//! the same construction without the file system in the way. The sequence is
6//! shared so the two cannot drift: validate the diagram against the builtin
7//! catalog, flatten it into a board, attach the board to the chip, place the
8//! images in flash and either let the second-stage bootloader run or jump
9//! straight to the application.
10//!
11//! [`boot`] chooses the backend from the board's manifest, exactly as the
12//! runner does, so every builtin chip is reachable from an in-memory host.
13//! [`boot_c3`] is the older ESP32-C3-only entry point kept for callers that
14//! named the chip themselves.
15
16use std::cell::RefCell;
17use std::rc::Rc;
18
19use litz_board::{Board, Chip, FlatBoard, ImageKind};
20use litz_catalog::Registry;
21use litz_diagram::Circuit;
22use litz_esp::backend::{C3, C6, P4, S31};
23#[cfg(not(target_family = "wasm"))]
24use litz_esp::backend::{Esp32, S3};
25
26use crate::config::{Runtime, parse_size};
27use crate::image::{FirmwareLayout, detect as detect_layout};
28use crate::python::{PythonRuntime, detect_bytes};
29
30/// The second-stage bootloader's offset in flash.
31const BOOTLOADER_OFFSET: usize = 0x0;
32/// The partition table's offset in flash.
33const PTABLE_OFFSET: usize = 0x8000;
34/// The factory application's offset in flash.
35const APP_OFFSET: usize = 0x1_0000;
36
37/// Espressif's example MAC. Nothing in the simulation is MAC-specific, so a
38/// fixed value keeps two runs byte-identical.
39pub const DEFAULT_MAC: [u8; 6] = [0x24, 0x0a, 0xc4, 0x12, 0x34, 0x56];
40
41/// The images a boot needs. ROM and the bootloader/partition-table pair are
42/// optional; the pair goes together or not at all, because the bootloader
43/// looks the application up through the table.
44pub struct Images<'a> {
45    /// The mask ROM, or an empty slice to let the chip use its own.
46    pub rom: &'a [u8],
47    /// The second-stage bootloader, when the application is not booted bare.
48    pub bootloader: &'a [u8],
49    /// The partition table that names the application's partition.
50    pub partition_table: &'a [u8],
51    /// The application image; required.
52    pub app: &'a [u8],
53}
54
55impl Images<'_> {
56    /// Every image as an owned slice, so a caller can hand the boot code
57    /// borrowed input and still construct the session from its own copies.
58    fn owned(&self) -> OwnedImages {
59        OwnedImages {
60            rom: self.rom.to_vec(),
61            bootloader: self.bootloader.to_vec(),
62            partition_table: self.partition_table.to_vec(),
63            app: self.app.to_vec(),
64        }
65    }
66}
67
68/// What a host can choose about a boot before the diagram is read.
69#[derive(Clone, Debug)]
70pub struct BootOptions {
71    /// Flash size in bytes. `None` uses the board manifest's, then 4 MiB.
72    pub flash_size: Option<usize>,
73    /// The MAC the station reports. The default is stable so runs match.
74    pub mac: [u8; 6],
75    /// Solve the analog network instead of treating every net as digital.
76    pub analog: bool,
77    /// Catalog manifests the host supplies. A browser has no directory to
78    /// load them from, so a custom part or board arrives here.
79    pub manifests: Vec<ManifestText>,
80}
81
82/// One manifest the host supplies, with the board's internal schematic when
83/// the manifest names one and has no directory to resolve it against.
84#[derive(Clone, Debug, Default)]
85pub struct ManifestText {
86    pub toml: String,
87    pub schematic: Option<String>,
88}
89
90impl Default for BootOptions {
91    fn default() -> Self {
92        Self {
93            flash_size: None,
94            mac: DEFAULT_MAC,
95            analog: false,
96            manifests: Vec::new(),
97        }
98    }
99}
100
101/// A booted circuit: the chip that runs it and the board it drives.
102pub struct Booted {
103    pub chip: Box<dyn Chip>,
104    /// The same board the chip was given, kept so a host can ask about parts,
105    /// probes and the display without reaching through the backend.
106    pub board: Rc<RefCell<Board>>,
107    /// The parsed diagram, kept so part enumeration reports the ids the host
108    /// wrote rather than the prefixed ids a board expansion invents.
109    pub circuit: Circuit,
110}
111
112struct OwnedImages {
113    rom: Vec<u8>,
114    bootloader: Vec<u8>,
115    partition_table: Vec<u8>,
116    app: Vec<u8>,
117}
118
119/// What a chip is given besides its own pins: the circuit's network, its
120/// advertisers, and the firmware's symbol table.
121pub(crate) struct Attachments<'a> {
122    pub(crate) network: Option<&'a litz_net::NetworkConfig>,
123    /// A virtual station for a guest in AP mode (`--wifi-sta`), as the
124    /// `ssid=NAME[,psk=PASS][,mac=..]` spec.
125    pub(crate) station: Option<&'a str>,
126    pub(crate) bluetooth: Option<&'a litz_ble::BleConfig>,
127    pub(crate) elf: Option<&'a [u8]>,
128    /// Bring the Bluetooth controller up even when the project asks for no
129    /// beacons: a CircuitPython build initialises it on every boot.
130    pub(crate) ble_controller: bool,
131}
132
133/// The builtin backend a board's `chip` name selects, with the board attached.
134pub(crate) fn builtin_chip(
135    name: &str,
136    mac: [u8; 6],
137    flash: usize,
138    board: Rc<RefCell<litz_board::Board>>,
139    index: u16,
140    attachments: Attachments<'_>,
141) -> Result<Box<dyn Chip>, String> {
142    let Attachments {
143        network,
144        station,
145        bluetooth,
146        elf,
147        ble_controller,
148    } = attachments;
149    // Only a chip with a modelled Wi-Fi MAC can hear the virtual station. The
150    // P4 has the radio block left out of its model, so it is not in this list.
151    if station.is_some()
152        && !matches!(
153            name,
154            "esp32" | "esp32c3" | "esp32c6" | "esp32s3" | "esp32s31"
155        )
156    {
157        return Err(format!(
158            "{name} has no Wi-Fi radio; remove [sim] wifi_sta / --wifi-sta"
159        ));
160    }
161    // A radio is part of the ESP32-family adapters, not of `Chip`; the macro
162    // attaches it before the machine is boxed and erased.
163    macro_rules! esp {
164        ($chip:expr) => {{
165            let mut chip = $chip;
166            if let Some(bytes) = elf {
167                chip = chip.with_elf(bytes)?;
168            }
169            if let Some(config) = network {
170                chip.attach_network(config)?;
171            }
172            if let Some(spec) = station {
173                chip.attach_station(spec)?;
174            }
175            if let Some(config) = bluetooth {
176                chip.attach_ble(config)?;
177            }
178            // A CircuitPython build ships with Bluetooth and brings the
179            // controller up on every boot. With no controller behind the
180            // registers the ROM's init asserts and the interpreter never
181            // reaches its own main loop, so the runtime choice carries the
182            // radio with it. `attach_ble` above still decides what is on air.
183            if ble_controller {
184                chip.enable_full_ble(false)?;
185            }
186            Box::new(chip)
187        }};
188    }
189    Ok(match name {
190        "esp32" => {
191            #[cfg(not(target_family = "wasm"))]
192            {
193                esp!(Esp32::new(mac, flash).with_shared_board(Rc::clone(&board), index))
194            }
195            #[cfg(target_family = "wasm")]
196            {
197                let _ = (mac, flash, &board, index);
198                return Err(xtensa_unavailable("esp32"));
199            }
200        }
201        "esp32c3" => esp!(C3::new(mac, flash).with_shared_board(Rc::clone(&board), index)),
202        "esp32c6" => esp!(C6::new(mac, flash).with_shared_board(Rc::clone(&board), index)),
203        "esp32s3" => {
204            #[cfg(not(target_family = "wasm"))]
205            {
206                esp!(S3::new(mac, flash).with_shared_board(Rc::clone(&board), index))
207            }
208            #[cfg(target_family = "wasm")]
209            {
210                let _ = (mac, flash, &board, index);
211                return Err(xtensa_unavailable("esp32s3"));
212            }
213        }
214        "esp32p4" => esp!(P4::new(mac, flash).with_shared_board(Rc::clone(&board), index)),
215        "esp32s31" => {
216            esp!(S31::new(mac, flash).with_shared_board(Rc::clone(&board), index))
217        }
218        "atmega328p" | "atmega2560" | "atmega32u4" | "attiny85" => {
219            if network.is_some() {
220                return Err(format!("{name} has no Wi-Fi radio; remove [sim] wifi"));
221            }
222            if bluetooth.is_some() {
223                return Err(format!("{name} has no Bluetooth radio; remove the beacon"));
224            }
225            match name {
226                "atmega328p" => {
227                    Box::new(litz_avr::Atmega328p::new().with_shared_board(board, index))
228                }
229                "atmega2560" => {
230                    Box::new(litz_avr::Atmega2560::new().with_shared_board(board, index))
231                }
232                "atmega32u4" => {
233                    Box::new(litz_avr::Atmega32u4::new().with_shared_board(board, index))
234                }
235                _ => Box::new(litz_avr::Attiny85::new().with_shared_board(board, index)),
236            }
237        }
238        "rp2040" => {
239            if network.is_some() {
240                return Err("rp2040 has no radio; remove [sim] wifi".into());
241            }
242            if bluetooth.is_some() {
243                return Err("rp2040 has no Bluetooth radio; remove the beacon".into());
244            }
245            Box::new(litz_rp::Rp2040::new().with_shared_board(board, index))
246        }
247        "rp2350" => {
248            if network.is_some() {
249                return Err("rp2350 has no radio; remove [sim] wifi".into());
250            }
251            if bluetooth.is_some() {
252                return Err("rp2350 has no Bluetooth radio; remove the beacon".into());
253            }
254            Box::new(litz_rp2350::Rp2350::new().with_shared_board(board, index))
255        }
256        "stc89c52" => {
257            if network.is_some() {
258                return Err("stc89c52 has no radio; remove [sim] wifi".into());
259            }
260            if bluetooth.is_some() {
261                return Err("stc89c52 has no Bluetooth radio; remove the beacon".into());
262            }
263            Box::new(litz_8051::Stc89c52::new().with_shared_board(board, index))
264        }
265        "ch32v003" => {
266            if network.is_some() {
267                return Err("ch32v003 has no radio; remove [sim] wifi".into());
268            }
269            if bluetooth.is_some() {
270                return Err("ch32v003 has no Bluetooth radio; remove the beacon".into());
271            }
272            Box::new(litz_ch32v003::Ch32v003::new().with_shared_board(board, index))
273        }
274        other => return Err(format!("chip {other:?} is not built in")),
275    })
276}
277
278/// Why an Xtensa board cannot boot in the zero-import browser build.
279#[cfg(target_family = "wasm")]
280fn xtensa_unavailable(name: &str) -> String {
281    format!(
282        "{name} runs on the Xtensa core, which executes guest blocks through a host JIT; \
283         the browser module has no imports, so use a RISC-V or 8/16-bit part or \
284         run this diagram with the CLI"
285    )
286}
287
288/// The board instance a diagram boots, with its manifest.
289fn find_board<'a>(
290    circuit: &Circuit,
291    registry: &'a Registry,
292) -> Result<&'a litz_catalog::BoardInfo, String> {
293    let mut found: Vec<(&str, &litz_catalog::BoardInfo)> = Vec::new();
294    for part in &circuit.parts {
295        let Some(manifest) = registry.get(&part.type_key) else {
296            continue;
297        };
298        if let Some(info) = manifest.board.as_ref() {
299            found.push((part.id.as_str(), info));
300        }
301    }
302    match found.as_slice() {
303        [] => Err("the diagram has no development board".into()),
304        [(_, info)] => Ok(info),
305        [first, rest @ ..] => {
306            let mut ids = vec![first.0];
307            ids.extend(rest.iter().map(|(id, _)| *id));
308            Err(format!(
309                "the diagram has {} boards ({}); an in-memory session runs one",
310                ids.len(),
311                ids.join(", ")
312            ))
313        }
314    }
315}
316
317/// Boot whatever chip the diagram's board names.
318///
319/// The images are copied before this returns, so the caller keeps ownership of
320/// its buffers. A merged ESP image is recognised and written at the
321/// bootloader offset, the way the runner does it; a bare application goes at
322/// the chip's own application offset.
323pub fn boot(diagram: &str, images: Images<'_>, options: &BootOptions) -> Result<Booted, String> {
324    let images = images.owned();
325    if images.app.is_empty() {
326        return Err("no application image: app_len is 0".into());
327    }
328
329    let mut registry = Registry::builtin();
330    for manifest in &options.manifests {
331        let id = registry
332            .insert_text(&manifest.toml)
333            .map_err(|error| format!("catalog manifest: {error}"))?;
334        if let Some(schematic) = &manifest.schematic {
335            registry.set_schematic(&id, schematic.as_str());
336        }
337    }
338    let circuit = Circuit::from_json(diagram).map_err(|e| e.to_string())?;
339    let info = find_board(&circuit, &registry)?;
340    let simulator = info.simulator.clone();
341    let name = info.chip.as_deref().unwrap_or("esp32c3").to_string();
342    let flash_size = options
343        .flash_size
344        .or_else(|| {
345            info.flash_size
346                .as_deref()
347                .and_then(|text| parse_size(text).ok())
348        })
349        .unwrap_or(4 * 1024 * 1024);
350
351    let flat = FlatBoard::build(&circuit, &registry).map_err(|e| e.to_string())?;
352    let mut board = Board::new(flat)
353        .map_err(|e| e.to_string())?
354        .with_analog(options.analog);
355    // Radios belong to the circuit's parts, so the chip is attached to the
356    // network and the beacons the diagram already describes.
357    let network = board.network().cloned();
358    let bluetooth = board.bluetooth().cloned();
359    if let Some(config) = network.clone() {
360        board.set_network(config);
361    }
362    let shared = Rc::new(RefCell::new(board));
363
364    let mut chip: Box<dyn Chip> = if let Some(simulator) = &simulator {
365        #[cfg(target_arch = "wasm32")]
366        {
367            Box::new(litz_board::host::HostChip::open(
368                &simulator.module,
369                Rc::clone(&shared),
370                0,
371            )?)
372        }
373        #[cfg(not(target_arch = "wasm32"))]
374        {
375            let _ = simulator;
376            return Err(
377                "this board runs a wasm guest chip, which an in-memory session does not host; \
378                 install the board and run it from a project instead"
379                    .into(),
380            );
381        }
382    } else {
383        let python = detect_bytes(Runtime::Native, &images.app);
384        let mut chip = builtin_chip(
385            &name,
386            options.mac,
387            flash_size,
388            Rc::clone(&shared),
389            0,
390            Attachments {
391                network: network.as_ref(),
392                station: None,
393                bluetooth: bluetooth.as_ref(),
394                elf: None,
395                ble_controller: python == PythonRuntime::CircuitPython,
396            },
397        )?;
398        if info.psram {
399            chip.set_psram_size(4 << 20)?;
400        }
401        chip
402    };
403
404    if !images.rom.is_empty() {
405        chip.load_image(ImageKind::Rom, 0, &images.rom)?;
406    }
407    let flash = chip.info().flash;
408    match (
409        images.bootloader.is_empty(),
410        images.partition_table.is_empty(),
411    ) {
412        (false, false) => {
413            chip.load_image(ImageKind::Bootloader, flash.bootloader, &images.bootloader)?;
414            chip.load_image(
415                ImageKind::PartitionTable,
416                flash.partition_table,
417                &images.partition_table,
418            )?;
419            chip.load_image(ImageKind::Firmware, flash.app, &images.app)?;
420        }
421        (true, true) => {
422            // A chip whose application is not at an ESP-IDF offset has no
423            // merged form to detect: the whole file is the application.
424            let merged = flash.app > 0
425                && detect_layout(&images.app).unwrap_or(FirmwareLayout::Application)
426                    == FirmwareLayout::Merged;
427            if merged {
428                chip.load_image(ImageKind::Bootloader, flash.bootloader, &images.app)?;
429            } else {
430                chip.load_image(ImageKind::Firmware, flash.app, &images.app)?;
431            }
432        }
433        _ => {
434            return Err("bootloader and partition table must be supplied together".into());
435        }
436    }
437    chip.boot()?;
438
439    Ok(Booted {
440        chip,
441        board: shared,
442        circuit,
443    })
444}
445
446/// Build a board and an ESP32-C3 wired to it, then place `images` in flash.
447///
448/// Kept for callers that know the chip is a C3; [`boot`] is the entry point
449/// that reads the chip from the diagram.
450pub fn boot_c3(
451    diagram: &str,
452    images: Images<'_>,
453    flash_size: usize,
454    mac: [u8; 6],
455) -> Result<(C3, Circuit), String> {
456    if images.app.is_empty() {
457        return Err("no application image: app_len is 0".into());
458    }
459
460    let registry = Registry::builtin();
461    let circuit = Circuit::from_json(diagram).map_err(|e| e.to_string())?;
462    require_c3(&circuit, &registry)?;
463    let flat = FlatBoard::build(&circuit, &registry).map_err(|e| e.to_string())?;
464    let board = Board::new(flat).map_err(|e| e.to_string())?;
465
466    let mut mcu = C3::new(mac, flash_size).with_board(board);
467    if !images.rom.is_empty() {
468        mcu.load_rom(images.rom)?;
469    }
470
471    match (
472        images.bootloader.is_empty(),
473        images.partition_table.is_empty(),
474    ) {
475        (true, true) => {
476            // No bootloader: start the app the way one would.
477            mcu.write_flash(APP_OFFSET, images.app)?;
478            mcu.boot_app(APP_OFFSET)?;
479        }
480        (false, false) => {
481            mcu.write_flash(BOOTLOADER_OFFSET, images.bootloader)?;
482            mcu.write_flash(PTABLE_OFFSET, images.partition_table)?;
483            mcu.write_flash(APP_OFFSET, images.app)?;
484        }
485        _ => {
486            return Err("bootloader and partition table must be supplied together".into());
487        }
488    }
489
490    Ok((mcu, circuit))
491}
492
493/// Reject a diagram whose board is not the chip this boot path builds.
494fn require_c3(circuit: &Circuit, registry: &Registry) -> Result<(), String> {
495    let board = circuit
496        .parts
497        .iter()
498        .find(|p| {
499            registry
500                .get(&p.type_key)
501                .and_then(|m| m.board.as_ref())
502                .is_some()
503        })
504        .ok_or("the diagram has no development board")?;
505    let info = registry
506        .get(&board.type_key)
507        .and_then(|m| m.board.as_ref())
508        .expect("filtered above");
509    let chip = info.chip.as_deref().unwrap_or("");
510    if chip != "esp32c3" {
511        return Err(format!(
512            "chip {chip:?} is not built by this boot path; only esp32c3 is supported"
513        ));
514    }
515    Ok(())
516}
517
518/// One development board's images for [`boot_fleet`]. A host that runs a
519/// multi-board diagram names each board's instance id and boots every chip
520/// against the same flattened circuit.
521pub struct BoardImage<'a> {
522    /// The `diagram.json` instance id. `None` matches boards by position.
523    pub id: Option<&'a str>,
524    pub app: &'a [u8],
525    pub rom: &'a [u8],
526    pub bootloader: &'a [u8],
527    pub partition_table: &'a [u8],
528    pub flash_size: Option<usize>,
529    pub mac: Option<[u8; 6]>,
530}
531
532/// The chips a multi-board circuit runs, with the board they share and the
533/// ids of the development board instances in diagram order.
534pub struct BootedFleet {
535    pub chips: Vec<Box<dyn Chip>>,
536    pub board: Rc<RefCell<Board>>,
537    pub circuit: Circuit,
538    pub ids: Vec<String>,
539}
540
541/// Every development board instance the diagram names, in part order.
542fn find_boards<'a>(
543    circuit: &'a Circuit,
544    registry: &'a Registry,
545) -> Result<Vec<(&'a str, &'a litz_catalog::BoardInfo)>, String> {
546    let mut found = Vec::new();
547    for part in &circuit.parts {
548        let Some(manifest) = registry.get(&part.type_key) else {
549            continue;
550        };
551        if let Some(info) = manifest.board.as_ref() {
552            found.push((part.id.as_str(), info));
553        }
554    }
555    if found.is_empty() {
556        return Err("the diagram has no development board".into());
557    }
558    Ok(found)
559}
560
561/// Boot one chip per development board, all attached to one shared circuit.
562///
563/// This is the in-memory counterpart of the native runner's fleet: every board
564/// gets its own images and its own index into the flattened board, so a wire
565/// between two boards is an ordinary net both chips drive.
566pub fn boot_fleet(
567    diagram: &str,
568    images: &[BoardImage<'_>],
569    options: &BootOptions,
570) -> Result<BootedFleet, String> {
571    let mut registry = Registry::builtin();
572    for manifest in &options.manifests {
573        let id = registry
574            .insert_text(&manifest.toml)
575            .map_err(|error| format!("catalog manifest: {error}"))?;
576        if let Some(schematic) = &manifest.schematic {
577            registry.set_schematic(&id, schematic.as_str());
578        }
579    }
580    let circuit = Circuit::from_json(diagram).map_err(|e| e.to_string())?;
581    let boards = find_boards(&circuit, &registry)?;
582    if images.is_empty() {
583        return Err("no application image: app_len is 0".into());
584    }
585    if images.len() != boards.len() {
586        return Err(format!(
587            "the diagram has {} development boards but {} images were supplied",
588            boards.len(),
589            images.len()
590        ));
591    }
592    let named = images.iter().any(|image| image.id.is_some());
593    if named && images.iter().any(|image| image.id.is_none()) {
594        return Err("boot images must either all name a board id or all omit it".into());
595    }
596    if named {
597        for (id, _) in &boards {
598            if !images.iter().any(|image| image.id == Some(*id)) {
599                return Err(format!("board {id:?} has no boot image"));
600            }
601        }
602    }
603
604    let flat = FlatBoard::build(&circuit, &registry).map_err(|e| e.to_string())?;
605    let mut board = Board::new(flat)
606        .map_err(|e| e.to_string())?
607        .with_analog(options.analog);
608    let network = board.network().cloned();
609    let bluetooth = board.bluetooth().cloned();
610    if let Some(config) = network.clone() {
611        board.set_network(config);
612    }
613    let shared = Rc::new(RefCell::new(board));
614
615    let mut chips: Vec<Box<dyn Chip>> = Vec::with_capacity(boards.len());
616    for (index, (id, info)) in boards.iter().enumerate() {
617        let image = if named {
618            images
619                .iter()
620                .find(|image| image.id == Some(*id))
621                .expect("checked above")
622        } else {
623            &images[index]
624        };
625        let name = info.chip.as_deref().unwrap_or("esp32c3").to_string();
626        let flash_size = image
627            .flash_size
628            .or_else(|| {
629                info.flash_size
630                    .as_deref()
631                    .and_then(|text| parse_size(text).ok())
632            })
633            .unwrap_or(4 * 1024 * 1024);
634        let mut chip: Box<dyn Chip> = if let Some(simulator) = &info.simulator {
635            #[cfg(target_arch = "wasm32")]
636            {
637                Box::new(litz_board::host::HostChip::open(
638                    &simulator.module,
639                    Rc::clone(&shared),
640                    index as u16,
641                )?)
642            }
643            #[cfg(not(target_arch = "wasm32"))]
644            {
645                let _ = simulator;
646                return Err(
647                    "this board runs a wasm guest chip, which an in-memory session does not host; \
648                     install the board and run it from a project instead"
649                        .into(),
650                );
651            }
652        } else {
653            // A fleet boots each image independently, so each board's runtime is
654            // read from its own bytes. CircuitPython initializes the Bluetooth
655            // controller on boot and stalls without it, whether the session has
656            // one board or several.
657            let python = detect_bytes(Runtime::Native, image.app);
658            let mut chip = builtin_chip(
659                &name,
660                image.mac.unwrap_or(options.mac),
661                flash_size,
662                Rc::clone(&shared),
663                index as u16,
664                Attachments {
665                    network: network.as_ref(),
666                    station: None,
667                    bluetooth: bluetooth.as_ref(),
668                    elf: None,
669                    ble_controller: python == PythonRuntime::CircuitPython,
670                },
671            )?;
672            if info.psram {
673                chip.set_psram_size(4 << 20)?;
674            }
675            chip
676        };
677
678        if !image.rom.is_empty() {
679            chip.load_image(ImageKind::Rom, 0, image.rom)?;
680        }
681        let flash = chip.info().flash;
682        match (
683            image.bootloader.is_empty(),
684            image.partition_table.is_empty(),
685        ) {
686            (false, false) => {
687                chip.load_image(ImageKind::Bootloader, flash.bootloader, image.bootloader)?;
688                chip.load_image(
689                    ImageKind::PartitionTable,
690                    flash.partition_table,
691                    image.partition_table,
692                )?;
693                chip.load_image(ImageKind::Firmware, flash.app, image.app)?;
694            }
695            (true, true) => {
696                if image.app.is_empty() {
697                    // A wasm MCU may carry its own program.
698                    chip.boot()?;
699                } else {
700                    let merged = flash.app > 0
701                        && detect_layout(image.app).unwrap_or(FirmwareLayout::Application)
702                            == FirmwareLayout::Merged;
703                    if merged {
704                        chip.load_image(ImageKind::Bootloader, flash.bootloader, image.app)?;
705                    } else {
706                        chip.load_image(ImageKind::Firmware, flash.app, image.app)?;
707                    }
708                    chip.boot()?;
709                }
710            }
711            _ => {
712                return Err("bootloader and partition table must be supplied together".into());
713            }
714        }
715        chips.push(chip);
716    }
717
718    let ids = boards.iter().map(|(id, _)| (*id).to_string()).collect();
719    Ok(BootedFleet {
720        chips,
721        board: shared,
722        circuit,
723        ids,
724    })
725}