rem100 0.1.0

Rust library and command-line utility for the Dediprog EM100Pro SPI flash emulator
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
//! rem100 - EM100Pro SPI flash emulator command-line utility
//!
//! A Rust port of the em100 utility for controlling the Dediprog EM100Pro
//! SPI flash emulator hardware.

use clap::Parser;
use em100::chips::ChipDatabase;
use em100::device::{Em100, HoldPinState, list_devices};
use em100::download::update_all_files;
use em100::firmware::{firmware_dump, firmware_update};
use em100::image::autocorrect_image;
use em100::trace::{self, TraceState};
use std::fs::File;
use std::io::{Read, Write};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

/// EM100Pro command-line utility
#[derive(Parser, Debug)]
#[command(name = "rem100")]
#[command(author = "Google Inc., Rust port contributors")]
#[command(version = "0.1.0")]
#[command(about = "EM100Pro SPI flash emulator command-line utility")]
#[command(
    long_about = "A Rust port of the em100 utility for controlling the Dediprog EM100Pro SPI flash emulator hardware.

Example:
  rem100 --stop --set M25P80 -d file.bin -v --start -t -O 0xfff00000"
)]
struct Args {
    /// Select chip emulation
    #[arg(short = 'c', long = "set")]
    chip: Option<String>,

    /// Download FILE into EM100pro
    #[arg(short = 'd', long = "download")]
    download: Option<String>,

    /// Start address for download (e.g., -a 0x300000)
    #[arg(short = 'a', long = "start-address")]
    start_address: Option<String>,

    /// Force 3 or 4 byte address mode
    #[arg(short = 'm', long = "address-mode")]
    address_mode: Option<u8>,

    /// Upload from EM100pro into FILE
    #[arg(short = 'u', long = "upload")]
    upload: Option<String>,

    /// Start emulation
    #[arg(short = 'r', long = "start")]
    start: bool,

    /// Stop emulation
    #[arg(short = 's', long = "stop")]
    stop: bool,

    /// Verify EM100 content matches the file
    #[arg(short = 'v', long = "verify")]
    verify: bool,

    /// Enable trace mode
    #[arg(short = 't', long = "trace")]
    trace: bool,

    /// Address offset for trace mode (hex)
    #[arg(short = 'O', long = "offset")]
    offset: Option<String>,

    /// Enable terminal mode
    #[arg(short = 'T', long = "terminal")]
    terminal: bool,

    /// Enable trace console mode
    #[arg(short = 'R', long = "traceconsole")]
    traceconsole: bool,

    /// Length of buffer for traceconsole mode (hex)
    #[arg(short = 'L', long = "length")]
    length: Option<String>,

    /// Brief mode for traces
    #[arg(short = 'b', long = "brief")]
    brief: bool,

    /// Update EM100pro firmware (dangerous). Use "auto" for automatic update.
    #[arg(short = 'F', long = "firmware-update")]
    firmware_update: Option<String>,

    /// Export raw EM100pro firmware to file
    #[arg(short = 'f', long = "firmware-dump")]
    firmware_dump: Option<String>,

    /// Export EM100pro firmware to DPFW file
    #[arg(short = 'g', long = "firmware-write")]
    firmware_write: Option<String>,

    /// Set serial number
    #[arg(short = 'S', long = "set-serialno")]
    set_serialno: Option<String>,

    /// Switch FPGA voltage (1.8 or 3.3) - obsolete
    #[arg(short = 'P', long = "set-voltage")]
    set_voltage: Option<String>,

    /// Set hold pin state (LOW, FLOAT, INPUT)
    #[arg(short = 'p', long = "holdpin")]
    holdpin: Option<String>,

    /// Use EM100pro on USB bus:device or serial number (e.g., 001:003 or EM123456)
    #[arg(short = 'x', long = "device")]
    device: Option<String>,

    /// List all connected EM100pro devices
    #[arg(short = 'l', long = "list-devices")]
    list_devices: bool,

    /// Update device (chip) and firmware database
    #[arg(short = 'U', long = "update-files")]
    update_files: bool,

    /// Enable compatibility mode (patch image for EM100Pro)
    #[arg(short = 'C', long = "compatible")]
    compatible: bool,

    /// Print debug information
    #[arg(short = 'D', long = "debug")]
    debug: bool,
}

fn parse_hex(s: &str) -> Option<u64> {
    let s = s.trim();
    if let Some(hex) = s.strip_prefix("0x").or_else(|| s.strip_prefix("0X")) {
        u64::from_str_radix(hex, 16).ok()
    } else {
        s.parse().ok()
    }
}

