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
//! A **R**ust **A**rithmetic **L**ibrary **T**esting **E**nvironment for embedded RISC-V
//! **32**-bit. This libraries allows the testing of arithmetic Rust code made for [RISC-V] 32-bit
//! using the [QEMU] simulator. This is especially useful when developing with the [Rust riscv32
//! intrinsics].
//!
//! This library is mostly just a minimal hack to implement a testing environment and port the
//! `riscv32` embedded targets to a Linux userspace target.
//!
//! ## Usage
//!
//! First, this project uses the [QEMU] userspace simulator to simulate the target code. This can
//! be installed with the standard `qemu-user` package on most operating systems.
//!
//! ```bash
//! # Linux: Debian / Ubuntu
//! sudo apt-get install qemu-user
//!
//! # Linux: ArchLinux
//! sudo pacman -S qemu-user
//! ```
//!
//! For more platforms, take a look [here](https://www.qemu.org/download).
//!
//! Then, add `ralte32` as a development dependency.
//!
//! ```bash
//! cargo add --dev ralte32
//! ```
//!
//! Lastly, create and/or add a short section to your `.cargo/config.toml`.
//!
//! ```toml
//! # ...
//!
//! [target.riscv32imac-unknown-none-elf]
//! rustflags = ['-Ctarget-feature=+crt-static']
//! runner = "qemu-riscv32 -cpu rv32"
//!
//! # NOTE: If you want to enable additional target features, add them here.
//! #
//! # Example to enable the `zk` feature:
//! # rustflags = ['-Ctarget-feature=+crt-static,+zk']
//! # runner = "qemu-riscv32 -cpu rv32,zk=true"
//! ```
//!
//! Then, to implement some tests, you add an example in `examples/`.
//!
//! ```rust,no_run
//! // examples/test-rv32.rs
//! #![no_std]
//! #![no_main]
//!
//! use ralte32::define_tests;
//!
//! fn test_multiplication() {
//!     assert_eq!(6 * 7, 42);
//! }
//!
//! fn test_remainder() {
//!     assert_eq!(7 % 6, 1);
//! }
//!
//! define_tests!{
//!     test_multiplication,
//!     test_remainder,
//! }
//! ```
//!
//! This can then be ran with:
//!
//! ```bash
//! cargo run --example test-rv32 --target riscv32imac-unknown-none-elf
//! ```
//!
//! This will give:
//!
//! ```text
//! Running tests...
//!
//! Running "test_multiplication"... SUCCESSFUL
//! Running "test_remainder"... SUCCESSFUL
//! ```
//!
//! ## Limitations
//!
//! There are several known limitations.
//!
//! 1. First test or assert to fail, stops the test environment.
//! 2. This only tests user-level code. Access to supervisor, machine or hypervisor instructions
//!    and CSRs is not possible.
//! 3. Very limited support for printing.
//!
//! ## License
//!
//! This project is dual licensed under [MIT](./LICENSE-MIT) and [APACHE-2.0](./LICENSE-APACHE)
//! licenses.
//!
//! [QEMU]: https://www.qemu.org/
//! [RISC-V]: https://en.wikipedia.org/wiki/RISC-V
//! [Rust riscv32 intrinsics]: https://doc.rust-lang.org/nightly/core/arch/riscv32
#![cfg_attr(not(any(not(target_arch = "riscv32"), doc)), no_std)]

#[macro_export]
/// Assert whether an condition is true similar to [`core::assert`].
///
/// This macro has better formatting within the context of this crate.
macro_rules! assert {
    ($condition:expr$(, $txt:literal)?) => {{
        if ! { $condition } {
            $crate::eprint![
                "\n",
                file!(), ":", line!(), ": Assertion failed \"", stringify!($condition), "\"\n",
                $(
                    $txt,
                    "\n",
                )?
            ];
            $crate::syscall::exit(1);
        }
    }};
}

#[macro_export]
/// Assert whether two items are equal similar to [`core::assert_eq`].
///
/// This macro has better formatting within the context of this crate.
macro_rules! assert_eq {
    ($lhs:expr, $rhs:expr$(, $txt:literal)?) => {{
        if ! { $lhs == $rhs } {
            $crate::eprint![
                "\n",
                file!(), ":", line!(), ": Assertion failed. \"", stringify!($lhs), "\" is not equal to \"", stringify!($rhs), "\"\n",
                $(
                    $txt,
                    "\n",
                )?
            ];
            $crate::syscall::exit(1);
        }
    }};
}

#[macro_export]
/// Assert whether two items are not equal similar to [`core::assert_ne`].
///
/// This macro has better formatting within the context of this crate.
macro_rules! assert_ne {
    ($lhs:expr, $rhs:expr$(, $txt:literal)?) => {{
        if ! { $lhs != $rhs } {
            $crate::eprint![
                "\n",
                file!(), ":", line!(), ": Assertion failed. \"", stringify!($lhs), "\" is equal to \"", stringify!($rhs), "\"\n",
                $(
                    $txt,
                    "\n",
                )?
            ];
            $crate::syscall::exit(1);
        }
    }};
}

