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
/*!
Utilities to inspect the data layout of objects.

This library is for debugging only because data layout of Rust is not be stabilized.
Please read [Data Layout - The Rustonomicon](https://doc.rust-lang.org/stable/nomicon/data.html) in detail.

# Examples

```rust
use binspect::binspect;

let s = "ABC";
binspect!(s);
binspect!(*s);
```

An example of output (depends on compilation and runtime environments):

```text
-----+ 0x7ffce3c8f7a0: &str = s
0000 | 49 03 b4 2f 2c 56 00 00 : 03 00 00 00 00 00 00 00
-----+ 0x562c2fb40349: str = *s
0000 | 41 42 43
```
*/

use std::any::type_name;
use std::io::{self, Write};
use std::mem;
use std::ptr;

#[inline]
#[doc(hidden)]
pub unsafe fn as_bytes_with_len<T: ?Sized>(t: &T, len: usize) -> &[u8] {
    let p = t as *const _ as *const u8;
    &*ptr::slice_from_raw_parts(p, len)
}

#[inline]
#[doc(hidden)]
pub fn as_bytes<T: ?Sized>(t: &T) -> &[u8] {
    unsafe { as_bytes_with_len(t, mem::size_of_val::<T>(t)) }
}

#[doc(hidden)]
pub struct Record<'a, T: ?Sized> {
    pub reference: &'a T,
    pub bytes: &'a [u8],
    pub sized: bool,
    pub source: &'a str,
    pub label: Option<&'a str>,
    pub file: &'a str,
    pub line: u32,
    pub column: u32,
}

#[doc(hidden)]
pub fn write_internal<W: Write, T: ?Sized>(
    mut w: W,
    record: &Record<T>,
    absolute: bool,
) -> Result<(), io::Error> {
    let width = 16;
    let center = width / 2;
    if absolute {
        writeln!(
            w,
            "{:p} : {} = {}",
            record.reference,
            type_name::<T>(),
            record.source
        )?;
    } else {
        writeln!(
            w,
            "-----+ {:p}: {} = {}",
            record.reference,
            type_name::<T>(),
            record.source
        )?;
    }
    for (i, x) in record.bytes.iter().enumerate() {
        if i % width == 0 {
            if i != 0 {
                writeln!(w)?;
            }
            if absolute {
                write!(w, "{:p} |", unsafe {
                    (record.reference as *const _ as *const u8).add(i)
                })?;
            } else {
                write!(w, "{:04x} |", i)?;
            }
        } else if i % center == 0 {
            write!(w, " :")?;
        }
        write!(w, " {:02x}", x)?;
    }
    if !record.bytes.is_empty() {
        writeln!(w)?;
    }
    Ok(())
}

#[inline]
#[doc(hidden)]
pub fn print_internal<T: ?Sized>(record: &Record<T>, absolute: bool) {
    write_internal(io::stdout().lock(), record, absolute).unwrap()
}

#[inline]
#[doc(hidden)]
pub fn eprint_internal<T: ?Sized>(record: &Record<T>, absolute: bool) {
    write_internal(io::stderr().lock(), record, absolute).unwrap()
}

#[macro_export]
#[doc(hidden)]
macro_rules! record {
    ($t: expr, $v: expr, $bs: expr, $sized: expr) => {{
        let bytes = $bs;
        $crate::Record {
            reference: $t,
            bytes,
            sized: $sized,
            source: stringify!($v),
            label: None,
            file: file!(),
            line: line!(),
            column: column!(),
        }
    }};
}

/// Prints the memory address and the hex representation of an object to stdout.
///
/// # Examples
///
/// ```
/// # use binspect::binspect;
/// let s = "ABC";
/// binspect!(s);
/// binspect!(*s);
/// ```
#[macro_export]
macro_rules! binspect {
    ($v: expr) => {{
        let t = &$v;
        let bs = $crate::as_bytes(t);
        $crate::print_internal(&$crate::record!(t, $v, bs, true), false);
    }};
    ($v: expr, $len: expr) => {{
        let t = &$v;
        let bs = $crate::as_bytes_with_len(t, $len);
        $crate::print_internal(&$crate::record!(t, $v, bs, false), false);
    }};
}

/// Prints the memory address and the hex representation of an object to stderr.
///
/// # Examples
///
/// ```
/// # use binspect::ebinspect;
/// let s = "ABC";
/// ebinspect!(s);
/// ebinspect!(*s);
/// ```
#[macro_export]
macro_rules! ebinspect {
    ($v: expr) => {{
        let t = &$v;
        let bs = $crate::as_bytes(t);
        $crate::eprint_internal(&$crate::record!(t, $v, bs, true), false);
    }};
    ($v: expr, $len: expr) => {{
        let t = &$v;
        let bs = $crate::as_bytes_with_len(t, $len);
        $crate::eprint_internal(&$crate::record!(t, $v, bs, false), false);
    }};
}

/// Writes the memory address and the hex representation of an object to [`std::io::Write`].
///
/// # Examples
///
/// ```
/// # use binspect::write_binspect;
/// let s = "ABC";
/// let mut buf: Vec<u8> = vec![];
/// write_binspect!(&mut buf, s).unwrap();
/// buf.clear();
/// write_binspect!(&mut buf, *s).unwrap();
/// ```
#[macro_export]
macro_rules! write_binspect {
    ($w: expr, $v: expr) => {{
        let t = &$v;
        let bs = $crate::as_bytes(t);
        $crate::write_internal($w, &$crate::record!(t, $v, bs, true), false)
    }};
    ($w: expr, $v: expr, $len: expr) => {{
        let t = &$v;
        let bs = $crate::as_bytes_with_len(t, $len);
        $crate::write_internal($w, &$crate::record!(t, $v, bs, false), false)
    }};
}