fn parse_device(s: &str) -> (Option<u8>, Option<u8>, Option<u32>) {
    let s = s.to_uppercase();
    if s.starts_with("DP") || s.starts_with("EM") {
        // Serial number
        if let Ok(serial) = s[2..].parse::<u32>() {
            return (None, None, Some(serial));
        }
    } else if s.contains(':') {
        // Bus:device
        let parts: Vec<&str> = s.split(':').collect();
        if parts.len() == 2 {
            if let (Ok(bus), Ok(dev)) = (parts[0].parse::<u8>(), parts[1].parse::<u8>()) {
                return (Some(bus), Some(dev), None);
            }
        }
    }
    (None, None, None)
}

fn main() {
    let args = Args::parse();

    // Handle --list-devices
    if args.list_devices {
        match list_devices() {
            Ok(devices) => {
                if devices.is_empty() {
                    println!("No EM100pro devices found.");
                } else {
                    for (bus, dev, serial) in devices {
                        println!(" Bus {:03} Device {:03}: EM100pro {}", bus, dev, serial);
                    }
                }
            }
            Err(e) => {
                eprintln!("Error listing devices: {}", e);
                std::process::exit(1);
            }
        }
        return;
    }

    // Handle --update-files
    if args.update_files {
        if let Err(e) = update_all_files() {
            eprintln!("Error updating files: {}", e);
            std::process::exit(1);
        }
        return;
    }

    // Parse device selection
    let (bus, device, serial) = args
        .device
        .as_ref()
        .map(|d| parse_device(d))
        .unwrap_or((None, None, None));

    // Open device
    let mut em100 = match Em100::open(bus, device, serial) {
        Ok(em100) => em100,
        Err(e) => {
            eprintln!("Error: {}", e);
            std::process::exit(1);
        }
    };

    // Load chip database
    let chip_db = ChipDatabase::load().ok();

    // Setup chips if requested
    let chip = if let Some(chip_name) = &args.chip {
        match chip_db.as_ref() {
            Some(db) => match db.find_chip(chip_name) {
                Ok(chip) => Some(chip),
                Err(_) => {
                    println!("Supported chips:\n");
                    for chip in db.list_chips() {
                        println!("  - {} {}", chip.vendor, chip.name);
                    }
                    println!(
                        "\nCould not find a chip matching '{}' to be emulated.",
                        chip_name
                    );
                    std::process::exit(1);
                }
            },
            None => {
                eprintln!("Can't find chip configs. Please run: rem100 --update-files");
                std::process::exit(1);
            }
        }
    } else {
        None
    };

    // Set up signal handler
    let exit_requested = Arc::new(AtomicBool::new(false));
    let exit_clone = exit_requested.clone();
    ctrlc::set_handler(move || {
        exit_clone.store(true, Ordering::SeqCst);
    })
    .ok();

    // Print device info
    em100.print_info();
    if let Some(db) = &chip_db {
        println!("SPI flash database: {}", db.version);
    }

    // Print current state
    match em100.get_state() {
        Ok(running) => println!(
            "EM100Pro currently {}",
            if running { "running" } else { "stopped" }
        ),
        Err(_) => println!("EM100Pro state unknown"),
    }

    if let Ok(state) = em100.get_hold_pin_state() {
        println!("EM100Pro hold pin currently {}", state)
    }
    println!();

    // Debug mode
    if args.debug {
        if let Err(e) = em100.debug() {
            eprintln!("Debug error: {}", e);
        }
    }

    // Firmware update
    if let Some(firmware_in) = &args.firmware_update {
        if let Err(e) = firmware_update(&em100, firmware_in, args.verify) {
            eprintln!("Firmware update error: {}", e);
            std::process::exit(1);
        }
        return;
    }

    // Firmware dump
    if let Some(firmware_out) = &args.firmware_dump {
        if let Err(e) = firmware_dump(&em100, firmware_out, false) {
            eprintln!("Firmware dump error: {}", e);
            std::process::exit(1);
        }
        return;
    }

    // Firmware write (DPFW format)
    if let Some(firmware_out) = &args.firmware_write {
        if let Err(e) = firmware_dump(&em100, firmware_out, true) {
            eprintln!("Firmware write error: {}", e);
            std::process::exit(1);
        }
        return;
    }

    // Set serial number
    if let Some(serialno) = &args.set_serialno {
        let mut s = serialno.as_str();
        if s.to_uppercase().starts_with("DP") || s.to_uppercase().starts_with("EM") {
            s = &s[2..];
        }
        match s.parse::<u32>() {
            Ok(serial) => {
                if let Err(e) = em100.set_serial_no(serial) {
                    eprintln!("Error setting serial number: {}", e);
                    std::process::exit(1);
                }
            }
            Err(_) => {
                eprintln!("Error: Can't parse serial number '{}'", serialno);
                std::process::exit(1);
            }
        }
        return;
    }

    // Stop emulation
    if args.stop {
        if let Err(e) = em100.set_state(false) {
            eprintln!("Error stopping emulation: {}", e);
        } else {
            println!("Stopped EM100Pro");
        }
    }

    // Set chip type
    if let Some(chip) = &chip {
        println!("Configuring SPI flash chip emulation.");
        if let Err(e) = em100.set_chip_type(chip) {
            eprintln!("Failed configuring chip type: {}", e);
            std::process::exit(1);
        }
        println!("Chip set to {} {}.", chip.vendor, chip.name);

        // Auto-enable 4-byte mode for large chips
        if args.address_mode.is_none() && chip.size > 16 * 1024 * 1024 {
            if let Err(e) = em100.set_address_mode(4) {
                eprintln!("Warning: {}", e);
            } else {
                println!("Enabled 4 byte address mode");
            }
        }
    }

    // Set address mode
    if let Some(mode) = args.address_mode {
        if let Err(e) = em100.set_address_mode(mode) {
            eprintln!("Error: {}", e);
            std::process::exit(1);
        }
        println!("Enabled {} byte address mode", mode);
    }

    // Set voltage (obsolete)
    if let Some(voltage) = &args.set_voltage {
        let voltage_code = match voltage.as_str() {
            "3.3" => 33,
            "1.8" => 18,
            _ => {
                eprintln!("Invalid voltage, use 1.8 or 3.3.");
                std::process::exit(1);
            }
        };

        println!("Setting the voltage on the command line is known to cause problems.");
        println!("Please report to the coreboot mailing list why this is necessary.");

        if args.debug {
            println!("Setting anyways on your own risk (debug mode enabled)");
            if em100.set_fpga_voltage(voltage_code).is_err() {
                eprintln!("Failed configuring FPGA voltage.");
                std::process::exit(1);
            }
        }
    }

    // Set hold pin
    if let Some(holdpin) = &args.holdpin {
        match holdpin.parse::<HoldPinState>() {
            Ok(state) => {
                if let Err(e) = em100.set_hold_pin_state(state) {
                    eprintln!("Failed configuring hold pin state: {}", e);
                    std::process::exit(1);
                }
                println!("Hold pin state set to {}", state);
            }
            Err(e) => {
                eprintln!("{}", e);
                std::process::exit(1);
            }
        }
    }

    // Upload from device
    if let Some(upload_file) = &args.upload {
        let maxlen = chip.as_ref().map(|c| c.size as usize).unwrap_or(0x4000000);

        match em100.upload(0, maxlen) {
            Ok(data) => {
                let mut file = match File::create(upload_file) {
                    Ok(f) => f,
                    Err(e) => {
                        eprintln!("Could not open download file: {}", e);
                        std::process::exit(1);
                    }
                };
                if let Err(e) = file.write_all(&data) {
                    eprintln!("Error writing file: {}", e);
                    std::process::exit(1);
                }
            }
            Err(e) => {
                eprintln!("Upload error: {}", e);
                std::process::exit(1);
            }
        }
    }

    // Download to device
    if let Some(download_file) = &args.download {
        let spi_start_address = args
            .start_address
            .as_ref()
            .and_then(|s| parse_hex(s))
            .unwrap_or(0) as u32;

        if spi_start_address != 0 {
            println!("SPI address: 0x{:08x}", spi_start_address);
        }

        let maxlen = chip.as_ref().map(|c| c.size as usize).unwrap_or(0x4000000);

        let mut file = match File::open(download_file) {
            Ok(f) => f,
            Err(e) => {
                eprintln!("Can't open file '{}': {}", download_file, e);
                std::process::exit(1);
            }
        };

        let mut data = Vec::new();
        if let Err(e) = file.read_to_end(&mut data) {
            eprintln!("Error reading file: {}", e);
            std::process::exit(1);
        }

        if data.is_empty() {
            eprintln!("FATAL: No file to upload.");
            std::process::exit(1);
        }

        if data.len() > maxlen {
            eprintln!("FATAL: file size exceeds maximum");
            std::process::exit(1);
        }

        // When a chip is specified, validate that file size matches expected size
        if chip.is_some() {
            let expected_size = maxlen - spi_start_address as usize;
            if data.len() != expected_size {
                eprintln!(
                    "FATAL: file size ({}) does not match chip size minus start address ({}).",
                    data.len(),
                    expected_size
                );
                std::process::exit(1);
            }
        }

        // Apply image auto-correction if requested
        if args.compatible {
            autocorrect_image(&em100, &mut data).ok();
        }

        // Handle start address
        if spi_start_address != 0 {
            // Read existing data and merge
            match em100.upload(0, maxlen) {
                Ok(mut existing) => {
                    let start = spi_start_address as usize;
                    let end = start + data.len();
                    if end <= existing.len() {
                        existing[start..end].copy_from_slice(&data);
                        if let Err(e) = em100.download(&existing, 0) {
                            eprintln!("Download error: {}", e);
                            std::process::exit(1);
                        }
                    }
                }
                Err(e) => {
                    eprintln!("SDRAM readback failed: {}", e);
                    std::process::exit(1);
                }
            }
        } else if let Err(e) = em100.download(&data, 0) {
            eprintln!("Download error: {}", e);
            std::process::exit(1);
        }

        // Verify
        if args.verify {
            match em100.upload(spi_start_address, data.len()) {
                Ok(readback) => {
                    if readback == data {
                        println!("Verify: PASS");
                    } else {
                        println!("Verify: FAIL");
                        std::process::exit(1);
                    }
                }
                Err(e) => {
                    eprintln!("Verification error: {}", e);
                    std::process::exit(1);
                }
            }
        }
    }

    // Start emulation
    if args.start {
        if let Err(e) = em100.set_state(true) {
            eprintln!("Error starting emulation: {}", e);
        } else {
            println!("Started EM100Pro");
        }
    }

    // Trace/terminal mode
    if args.trace || args.terminal || args.traceconsole {
        const MAX_USB_ERRORS: u32 = 10;

        // Set hold pin to input if not explicitly set
        if args.holdpin.is_none() {
            if let Err(e) = em100.set_hold_pin_state(HoldPinState::Input) {
                eprintln!("Error: Failed to set EM100 to input: {}", e);
                std::process::exit(1);
            }
        }

        // Start emulation if not explicitly started or stopped
        if !args.start && !args.stop {
            em100.set_state(true).ok();
        }

        print!("Starting ");

        if args.trace || args.traceconsole {
            trace::reset_spi_trace(&em100).ok();
            print!("trace{}", if args.terminal { " & " } else { "" });
        }

        if args.terminal {
            trace::init_spi_terminal(&em100).ok();
            print!("terminal");
        }

        println!(". Press CTRL-C to exit.\n");
        std::io::stdout().flush().ok();

        let address_offset = args.offset.as_ref().and_then(|s| parse_hex(s)).unwrap_or(0);

        if address_offset != 0 {
            println!("Address offset: 0x{:08x}", address_offset);
        }

        let address_length = args.length.as_ref().and_then(|s| parse_hex(s)).unwrap_or(0);

        let mut trace_state = TraceState::new(args.brief, args.address_mode.unwrap_or(3));
        let mut usb_errors = 0u32;

        while !exit_requested.load(Ordering::SeqCst) && usb_errors < MAX_USB_ERRORS {
            let ret = if args.traceconsole {
                trace::read_spi_trace_console(
                    &em100,
                    &mut trace_state,
                    address_offset,
                    address_length,
                )
            } else if args.trace {
                trace::read_spi_trace(&em100, &mut trace_state, args.terminal, address_offset)
            } else if args.terminal {
                trace::read_spi_terminal(&em100, false)
            } else {
                Ok(true)
            };

            match ret {
                Ok(false) => usb_errors += 1,
                Err(_) => break,
                _ => {}
            }
        }

        if usb_errors >= MAX_USB_ERRORS {
            eprintln!("Error: Bailed out with too many USB errors.");
        }

        // Stop emulation if not explicitly started or stopped
        if !args.start && !args.stop {
            em100.set_state(false).ok();
        }

        if args.trace {
            trace::reset_spi_trace(&em100).ok();
        }

        // Reset hold pin to float
        if args.holdpin.is_none() {
            if let Err(e) = em100.set_hold_pin_state(HoldPinState::Float) {
                eprintln!("Error: Failed to set EM100 to float: {}", e);
            }
        }
    }
}