#[macro_export]
/// Print several items to the standard output.
///
/// This is similar to [`std::print`], but is used without formatting. Instead, all items are
/// specified sequentially.
macro_rules! print {
    ($($item:expr),* $(,)?) => {{
        $(
            $crate::Rv32Write::write(&$item, $crate::buffered_writer::write_stdout);
        )*
        $crate::buffered_writer::flush_stdout();
    }};
}

#[macro_export]
/// Print several items and a newline to the standard output.
///
/// This is similar to [`std::println`], but is used without formatting. Instead, all items are
/// specified sequentially.
macro_rules! println {
    ($($item:expr),* $(,)?) => {{
        $(
            $crate::Rv32Write::write(&$item, $crate::buffered_writer::write_stdout);
        )*
        $crate::Rv32Write::write(&"\n", $crate::buffered_writer::write_stdout);
        $crate::buffered_writer::flush_stdout();
    }};
}

#[macro_export]
/// Print several items to the standard error.
///
/// This is similar to [`std::eprint`], but is used without formatting. Instead, all items are
/// specified sequentially.
macro_rules! eprint {
    ($($item:expr),* $(,)?) => {{
        $(
            $crate::Rv32Write::write(&$item, $crate::buffered_writer::write_stderr);
        )*
        $crate::buffered_writer::flush_stderr();
    }};
}

#[macro_export]
/// Print several items and a newline to the standard error.
///
/// This is similar to [`std::eprintln`], but is used without formatting. Instead, all items are
/// specified sequentially.
macro_rules! eprintln {
    ($($item:expr),* $(,)?) => {{
        $(
            $crate::Rv32Write::write(&$item, $crate::buffered_writer::write_stderr);
        )*
        $crate::Rv32Write::write(&"\n", $crate::buffered_writer::write_stderr);
        $crate::buffered_writer::flush_stderr();
    }};
}

#[macro_export]
/// Define a set of test functions to run.
///
/// This is the main entry into this crate.
macro_rules! define_tests {
    ($($test_fn:ident),* $(,)?) => {
        #[cfg(target_arch = "riscv32")]
        #[panic_handler]
        fn panic(info: &core::panic::PanicInfo) -> ! {
            $crate::eprintln!();

            if let Some(loc) = info.location() {
                $crate::eprint!(
                    loc.file(),
                    ":",
                    loc.line(),
                    ":",
                    loc.column(),
                    " "
                );
            }

            $crate::eprint!("Code panicked");

            if let Some(message) = info.payload().downcast_ref::<&str>() {
                $crate::eprint!(": ", *message);
            }

            $crate::eprintln!();

            $crate::syscall::exit(1)
        }

        // Linux links against the `_start` function specifically.
        #[cfg(target_arch = "riscv32")]
        #[no_mangle]
        pub extern "C" fn _start() -> ! {
            $crate::println!("Running tests...\n");

            $(
            $crate::print!("Running \"", stringify!($test_fn), "\"...");
            $test_fn();
            $crate::println!("\rRunning \"", stringify!($test_fn), "\"... SUCCESSFUL");
            )*


            $crate::syscall::exit(0)
        }

        #[cfg(not(target_arch = "riscv32"))]
        fn main() {
            return;

            #[allow(unreachable_code)]
            {
                $(
                $test_fn();
                )*
            }
        }
    };
}

/// Linux system calls used by this crate.
pub mod syscall {
    #[inline]
    pub fn write(_file_descriptor: u32, _buf: &[u8]) {
        #[cfg(target_arch = "riscv32")]
        unsafe {
            core::arch::asm!(
                "ecall",
                in ("a7") 64,
                in ("a0") _file_descriptor,
                in ("a1") _buf as *const [u8] as *const u8,
                in ("a2") _buf.len(),
            );
        }

        #[cfg(not(target_arch = "riscv32"))]
        {
            // Failed to write. Not running on RISC-V 32
            std::process::abort();
        }
    }

    #[inline]
    pub fn exit(_status_code: u32) -> ! {
        #[cfg(target_arch = "riscv32")]
        unsafe {
            core::arch::asm!(
                "ecall",
                in ("a7") 93,
                in ("a0") _status_code,
                options (noreturn)
            );
        }

        #[cfg(not(target_arch = "riscv32"))]
        {
            // Failed to exit. Not running on RISC-V 32
            std::process::abort();
        }
    }
}

/// Wrapper type to format a unsigned integer with hexadecimal
pub struct Hex<T>(pub T);
/// Wrapper type to format a unsigned integer with binary
pub struct Binary<T>(pub T);

