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
// Copyright lowRISC contributors (OpenTitan project).
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0

use std::fmt::LowerHex;
use std::io::{BufRead, BufReader, Write};
use std::mem::size_of;
use std::net::TcpStream;
use std::os::unix::process::CommandExt;
use std::path::Path;
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};

use anyhow::{bail, ensure, Context, Result};
use once_cell::sync::Lazy;
use regex::Regex;
use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::dif::lc_ctrl::LcCtrlReg;
use crate::impl_serializable_error;
use crate::io::jtag::{Jtag, JtagChain, JtagError, JtagParams, JtagTap, RiscvReg};
use crate::util::parse_int::ParseInt;
use crate::util::printer;

/// Represents an OpenOCD server that we can interact with.
pub struct OpenOcd {
    /// OpenOCD child process.
    server_process: Child,
    /// Receiving side of the stream to the telnet interface of OpenOCD.
    reader: BufReader<TcpStream>,
    /// Sending side of the stream to the telnet interface of OpenOCD.
    writer: TcpStream,
}

impl Drop for OpenOcd {
    fn drop(&mut self) {
        let _ = self.server_process.kill();
    }
}

impl OpenOcd {
    /// How long to wait for OpenOCD to get ready to accept a TCL connection.
    const OPENOCD_TCL_READY_TMO: Duration = Duration::from_secs(30);

