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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
// Licensed under the Apache License, Version 2.0 or the MIT License.
// SPDX-License-Identifier: Apache-2.0 OR MIT
// Copyright Tock Contributors 2022.

//! Support for in-kernel debugging.
//!
//! For printing, this module uses an internal buffer to write the strings into.
//! If you are writing and the buffer fills up, you can make the size of
//! `output_buffer` larger.
//!
//! Before debug interfaces can be used, the board file must assign them hardware:
//!
//! ```ignore
//! kernel::debug::assign_gpios(
//!     Some(&sam4l::gpio::PA[13]),
//!     Some(&sam4l::gpio::PA[15]),
//!     None,
//! );
//!
//! components::debug_writer::DebugWriterComponent::new(uart_mux).finalize(components::debug_writer_component_static!());
//! ```
//!
//! The debug queue is optional, if not set in the board it is just ignored.
//! You can add one in the board file as follows:
//!
//! ```ignore
//! components::debug_queue::DebugQueueComponent::new()
//!     .finalize(components::debug_queue_component_static!());
//! ```
//!
//! Example
//! -------
//!
//! ```no_run
//! # use kernel::{debug, debug_enqueue, debug_flush_queue, debug_gpio, debug_verbose};
//! # fn main() {
//! # let i = 42;
//! debug!("Yes the code gets here with value {}", i);
//! debug_verbose!("got here"); // Includes message count, file, and line.
//!
//! debug_gpio!(0, toggle); // Toggles the first debug GPIO.
//!
//! debug_enqueue!("foo"); // Adds some message to the debug queue.
//! debug_flush_queue!(); // Flushes the queue, writing "foo".
//! debug_enqueue!("bar");
//! panic!("42"); // Flushes the queue, writing "bar" in the debug queue section
//!               // of the panic diagnostic.
//! # }
//! ```
//!
//! ```text
//! Yes the code gets here with value 42
//! TOCK_DEBUG(0): /tock/capsules/src/sensys.rs:24: got here
//! ```

use core::cell::Cell;
use core::fmt::{write, Arguments, Result, Write};
use core::panic::PanicInfo;
use core::str;

use crate::collections::queue::Queue;
use crate::collections::ring_buffer::RingBuffer;
use crate::hil;
use crate::platform::chip::Chip;
use crate::process::Process;
use crate::process::ProcessPrinter;
use crate::processbuffer::ReadableProcessSlice;
use crate::utilities::binary_write::BinaryToWriteWrapper;
use crate::utilities::cells::NumericCellExt;
use crate::utilities::cells::{MapCell, TakeCell};
use crate::ErrorCode;

/// This trait is similar to std::io::Write in that it takes bytes instead of a string (contrary to
/// core::fmt::Write), but io::Write isn't available in no_std (due to std::io::Error not being
/// available).
///
/// Also, in our use cases, writes are infaillible, so the write function cannot return an Error,
/// however it might not be able to write everything, so it returns  the number of bytes written.
///
/// See also the tracking issue: <https://github.com/rust-lang/rfcs/issues/2262>
pub trait IoWrite {
    fn write(&mut self, buf: &[u8]) -> usize;

    fn write_ring_buffer(&mut self, buf: &RingBuffer<'_, u8>) -> usize {
        let (left, right) = buf.as_slices();
        let mut total = 0;
        if let Some(slice) = left {
            total += self.write(slice);
        }
        if let Some(slice) = right {
            total += self.write(slice);
        }
        total
    }
}

///////////////////////////////////////////////////////////////////
// panic! support routines