fn write_stdout(buf: &[u8]) {
    syscall::write(1, buf)
}

fn write_stderr(buf: &[u8]) {
    syscall::write(2, buf)
}

/// Trait to write data to a file descriptor
pub trait Rv32Write {
    /// Convert `self` into a set of UTF-8 bytes which get passed to `writer`.
    fn write(&self, writer: fn(&[u8]));
}

impl Rv32Write for &[u8] {
    fn write(&self, writer: fn(&[u8])) {
        writer(self)
    }
}

impl Rv32Write for char {
    fn write(&self, writer: fn(&[u8])) {
        let mut b = [0; 4];
        self.encode_utf8(&mut b);
        writer(&b[0..self.len_utf8()])
    }
}

impl Rv32Write for &str {
    fn write(&self, writer: fn(&[u8])) {
        writer(self.as_bytes())
    }
}

impl Rv32Write for u128 {
    fn write(&self, writer: fn(&[u8])) {
        let mut num = *self;

        if num == 0 {
            writer(b"0");
            return;
        }

        const MAX_DIGITS: usize = (u128::MAX.ilog10() + 1) as usize;

        let num_digits = u32::from(num % 10 != 0) + num.ilog10();

        let mut buf = [0u8; MAX_DIGITS];

        for i in 0..num_digits {
            buf[(num_digits - i - 1) as usize] = b'0' + (num % 10) as u8;
            num /= 10;
        }

        writer(&buf[0..num_digits as usize]);
    }
}

impl Rv32Write for i128 {
    fn write(&self, writer: fn(&[u8])) {
        let num = *self;

        if num < 0 {
            writer(b"-");
        }

        num.unsigned_abs().write(writer);
    }
}

macro_rules! impl_write {
    ($parent:ty, [$($child:ty),+]) => {
        $(
        impl Rv32Write for $child {
            fn write(&self, writer: fn(&[u8])) {
                <$parent>::from(*self).write(writer)
            }
        }
        )+

    };
}

const LUT: [u8; 16] = [
    b'0', b'1', b'2', b'3', b'4', b'5', b'6', b'7', b'8', b'9', b'A', b'B', b'C', b'D', b'E', b'F',
];

macro_rules! impl_binhex {
    ($($t:ty),+) => {
        $(
        impl Rv32Write for Hex<$t> {
            fn write(&self, writer: fn(&[u8])) {
                let num = self.0;

                for i in 0..<$t>::BITS / 4 {
                    if i != 0 && i % 4 == 0 {
                        "_".write(writer);
                    }

                    let c = LUT[((num >> ((<$t>::BITS / 4 - i - 1)*4)) & 0xF) as usize];
                    let c = char::from(c);

                    c.write(writer);
                }
            }
        }

        impl Rv32Write for Binary<$t> {
            fn write(&self, writer: fn(&[u8])) {
                let num = self.0;

                for i in 0..<$t>::BITS {
                    if i != 0 && i % 4 == 0 {
                        "_".write(writer);
                    }

                    let c = if (num >> (<$t>::BITS - i - 1)) & 1 == 1 {
                        "1"
                    } else {
                        "0"
                    };

                    c.write(writer);
                }
            }
        }
        )+

    };
}

impl_write! { u128, [ u8, u16, u32, u64 ] }
impl_write! { i128, [ i8, i16, i32, i64 ] }
impl_binhex! { u8, u16, u32, u64, u128 }

#[doc(hidden)]
pub mod buffered_writer {
    const PRINTBUF_CAPACITY: usize = 128;
    static mut PRINTBUF: [u8; PRINTBUF_CAPACITY] = [b'A'; PRINTBUF_CAPACITY];
    static mut PRINTBUF_LEN: usize = 0;

    pub fn write(buf: &[u8], back_writer: fn(&[u8])) {
        let current_len = unsafe { PRINTBUF_LEN };
        if current_len
            .checked_add(buf.len())
            .is_some_and(|value| value < PRINTBUF_CAPACITY)
        {
            for (i, c) in buf.iter().enumerate() {
                unsafe { PRINTBUF[current_len + i] = *c };
            }
            unsafe { PRINTBUF_LEN += buf.len() }
        } else {
            self::flush(back_writer);
            back_writer(buf);
        }
    }

    pub fn flush(back_writer: fn(&[u8])) {
        back_writer(unsafe { &PRINTBUF[0..PRINTBUF_LEN] });
        unsafe { PRINTBUF_LEN = 0 }
    }

    pub fn write_stdout(buf: &[u8]) {
        self::write(buf, super::write_stdout);
    }

    pub fn flush_stdout() {
        self::flush(super::write_stdout);
    }

    pub fn write_stderr(buf: &[u8]) {
        self::write(buf, super::write_stderr);
    }

    pub fn flush_stderr() {
        self::flush(super::write_stderr);
    }
}