    /// Wait until we see a particular message on the output.
    fn wait_until_regex_match<'a>(
        stderr: &mut impl BufRead,
        regex: &Regex,
        timeout: Duration,
        s: &'a mut String,
    ) -> Result<regex::Captures<'a>> {
        let start = Instant::now();
        loop {
            // NOTE the read could block indefinitely, a proper solution would involved spawning
            // a thread or using async.
            let n = stderr.read_line(s)?;
            if n == 0 {
                bail!("OpenOCD stopped before being ready?");
            }
            log::info!(target: concat!(module_path!(), "::stderr"), "{}", s);
            if regex.is_match(s) {
                // This is not a `if let Some(capture) = regex.captures(s) {}` to to Rust
                // borrow checker limitations. Can be modified if Polonius lands.
                return Ok(regex.captures(s).unwrap());
            }
            s.clear();

            if start.elapsed() >= timeout {
                bail!("OpenOCD did not become ready to accept a TCL connection");
            }
        }
    }

    /// Spawn an OpenOCD server with given path.
    pub fn spawn(path: &Path) -> Result<Self> {
        let mut cmd = Command::new(path);

        // Let OpenOCD choose which port to bind to, in order to never unnecesarily run into
        // issues due to a particular port already being in use.
        // We don't use the telnet and GDB ports so disable them.
        // The configuration will happen through the TCL interface, so use `noinit` to prevent
        // OpenOCD from transition to execution mode.
        cmd.arg("-c")
            .arg("tcl_port 0; telnet_port disabled; gdb_port disabled; noinit;");

        log::info!("CWD: {:?}", std::env::current_dir());
        log::info!("Spawning OpenOCD: {cmd:?}");

        cmd.stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());

        // SAFETY: prctl is a syscall which is atomic and thus async-signal-safe.
        unsafe {
            cmd.pre_exec(|| {
                // Since we use OpenOCD as a library, make sure it's killed when
                // the parent process dies. This setting is preserved across execve.
                rustix::process::set_parent_process_death_signal(Some(
                    rustix::process::Signal::Hup,
                ))?;
                Ok(())
            });
        }

        let mut child = cmd
            .spawn()
            .with_context(|| format!("failed to spawn openocd: {cmd:?}",))?;
        let stdout = child.stdout.take().unwrap();
        let mut stderr = BufReader::new(child.stderr.take().unwrap());
        // Wait until we see 'Info : Listening on port XXX for tcl connections' before knowing
        // which port to connect to.
        log::info!("Waiting for OpenOCD to be ready to accept a TCL connection...");
        static READY_REGEX: Lazy<Regex> = Lazy::new(|| {
            Regex::new("Info : Listening on port ([0-9]+) for tcl connections").unwrap()
        });
        let mut buf = String::new();
        let regex_captures = Self::wait_until_regex_match(
            &mut stderr,
            &READY_REGEX,
            Self::OPENOCD_TCL_READY_TMO,
            &mut buf,
        )
        .context("OpenOCD was not ready in time to accept a connection")?;
        let openocd_port: u16 = regex_captures.get(1).unwrap().as_str().parse()?;
        // Print stdout and stderr with log
        std::thread::spawn(move || {
            printer::accumulate(
                stdout,
                concat!(module_path!(), "::stdout"),
                Default::default(),
            )
        });
        std::thread::spawn(move || {
            printer::accumulate(
                stderr,
                concat!(module_path!(), "::stderr"),
                Default::default(),
            )
        });

        let kill_guard = scopeguard::guard(child, |mut child| {
            let _ = child.kill();
        });

        log::info!("Connecting to OpenOCD tcl interface...");

        let stream = TcpStream::connect(("localhost", openocd_port))
            .context("failed to connect to OpenOCD socket")?;

        let mut connection = Self {
            server_process: scopeguard::ScopeGuard::into_inner(kill_guard),
            reader: BufReader::new(stream.try_clone()?),
            writer: stream,
        };

        // Test the connection by asking for OpenOCD's version.
        let version = connection.execute("version")?;
        log::info!("OpenOCD version: {version}");

        Ok(connection)
    }

    /// Send a string to OpenOCD Tcl interface.
    fn send(&mut self, cmd: &str) -> Result<()> {
        // The protocol is to send the command followed by a `0x1a` byte,
        // see https://openocd.org/doc/html/Tcl-Scripting-API.html#Tcl-RPC-server

        // Sanity check to ensure that the command string is not malformed.
        if cmd.contains('\x1A') {
            bail!("TCL command string should be contained inside the text to send");
        }

        self.writer
            .write_all(cmd.as_bytes())
            .context("failed to send a command to OpenOCD server")?;
        self.writer
            .write_all(&[0x1a])
            .context("failed to send the command terminator to OpenOCD server")?;
        self.writer.flush().context("failed to flush stream")?;
        Ok(())
    }

    fn recv(&mut self) -> Result<String> {
        let mut buf = Vec::new();
        self.reader.read_until(0x1A, &mut buf)?;
        if !buf.ends_with(b"\x1A") {
            bail!(OpenOcdError::PrematureExit);
        }
        buf.pop();
        String::from_utf8(buf).context("failed to parse OpenOCD response as UTF-8")
    }

    pub fn shutdown(mut self) -> Result<()> {
        self.execute("shutdown")?;
        // Wait for it to exit.
        self.server_process
            .wait()
            .context("failed to wait for OpenOCD server to exit")?;
        Ok(())
    }

    /// Send a TCL command to OpenOCD and wait for its response.
    pub fn execute(&mut self, cmd: &str) -> Result<String> {
        self.send(cmd)?;
        self.recv()
    }

    /// Load instruction register of a given tap.
    pub fn irscan(&mut self, tap: &str, ir: u32) -> Result<()> {
        let cmd = format!("irscan {} {:#x}", tap, ir);
        let result = self.execute(&cmd)?;
        ensure!(result.is_empty(), "unexpected response: '{result}'");
        Ok(())
    }

    /// Load data register of a given tap and return the scan.
    pub fn drscan<T: ParseInt + LowerHex>(
        &mut self,
        tap: &str,
        numbits: u32,
        data: T,
    ) -> Result<T> {
        let cmd = format!("drscan {} {} {:#x}", tap, numbits, data);
        let result = self.execute(&cmd)?;
        Ok(T::from_str_radix(&result, 16).map_err(|x| x.into())?)
    }
}

/// An JTAG interface driver over OpenOCD.
pub struct OpenOcdJtagChain {
    /// OpenOCD server instance.
    openocd: OpenOcd,
}

/// Errors related to the OpenOCD server.
#[derive(Error, Debug, Deserialize, Serialize)]
pub enum OpenOcdError {
    #[error("OpenOCD initialization failed: {0}")]
    InitializeFailure(String),
    #[error("OpenOCD server exists prematurely")]
    PrematureExit,
    #[error("Generic error {0}")]
    Generic(String),
}
impl_serializable_error!(OpenOcdError);