/// Tock panic routine, without the infinite LED-blinking loop.
///
/// This is useful for boards which do not feature LEDs to blink or
/// want to implement their own behaviour. This method returns after
/// performing the panic dump.
///
/// After this method returns, the system is no longer in a
/// well-defined state. Care must be taken on how one interacts with
/// the system once this function returns.
///
/// **NOTE:** The supplied `writer` must be synchronous.
pub unsafe fn panic_print<W: Write + IoWrite, C: Chip, PP: ProcessPrinter>(
    writer: &mut W,
    panic_info: &PanicInfo,
    nop: &dyn Fn(),
    processes: &'static [Option<&'static dyn Process>],
    chip: &'static Option<&'static C>,
    process_printer: &'static Option<&'static PP>,
) {
    panic_begin(nop);
    // Flush debug buffer if needed
    flush(writer);
    panic_banner(writer, panic_info);
    panic_cpu_state(chip, writer);

    // Some systems may enforce memory protection regions for the
    // kernel, making application memory inaccessible. However,
    // priting process information will attempt to access memory. If
    // we are provided a chip reference, attempt to disable userspace
    // memory protection first:
    chip.map(|c| {
        use crate::platform::mpu::MPU;
        c.mpu().disable_app_mpu()
    });
    panic_process_info(processes, process_printer, writer);
}

/// Tock default panic routine.
///
/// **NOTE:** The supplied `writer` must be synchronous.
pub unsafe fn panic<L: hil::led::Led, W: Write + IoWrite, C: Chip, PP: ProcessPrinter>(
    leds: &mut [&L],
    writer: &mut W,
    panic_info: &PanicInfo,
    nop: &dyn Fn(),
    processes: &'static [Option<&'static dyn Process>],
    chip: &'static Option<&'static C>,
    process_printer: &'static Option<&'static PP>,
) -> ! {
    // Call `panic_print` first which will print out the panic
    // information and return
    panic_print(writer, panic_info, nop, processes, chip, process_printer);

    // The system is no longer in a well-defined state, we cannot
    // allow this function to return
    //
    // Forever blink LEDs in an infinite loop
    panic_blink_forever(leds)
}

/// Generic panic entry.
///
/// This opaque method should always be called at the beginning of a board's
/// panic method to allow hooks for any core kernel cleanups that may be
/// appropriate.
pub unsafe fn panic_begin(nop: &dyn Fn()) {
    // Let any outstanding uart DMA's finish
    for _ in 0..200000 {
        nop();
    }
}

/// Lightweight prints about the current panic and kernel version.
///
/// **NOTE:** The supplied `writer` must be synchronous.
pub unsafe fn panic_banner<W: Write>(writer: &mut W, panic_info: &PanicInfo) {
    let _ = writer.write_fmt(format_args!("\r\n{}\r\n", panic_info));

    // Print version of the kernel
    let _ = writer.write_fmt(format_args!(
        "\tKernel version {}\r\n",
        option_env!("TOCK_KERNEL_VERSION").unwrap_or("unknown")
    ));
}

/// Print current machine (CPU) state.
///
/// **NOTE:** The supplied `writer` must be synchronous.
pub unsafe fn panic_cpu_state<W: Write, C: Chip>(
    chip: &'static Option<&'static C>,
    writer: &mut W,
) {
    chip.map(|c| {
        c.print_state(writer);
    });
}

/// More detailed prints about all processes.
///
/// **NOTE:** The supplied `writer` must be synchronous.
pub unsafe fn panic_process_info<PP: ProcessPrinter, W: Write>(
    procs: &'static [Option<&'static dyn Process>],
    process_printer: &'static Option<&'static PP>,
    writer: &mut W,
) {
    process_printer.map(|printer| {
        // print data about each process
        let _ = writer.write_fmt(format_args!("\r\n---| App Status |---\r\n"));
        for idx in 0..procs.len() {
            procs[idx].map(|process| {
                // Print the memory map and basic process info.
                //
                // Because we are using a synchronous printer we do not need to
                // worry about looping on the print function.
                printer.print_overview(process, &mut BinaryToWriteWrapper::new(writer), None);
                // Print all of the process details.
                process.print_full_process(writer);
            });
        }
    });
}

/// Blinks a recognizable pattern forever.
///
/// If a multi-color LED is used for the panic pattern, it is
/// advised to turn off other LEDs before calling this method.
///
/// Generally, boards should blink red during panic if possible,
/// otherwise choose the 'first' or most prominent LED. Some
/// boards may find it appropriate to blink multiple LEDs (e.g.
/// one on the top and one on the bottom), thus this method
/// accepts an array, however most will only need one.
pub fn panic_blink_forever<L: hil::led::Led>(leds: &mut [&L]) -> ! {
    leds.iter_mut().for_each(|led| led.init());
    loop {
        for _ in 0..1000000 {
            leds.iter_mut().for_each(|led| led.on());
        }
        for _ in 0..100000 {
            leds.iter_mut().for_each(|led| led.off());
        }
        for _ in 0..1000000 {
            leds.iter_mut().for_each(|led| led.on());
        }
        for _ in 0..500000 {
            leds.iter_mut().for_each(|led| led.off());
        }
    }
}

// panic! support routines
///////////////////////////////////////////////////////////////////

///////////////////////////////////////////////////////////////////
// debug_gpio! support

pub static mut DEBUG_GPIOS: (
    Option<&'static dyn hil::gpio::Pin>,
    Option<&'static dyn hil::gpio::Pin>,
    Option<&'static dyn hil::gpio::Pin>,
) = (None, None, None);

pub unsafe fn assign_gpios(
    gpio0: Option<&'static dyn hil::gpio::Pin>,
    gpio1: Option<&'static dyn hil::gpio::Pin>,
    gpio2: Option<&'static dyn hil::gpio::Pin>,
) {
    DEBUG_GPIOS.0 = gpio0;
    DEBUG_GPIOS.1 = gpio1;
    DEBUG_GPIOS.2 = gpio2;
}

/// In-kernel gpio debugging, accepts any GPIO HIL method
#[macro_export]
macro_rules! debug_gpio {
    ($i:tt, $method:ident $(,)?) => {{
        #[allow(unused_unsafe)]
        unsafe {
            $crate::debug::DEBUG_GPIOS.$i.map(|g| g.$method());
        }
    }};
}

///////////////////////////////////////////////////////////////////
// debug_enqueue! support

/// Wrapper type that we need a mutable reference to for the core::fmt::Write
/// interface.
pub struct DebugQueueWrapper {
    dw: MapCell<&'static DebugQueue>,
}

impl DebugQueueWrapper {
    pub fn new(dw: &'static DebugQueue) -> Self {
        Self {
            dw: MapCell::new(dw),
        }
    }
}

pub struct DebugQueue {
    ring_buffer: TakeCell<'static, RingBuffer<'static, u8>>,
}

impl DebugQueue {
    pub fn new(ring_buffer: &'static mut RingBuffer<'static, u8>) -> Self {
        Self {
            ring_buffer: TakeCell::new(ring_buffer),
        }
    }
}

static mut DEBUG_QUEUE: Option<&'static mut DebugQueueWrapper> = None;

/// Function used by board main.rs to set a reference to the debug queue.
pub unsafe fn set_debug_queue(buffer: &'static mut DebugQueueWrapper) {
    DEBUG_QUEUE = Some(buffer);
}

impl Write for DebugQueueWrapper {
    fn write_str(&mut self, s: &str) -> Result {
        self.dw.map(|dw| {
            dw.ring_buffer.map(|ring_buffer| {
                let bytes = s.as_bytes();
                for &b in bytes {
                    ring_buffer.push(b);
                }
            });
        });

        Ok(())
    }
}

pub fn debug_enqueue_fmt(args: Arguments) {
    unsafe { DEBUG_QUEUE.as_deref_mut() }.map(|buffer| {
        let _ = write(buffer, args);
        let _ = buffer.write_str("\r\n");
    });
}

pub fn debug_flush_queue_() {
    let writer = unsafe { get_debug_writer() };

    unsafe { DEBUG_QUEUE.as_deref_mut() }.map(|buffer| {
        buffer.dw.map(|dw| {
            dw.ring_buffer.map(|ring_buffer| {
                writer.write_ring_buffer(ring_buffer);
                ring_buffer.empty();
            });
        });
    });
}

/// This macro prints a new line to an internal ring buffer, the contents of
/// which are only flushed with `debug_flush_queue!` and in the panic handler.
#[macro_export]
macro_rules! debug_enqueue {
    () => ({
        debug_enqueue!("")
    });
    ($msg:expr $(,)?) => ({
        $crate::debug::debug_enqueue_fmt(format_args!($msg))
    });
    ($fmt:expr, $($arg:tt)+) => ({
        $crate::debug::debug_enqueue_fmt(format_args!($fmt, $($arg)+))
    });
}