impl OpenOcdJtagChain {
    /// Start OpenOCD with given JTAG options but do not connect any TAP.
    pub fn new(adapter_command: &str, opts: &JtagParams) -> Result<OpenOcdJtagChain> {
        let mut openocd = OpenOcd::spawn(&opts.openocd)?;

        openocd.execute(adapter_command)?;
        openocd.execute(&format!("adapter speed {}", opts.adapter_speed_khz))?;
        openocd.execute("transport select jtag")?;
        openocd.execute("scan_chain")?;

        Ok(OpenOcdJtagChain { openocd })
    }
}

impl JtagChain for OpenOcdJtagChain {
    fn connect(mut self: Box<Self>, tap: JtagTap) -> Result<Box<dyn Jtag>> {
        // Pass through the config for the chosen TAP.
        let target = match tap {
            JtagTap::RiscvTap => include_str!(env!("openocd_riscv_target_cfg")),
            JtagTap::LcTap => include_str!(env!("openocd_lc_target_cfg")),
        };
        self.openocd.execute(target)?;

        // Capture outputs during initialization to see if error has occured during the process.
        let resp = self.openocd.execute("capture init")?;
        if resp.contains("JTAG scan chain interrogation failed") {
            bail!(OpenOcdError::InitializeFailure(resp));
        }

        Ok(Box::new(OpenOcdJtagTap {
            openocd: self.openocd,
            jtag_tap: tap,
        }))
    }

    fn into_raw(self: Box<Self>) -> Result<OpenOcd> {
        Ok(self.openocd)
    }
}

/// An JTAG interface driver over OpenOCD.
pub struct OpenOcdJtagTap {
    /// OpenOCD server instance.
    openocd: OpenOcd,
    /// JTAG TAP OpenOCD is connected to.
    jtag_tap: JtagTap,
}

impl OpenOcdJtagTap {
    /// Send a TCL command to OpenOCD and wait for its response.
    fn send_tcl_cmd(&mut self, cmd: &str) -> Result<String> {
        self.openocd.execute(cmd)
    }

    fn read_memory_impl<T: ParseInt>(&mut self, addr: u32, buf: &mut [T]) -> Result<usize> {
        // Ibex does not have a MMU so always tell OpenOCD that we are using physical addresses
        // otherwise it will try to translate the address through the (non-existent) MMU
        let cmd = format!(
            "read_memory 0x{addr:x} {width} {count} phys",
            width = 8 * size_of::<T>(),
            count = buf.len()
        );
        let response = self.send_tcl_cmd(cmd.as_str())?;
        response.trim().split(' ').try_fold(0, |idx, val| {
            if idx < buf.len() {
                buf[idx] = T::from_str(val).context(format!(
                    "expected response to be an hexadecimal byte, got '{response}'"
                ))?;
                Ok(idx + 1)
            } else {
                bail!("OpenOCD returned too much data on read".to_string())
            }
        })
    }

    fn write_memory_impl<T: ToString>(&mut self, addr: u32, bigbuf: &[T]) -> Result<()> {
        const CHUNK_SIZE: usize = 1024;
        for (idx, buf) in bigbuf.chunks(CHUNK_SIZE).enumerate() {
            // Convert data to space-separated strings.
            let data: Vec<_> = buf.iter().map(ToString::to_string).collect();
            let data_str = &data[..].join(" ");
            // See [read_memory] about physical addresses
            let cmd = format!(
                "write_memory 0x{chunk_addr:x} {width} {{ {data_str} }} phys",
                chunk_addr = addr + (idx * CHUNK_SIZE * size_of::<T>()) as u32,
                width = 8 * size_of::<T>()
            );
            let response = self.send_tcl_cmd(cmd.as_str())?;
            if !response.is_empty() {
                bail!("unexpected response: '{response}'");
            }
        }

        Ok(())
    }