/// This macro flushes the contents of the debug queue into the regular
/// debug output.
#[macro_export]
macro_rules! debug_flush_queue {
    () => {{
        $crate::debug::debug_flush_queue_()
    }};
}

///////////////////////////////////////////////////////////////////
// debug! and debug_verbose! support

/// Wrapper type that we need a mutable reference to for the core::fmt::Write
/// interface.
pub struct DebugWriterWrapper {
    dw: MapCell<&'static DebugWriter>,
}

/// Main type that we need an immutable reference to so we can share it with
/// the UART provider and this debug module.
pub struct DebugWriter {
    // What provides the actual writing mechanism.
    uart: &'static dyn hil::uart::Transmit<'static>,
    // The buffer that is passed to the writing mechanism.
    output_buffer: TakeCell<'static, [u8]>,
    // An internal buffer that is used to hold debug!() calls as they come in.
    internal_buffer: TakeCell<'static, RingBuffer<'static, u8>>,
    // Number of debug!() calls.
    count: Cell<usize>,
}

/// Static variable that holds the kernel's reference to the debug tool. This is
/// needed so the debug!() macros have a reference to the object to use.
static mut DEBUG_WRITER: Option<&'static mut DebugWriterWrapper> = None;

unsafe fn try_get_debug_writer() -> Option<&'static mut DebugWriterWrapper> {
    DEBUG_WRITER.as_deref_mut()
}

unsafe fn get_debug_writer() -> &'static mut DebugWriterWrapper {
    try_get_debug_writer().unwrap() // Unwrap fail = Must call `set_debug_writer_wrapper` in board initialization.
}

/// Function used by board main.rs to set a reference to the writer.
pub unsafe fn set_debug_writer_wrapper(debug_writer: &'static mut DebugWriterWrapper) {
    DEBUG_WRITER = Some(debug_writer);
}

impl DebugWriterWrapper {
    pub fn new(dw: &'static DebugWriter) -> DebugWriterWrapper {
        DebugWriterWrapper {
            dw: MapCell::new(dw),
        }
    }
}

impl DebugWriter {
    pub fn new(
        uart: &'static dyn hil::uart::Transmit,
        out_buffer: &'static mut [u8],
        internal_buffer: &'static mut RingBuffer<'static, u8>,
    ) -> DebugWriter {
        DebugWriter {
            uart: uart,
            output_buffer: TakeCell::new(out_buffer),
            internal_buffer: TakeCell::new(internal_buffer),
            count: Cell::new(0), // how many debug! calls
        }
    }

    fn increment_count(&self) {
        self.count.increment();
    }

    fn get_count(&self) -> usize {
        self.count.get()
    }

    /// Write as many of the bytes from the internal_buffer to the output
    /// mechanism as possible, returning the number written.
    fn publish_bytes(&self) -> usize {
        // Can only publish if we have the output_buffer. If we don't that is
        // fine, we will do it when the transmit done callback happens.
        self.internal_buffer.map_or(0, |ring_buffer| {
            if let Some(out_buffer) = self.output_buffer.take() {
                let mut count = 0;

                for dst in out_buffer.iter_mut() {
                    match ring_buffer.dequeue() {
                        Some(src) => {
                            *dst = src;
                            count += 1;
                        }
                        None => {
                            break;
                        }
                    }
                }

                if count != 0 {
                    // Transmit the data in the output buffer.
                    if let Err((_err, buf)) = self.uart.transmit_buffer(out_buffer, count) {
                        self.output_buffer.put(Some(buf));
                    } else {
                        self.output_buffer.put(None);
                    }
                }
                count
            } else {
                0
            }
        })
    }

    fn extract(&self) -> Option<&mut RingBuffer<'static, u8>> {
        self.internal_buffer.take()
    }

    fn available_len(&self) -> usize {
        self.internal_buffer.map_or(0, |rb| rb.available_len())
    }
}

impl hil::uart::TransmitClient for DebugWriter {
    fn transmitted_buffer(
        &self,
        buffer: &'static mut [u8],
        _tx_len: usize,
        _rcode: core::result::Result<(), ErrorCode>,
    ) {
        // Replace this buffer since we are done with it.
        self.output_buffer.replace(buffer);

        if self.internal_buffer.map_or(false, |buf| buf.has_elements()) {
            // Buffer not empty, go around again
            self.publish_bytes();
        }
    }
    fn transmitted_word(&self, _rcode: core::result::Result<(), ErrorCode>) {}
}

/// Pass through functions.
impl DebugWriterWrapper {
    fn increment_count(&self) {
        self.dw.map(|dw| {
            dw.increment_count();
        });
    }

    fn get_count(&self) -> usize {
        self.dw.map_or(0, |dw| dw.get_count())
    }

    fn publish_bytes(&self) -> usize {
        self.dw.map_or(0, |dw| dw.publish_bytes())
    }

    fn extract(&self) -> Option<&mut RingBuffer<'static, u8>> {
        self.dw.map_or(None, |dw| dw.extract())
    }

    fn available_len(&self) -> usize {
        const FULL_MSG: &[u8] = b"\n*** DEBUG BUFFER FULL ***\n";
        self.dw
            .map_or(0, |dw| dw.available_len().saturating_sub(FULL_MSG.len()))
    }
}

impl IoWrite for DebugWriterWrapper {
    fn write(&mut self, bytes: &[u8]) -> usize {
        const FULL_MSG: &[u8] = b"\n*** DEBUG BUFFER FULL ***\n";
        self.dw.map_or(0, |dw| {
            dw.internal_buffer.map_or(0, |ring_buffer| {
                let available_len_for_msg =
                    ring_buffer.available_len().saturating_sub(FULL_MSG.len());

                if available_len_for_msg >= bytes.len() {
                    for &b in bytes {
                        ring_buffer.enqueue(b);
                    }
                    bytes.len()
                } else {
                    for &b in &bytes[..available_len_for_msg] {
                        ring_buffer.enqueue(b);
                    }
                    // When the buffer is close to full, print a warning and drop the current
                    // string.
                    for &b in FULL_MSG {
                        ring_buffer.enqueue(b);
                    }
                    available_len_for_msg
                }
            })
        })
    }
}

impl Write for DebugWriterWrapper {
    fn write_str(&mut self, s: &str) -> Result {
        self.write(s.as_bytes());
        Ok(())
    }
}

pub fn debug_print(args: Arguments) {
    let writer = unsafe { get_debug_writer() };

    let _ = write(writer, args);
    writer.publish_bytes();
}

pub fn debug_println(args: Arguments) {
    let writer = unsafe { get_debug_writer() };

    let _ = write(writer, args);
    let _ = writer.write_str("\r\n");
    writer.publish_bytes();
}

pub fn debug_slice(slice: &ReadableProcessSlice) -> usize {
    let writer = unsafe { get_debug_writer() };
    let mut total = 0;
    for b in slice.iter() {
        let buf: [u8; 1] = [b.get(); 1];
        let count = writer.write(&buf);
        if count > 0 {
            total += count;
        } else {
            break;
        }
    }
    writer.publish_bytes();
    total
}

pub fn debug_available_len() -> usize {
    let writer = unsafe { get_debug_writer() };
    writer.available_len()
}