    /// Read a register: this function does not attempt to translate the
    /// name or number of the register. If force is set, bypass OpenOCD's
    /// register cache.
    fn read_register<T: ParseInt>(&mut self, reg_name: &str, force: bool) -> Result<T> {
        let cmd = format!(
            "get_reg {} {{ {} }}",
            if force { "-force" } else { "" },
            reg_name,
        );
        let response = self.send_tcl_cmd(cmd.as_str())?;
        // the expected output format is 'reg_name 0xabcdef', e.g 'pc 0x10009858'
        let (out_reg_name, value) = response
            .trim()
            .split_once(' ')
            .context("expected response of the form 'reg value', got '{response}'")?;
        ensure!(
            out_reg_name == reg_name,
            "OpenOCD returned the value for register '{out_reg_name}' instead of '{reg_name}"
        );
        T::from_str(value).context(format!(
            "expected value to be an hexadecimal string, got '{value}'"
        ))
    }

    fn write_register<T: ToString>(&mut self, reg_name: &str, value: T) -> Result<()> {
        let cmd = format!("set_reg {{ {reg_name} {} }}", T::to_string(&value));
        let response = self.send_tcl_cmd(cmd.as_str())?;
        if !response.is_empty() {
            bail!("unexpected response: '{response}'");
        }

        Ok(())
    }
}

impl Jtag for OpenOcdJtagTap {
    fn into_raw(self: Box<Self>) -> Result<OpenOcd> {
        Ok(self.openocd)
    }

    fn as_raw(&mut self) -> Result<&mut OpenOcd> {
        Ok(&mut self.openocd)
    }

    fn disconnect(self: Box<Self>) -> Result<()> {
        self.openocd.shutdown()
    }

    fn tap(&self) -> JtagTap {
        self.jtag_tap
    }

    fn read_lc_ctrl_reg(&mut self, reg: &LcCtrlReg) -> Result<u32> {
        ensure!(
            matches!(self.jtag_tap, JtagTap::LcTap),
            JtagError::Tap(self.jtag_tap)
        );
        let reg_offset = reg.word_offset();
        let cmd = format!("riscv dmi_read 0x{reg_offset:x}");
        let response = self.send_tcl_cmd(cmd.as_str())?;

        let value = u32::from_str(response.trim()).context(format!(
            "expected response to be hexadecimal word, got '{response}'"
        ))?;

        Ok(value)
    }

    fn write_lc_ctrl_reg(&mut self, reg: &LcCtrlReg, value: u32) -> Result<()> {
        ensure!(
            matches!(self.jtag_tap, JtagTap::LcTap),
            JtagError::Tap(self.jtag_tap)
        );
        let reg_offset = reg.word_offset();
        let cmd = format!("riscv dmi_write 0x{reg_offset:x} 0x{value:x}");
        let response = self.send_tcl_cmd(cmd.as_str())?;

        if !response.is_empty() {
            bail!("unexpected response: '{response}'");
        }

        Ok(())
    }

    fn read_memory(&mut self, addr: u32, buf: &mut [u8]) -> Result<usize> {
        ensure!(
            matches!(self.jtag_tap, JtagTap::RiscvTap),
            JtagError::Tap(self.jtag_tap)
        );
        self.read_memory_impl(addr, buf)
    }

    fn read_memory32(&mut self, addr: u32, buf: &mut [u32]) -> Result<usize> {
        ensure!(
            matches!(self.jtag_tap, JtagTap::RiscvTap),
            JtagError::Tap(self.jtag_tap)
        );
        self.read_memory_impl(addr, buf)
    }

    fn write_memory(&mut self, addr: u32, buf: &[u8]) -> Result<()> {
        ensure!(
            matches!(self.jtag_tap, JtagTap::RiscvTap),
            JtagError::Tap(self.jtag_tap)
        );
        self.write_memory_impl(addr, buf)
    }

    fn write_memory32(&mut self, addr: u32, buf: &[u32]) -> Result<()> {
        ensure!(
            matches!(self.jtag_tap, JtagTap::RiscvTap),
            JtagError::Tap(self.jtag_tap)
        );
        self.write_memory_impl(addr, buf)
    }

    fn halt(&mut self) -> Result<()> {
        ensure!(
            matches!(self.jtag_tap, JtagTap::RiscvTap),
            JtagError::Tap(self.jtag_tap)
        );
        let response = self.send_tcl_cmd("halt")?;
        if !response.is_empty() {
            bail!("unexpected response: '{response}'");
        }

        Ok(())
    }