fn write_header(writer: &mut DebugWriterWrapper, (file, line): &(&'static str, u32)) -> Result {
    writer.increment_count();
    let count = writer.get_count();
    writer.write_fmt(format_args!("TOCK_DEBUG({}): {}:{}: ", count, file, line))
}

pub fn debug_verbose_print(args: Arguments, file_line: &(&'static str, u32)) {
    let writer = unsafe { get_debug_writer() };

    let _ = write_header(writer, file_line);
    let _ = write(writer, args);
    writer.publish_bytes();
}

pub fn debug_verbose_println(args: Arguments, file_line: &(&'static str, u32)) {
    let writer = unsafe { get_debug_writer() };

    let _ = write_header(writer, file_line);
    let _ = write(writer, args);
    let _ = writer.write_str("\r\n");
    writer.publish_bytes();
}

/// In-kernel `println()` debugging.
#[macro_export]
macro_rules! debug {
    () => ({
        // Allow an empty debug!() to print the location when hit
        debug!("")
    });
    ($msg:expr $(,)?) => ({
        $crate::debug::debug_println(format_args!($msg));
    });
    ($fmt:expr, $($arg:tt)+) => ({
        $crate::debug::debug_println(format_args!($fmt, $($arg)+));
    });
}

/// In-kernel `println()` debugging that can take a process slice.
#[macro_export]
macro_rules! debug_process_slice {
    ($msg:expr $(,)?) => {{
        $crate::debug::debug_slice($msg)
    }};
}

/// In-kernel `println()` debugging with filename and line numbers.
#[macro_export]
macro_rules! debug_verbose {
    () => ({
        // Allow an empty debug_verbose!() to print the location when hit
        debug_verbose!("")
    });
    ($msg:expr $(,)?) => ({
        $crate::debug::debug_verbose_println(format_args!($msg), {
            // TODO: Maybe make opposite choice of panic!, no `static`, more
            // runtime code for less static data
            static _FILE_LINE: (&'static str, u32) = (file!(), line!());
            &_FILE_LINE
        })
    });
    ($fmt:expr, $($arg:tt)+) => ({
        $crate::debug::debug_verbose_println(format_args!($fmt, $($arg)+), {
            static _FILE_LINE: (&'static str, u32) = (file!(), line!());
            &_FILE_LINE
        })
    });
}

#[macro_export]
/// Prints out the expression and its location, then returns it.
///
/// ```rust,ignore
/// let foo: u8 = debug_expr!(0xff);
/// // Prints [main.rs:2] 0xff = 255
/// ```
/// Taken straight from Rust std::dbg.
macro_rules! debug_expr {
    // NOTE: We cannot use `concat!` to make a static string as a format argument
    // of `eprintln!` because `file!` could contain a `{` or
    // `$val` expression could be a block (`{ .. }`), in which case the `eprintln!`
    // will be malformed.
    () => {
        $crate::debug!("[{}:{}]", file!(), line!())
    };
    ($val:expr $(,)?) => {
        // Use of `match` here is intentional because it affects the lifetimes
        // of temporaries - https://stackoverflow.com/a/48732525/1063961
        match $val {
            tmp => {
                $crate::debug!("[{}:{}] {} = {:#?}",
                    file!(), line!(), stringify!($val), &tmp);
                tmp
            }
        }
    };
    ($($val:expr),+ $(,)?) => {
        ($($crate::debug_expr!($val)),+,)
    };
}

pub trait Debug {
    fn write(&self, buf: &'static mut [u8], len: usize) -> usize;
}

#[cfg(debug = "true")]
impl Default for Debug {
    fn write(&self, buf: &'static mut [u8], len: usize) {
        panic!(
            "No registered kernel debug printer. Thrown printing {:?}",
            buf
        );
    }
}

pub unsafe fn flush<W: Write + IoWrite>(writer: &mut W) {
    if let Some(debug_writer) = try_get_debug_writer() {
        if let Some(ring_buffer) = debug_writer.extract() {
            if ring_buffer.has_elements() {
                let _ = writer.write_str(
                    "\r\n---| Debug buffer not empty. Flushing. May repeat some of last message(s):\r\n",
                );

                writer.write_ring_buffer(ring_buffer);
            }
        }

        match DEBUG_QUEUE.as_deref_mut() {
            None => {
                let _ = writer.write_str(
                    "\r\n---| No debug queue found. You can set it with the DebugQueue component.\r\n",
                );
            }
            Some(buffer) => {
                let _ = writer.write_str("\r\n---| Flushing debug queue:\r\n");
                buffer.dw.map(|dw| {
                    dw.ring_buffer.map(|ring_buffer| {
                        writer.write_ring_buffer(ring_buffer);
                    });
                });
            }
        }
    } else {
        let _ = writer.write_str(
            "\r\n---| Global debug writer not registered.\
             \r\n     Call `set_debug_writer_wrapper` in board initialization.\r\n",
        );
    }
}