    fn wait_halt(&mut self, timeout: Duration) -> Result<()> {
        ensure!(
            matches!(self.jtag_tap, JtagTap::RiscvTap),
            JtagError::Tap(self.jtag_tap)
        );
        let cmd = format!("wait_halt {}", timeout.as_millis());
        let response = self.send_tcl_cmd(cmd.as_str())?;
        if !response.is_empty() {
            bail!("unexpected response: '{response}'");
        }
        Ok(())
    }

    fn resume(&mut self) -> Result<()> {
        ensure!(
            matches!(self.jtag_tap, JtagTap::RiscvTap),
            JtagError::Tap(self.jtag_tap)
        );
        let response = self.send_tcl_cmd("resume")?;
        if !response.is_empty() {
            bail!("unexpected response: '{response}'");
        }

        Ok(())
    }

    fn resume_at(&mut self, addr: u32) -> Result<()> {
        ensure!(
            matches!(self.jtag_tap, JtagTap::RiscvTap),
            JtagError::Tap(self.jtag_tap)
        );
        let cmd = format!("resume 0x{:x}", addr);
        let response = self.send_tcl_cmd(&cmd)?;
        if !response.is_empty() {
            bail!("unexpected response: '{response}'");
        }

        Ok(())
    }

    fn reset(&mut self, run: bool) -> Result<()> {
        ensure!(
            matches!(self.jtag_tap, JtagTap::RiscvTap),
            JtagError::Tap(self.jtag_tap)
        );
        let cmd = format!("reset {}", if run { "run" } else { "halt" });
        let response = self.send_tcl_cmd(&cmd)?;
        if !response.is_empty() {
            bail!("unexpected response: '{response}'");
        }

        Ok(())
    }

    fn step(&mut self) -> Result<()> {
        ensure!(
            matches!(self.jtag_tap, JtagTap::RiscvTap),
            JtagError::Tap(self.jtag_tap)
        );
        let response = self.send_tcl_cmd("step")?;
        if !response.is_empty() {
            bail!("unexpected response: '{response}'");
        }

        Ok(())
    }

    fn step_at(&mut self, addr: u32) -> Result<()> {
        ensure!(
            matches!(self.jtag_tap, JtagTap::RiscvTap),
            JtagError::Tap(self.jtag_tap)
        );
        let cmd = format!("step 0x{:x}", addr);
        let response = self.send_tcl_cmd(&cmd)?;
        if !response.is_empty() {
            bail!("unexpected response: '{response}'");
        }

        Ok(())
    }

    fn read_riscv_reg(&mut self, reg: &RiscvReg) -> Result<u32> {
        ensure!(
            matches!(self.jtag_tap, JtagTap::RiscvTap),
            JtagError::Tap(self.jtag_tap)
        );
        self.read_register::<u32>(reg.name(), true)
    }

    fn write_riscv_reg(&mut self, reg: &RiscvReg, val: u32) -> Result<()> {
        ensure!(
            matches!(self.jtag_tap, JtagTap::RiscvTap),
            JtagError::Tap(self.jtag_tap)
        );
        self.write_register(reg.name(), val)
    }

    fn set_breakpoint(&mut self, address: u32, hw: bool) -> Result<()> {
        let cmd = format!("bp {:#x} 2{}", address, if hw { " hw" } else { "" });
        let response = self.send_tcl_cmd(&cmd)?;
        if !response.starts_with("breakpoint set at ") {
            bail!("unexpected response: '{response}'");
        }
        Ok(())
    }

    fn remove_breakpoint(&mut self, addr: u32) -> Result<()> {
        let cmd = format!("rbp {:#x}", addr);
        let response = self.send_tcl_cmd(&cmd)?;
        if !response.is_empty() {
            bail!("unexpected response: '{response}'");
        }
        Ok(())
    }

    fn remove_all_breakpoints(&mut self) -> Result<()> {
        let response = self.send_tcl_cmd("rbp all")?;
        if !response.is_empty() {
            bail!("unexpected response: '{response}'");
        }
        Ok(())
    }
}